Java Tutorial
Java Booleans
boolean is true or false. Comparisons produce booleans. Conditions consume them.
true and false
A boolean is one of two values. Print it and you see true or false, not 1 and 0.
Example
public class Main {
public static void main(String[] args) {
boolean ready = true;
System.out.println(ready);
System.out.println(3 > 1);
}
}and, or, not
&& is and. || is or. ! is not. Use them to combine tests.
Example
public class Main {
public static void main(String[] args) {
double ph = 7.2;
boolean ok = ph >= 7.0 && ph <= 7.4;
System.out.println(ok);
}
}Conditions consume booleans
if (ready) is enough. You do not write if (ready == true) — the extra comparison is noise. To test the false case, flip it with !: if (!ready).
Example
public class Main {
public static void main(String[] args) {
boolean raining = true;
boolean haveUmbrella = false;
boolean getWet = raining && !haveUmbrella;
System.out.println(getWet); // true
}
}Storing a condition in a well-named boolean (like getWet) makes the followingif read like plain English. A good name often replaces a comment.
Try It Yourself
Exercise: Set int age = 15 and print whether the person is a teenager (13 to 19 inclusive) as a single boolean expression.
Show solution
int age = 15;
boolean teen = age >= 13 && age <= 19;
System.out.println(teen); // trueBoth halves must be true, so && is the right join. There is no 13 <= age <= 19 in Java — you write the two comparisons out.
Key Takeaways
- A
booleanistrueorfalse; comparisons produce one. - Combine with
&&,||, and!. - Write
if (ready), notif (ready == true). - Java has no
a < b < c— writea < b && b < c.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.
Chemistry
Within a pH window
A buffer is useful in a range. Two comparisons joined with && produce one boolean: in range or not.
Example
public class Main {
public static void main(String[] args) {
double ph = 7.2;
boolean ok = ph >= 7.0 && ph <= 7.4;
System.out.println(ok);
}
}