hotandhonour answer is on the right track, but will not work for all possible values ββof arrayName , in particular, the case when arrayName not defined and null . In this case, the code:
if(arrayName.length == 0) System.out.println("array empty"); else System.out.println("array not empty");
with a NullPointerException. error NullPointerException. TimeTravel will correctly check this case and correctly process all possible values ββfor arrayName . The only drawback is that its code is more verbose than it should be.
Java provides an assessment of the short circuits of Boolean expressions. In particular, the result (false && xx) is false for all possible xx values. Therefore, evaluating the first operand of the && logical operator, the JVM will ignore the second operand if the first evaluates to false.
Using this, we can write:
if (arrayName != null && arrayName.length > 0) { System.out.println("The array length > 0"); } else { System.out.println("The array is null or empty"); }
There is also a ternary operator that provides a mechanism for building if-then-else expressions. This can improve readability in some cases:
System.out.println((arrayName == null) ? "The arrayName variable is null" : (arrayName.length < 1) ? "The array length is zero" : "The array length is " + String.valueOf(arrayName.length) );
source share