SwadhyAI Notes

All Java notes

Java booleans

›Short versionOpen if you only have a minute.
  • A boolean is true or false. It is not 1 or 0, and if (1) does not compile.
  • A comparison such as age >= 18 produces a boolean. You can store that result.
  • = assigns. == compares. if (ready = true) stores true and the branch is taken.
  • && skips its right side when the left is false. || skips its right side when the left is true.
  • Put the null check on the left of &&. The equals call on the right then does not run on null.

A is the type a condition actually wants. You either write the literal, or you write an that computes one. The second form is most of what programs do with the type.

java
boolean isJavaFun = true;
boolean isFishTasty = false;
int age = 20;
boolean isAdult = age >= 18;

System.out.println(isJavaFun);
System.out.println(isAdult);

Both prints are true. age >= 18 is a . The int is not converted into a boolean by wishful thinking. The comparison is what produces the boolean, and isAdult stores it. Later code can test isAdult without repeating the comparison.

Combining tests, and the side that is skipped

A joins tests you would otherwise nest. evaluation is the part that changes which code runs, not only which value you get.

java
int age = 20;
boolean hasLicense = true;
System.out.println(age >= 18 && hasLicense);
System.out.println(age < 13 || hasLicense);
System.out.println(!hasLicense);

What the console shows

true
true
false

A store that looks like a test

On an int, if (age = 18) does not compile, because the assignment's value is an int. On a boolean, the same shape compiles. That is the dangerous case.

java
boolean ready = false;
if (ready = true) {
    System.out.println("runs");
}
System.out.println(ready);

The program prints runs and then true. The condition assigned true to ready and used that new value as the test. if (ready == true) would have compared. if (ready) is the same comparison without the extra == true, and it does not assign.

The branch that uses these values is the next page, Java if...else. The operators that produce them are on Java operators.

boolean ready = false; then if (ready = true). Does the body run? What is ready afterward?

The body runs. The single = stores true, and a boolean assignment is itself a boolean expression, so the if sees true. After the statement, ready is true even though it started false. == would have left it false and skipped the body.