Java ยท Chapter 12 of 42

Java Booleans

A boolean variable holds one of two values: true or false. Booleans are the result of comparison and logical expressions, and control the flow of if statements and loops.

Unlike some languages, Java does not treat integers as true/false โ€” a boolean must always be explicitly true or false.

Syntax
boolean isTrue = true;
boolean result = (5 > 3);

Boolean expressions

Comparisons like a > b, or logical combinations like a && b, always evaluate to a boolean value.

Boolean in control flow

if statements and loop conditions require a boolean expression; you cannot use an int in place of a boolean like in C.

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    boolean isJavaFun = true;
    boolean result = (10 > 5);
    System.out.println(isJavaFun);
    System.out.println(result);
  }
}
Output
true
true

Both a literal boolean and a comparison expression print as true or false.

Key points

  • boolean holds only true or false.
  • Comparisons produce boolean results.
  • if and while require an actual boolean expression.
  • Java does not auto-convert int to boolean.
๐Ÿ’ก Note: This strict boolean typing prevents a common class of bugs found in C, like `if (x = 5)` typos.

๐Ÿ“ Quick Quiz

1. What are the only two boolean values?

2. Can you use an int directly as a condition in Java's if statement?

3. What does 10 > 5 evaluate to?