1. Booleans and Boolean Operators
Declaring a boolean
The boolean variable type stores either true or false, and it can be nothing else. Unlike in languages like C or C++, in Java, a boolean cannot be 0, 1, 4.2, "Hello", etc. You can declare a boolean like so:
public class MyProgram { public static void main(String[] args) { boolean c = true; System.out.println(c); //outputs true } }
The boolean NOT (!) operator
To invert (flip) a boolean, put an exclamation mark in front of the variable or expression:
public class MyProgram { public static void main(String[] args) { System.out.println(!true); //prints false System.out.println(!false); //prints true System.out.println(!!true); //prints true System.out.println(!!!true); //prints false } }
Boolean operators AND and OR (&& ||)
The AND (&&) and OR (||) operators require two booleans on either side. In the case of the AND, if both sides are true then the expression is true. In the case of the OR, if either side is true, then the expression is true:
public class MyProgram { public static void main(String[] args) { System.out.println(true && false); //false System.out.println(true && true); //true System.out.println(false && false); //false System.out.println(true || false); //true System.out.println(true || true); //true System.out.println(false || false); //false } } //Note that A AND B evaluates to the same as B AND A //Also A OR B evaluates to the same as B OR A
Note on operator order of && and ||: AND is run before OR
Advanced students should note that these operators are short circuiting. If the left side of an AND is false, Java will not even try to evaluate the right side and will immediately return false. If the left side of an OR is true, Java will immediately return true without evaluating the right side. We will discuss short circuiting more later.