What are the boolean values ​​in Java

What are boolean expressions?

Boolean is a primitive data type that can take the values ​​or. It mainly serves to differentiate whether a condition applies or not and, as a result, whether and which instructions are executed. The syntax of the case distinctions themselves is covered in the articles on the if branch and switch-case branch.

boolean b = true; if (b) {System.out.println ("b is true"); }

Boolean expressions are often composed so that several Boolean values ​​are evaluated together.

boolean a = false; boolean b = true; System.out.println ("a: false, b: true, (a && b) -" + (a && b)); // false System.out.println ("a: false, b: true, (a || b) -" + (a || b)); // true a = true; b = true; System.out.println ("a: true, b: true, (a && b) -" + (a && b)); // true System.out.println ("a: true, b: true, (a || b) -" + (a || b)); // true a = false; b = false; System.out.println ("a: false, b: false, (a && b) -" + (a && b)); // false System.out.println ("a: false, b: false, (a || b) -" + (a || b)); // false

When evaluating the expressions using the OR operator (), the order must be taken into account, since Java supports a mechanism that is called Short-circuit evaluation is known. This means that, starting from the left, the individual expressions of a compound expression are only evaluated if the result of the overall expression is not yet clearly established.

int i = 0; String s = null; (i == 0 || s.length ()! = 0) // true (s.length ()! = 0 || i == 0) // java.lang.NullPointerException (i == 0 && s. length ()! = 0) // java.lang.NullPointerException (s.length ()! = 0 && i == 0) // java.lang.NullPointerException

The above example demonstrates what has been said: Two variables are declared, of which the string is also initialized. If you use its method, one is thrown.
In the first example, by using the OR operator, after evaluating the first partial expression, it is certain that the overall expression will deliver in any case. The second partial expression is therefore no longer evaluated at all. In the second example, the is queried as the first partial expression and therefore an exception is thrown. With the two expressions that follow, it is absolutely necessary to evaluate the value of the total expression in order to make a final statement on the basis of the AND operator, which leads to the error mentioned.