&& (AND) and || (OR) in IF statements && (AND) and || (OR) in IF statements java java

&& (AND) and || (OR) in IF statements


No, it will not be evaluated. And this is very useful. For example, if you need to test whether a String is not null or empty, you can write:

if (str != null && !str.isEmpty()) {  doSomethingWith(str.charAt(0));}

or, the other way around

if (str == null || str.isEmpty()) {  complainAboutUnusableString();} else {  doSomethingWith(str.charAt(0));}

If we didn't have 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code.


Java has 5 different boolean compare operators: &, &&, |, ||, ^

& and && are "and" operators, | and || "or" operators, ^ is "xor"

The single ones will check every parameter, regardless of the values, before checking the values of the parameters.The double ones will first check the left parameter and its value and if true (||) or false (&&) leave the second one untouched.Sound compilcated? An easy example should make it clear:

Given for all examples:

 String aString = null;

AND:

 if (aString != null & aString.equals("lala"))

Both parameters are checked before the evaluation is done and a NullPointerException will be thrown for the second parameter.

 if (aString != null && aString.equals("lala"))

The first parameter is checked and it returns false, so the second paramter won't be checked, because the result is false anyway.

The same for OR:

 if (aString == null | !aString.equals("lala"))

Will raise NullPointerException, too.

 if (aString == null || !aString.equals("lala"))

The first parameter is checked and it returns true, so the second paramter won't be checked, because the result is true anyway.

XOR can't be optimized, because it depends on both parameters.


No it will not be checked. This behaviour is called short-circuit evaluation and is a feature in many languages including Java.