proudandhonour's answer is on the right track but won't work for all possible values of arrayName
, specifically that case in which arrayName
hasn't been defined and is null
. In that case, the code:
if(arrayName.length == 0)
System.out.println("array empty");
else
System.out.println("array not empty");
will fail with a NullPointerException.
TimeTravel's answer correctly tests for this case and correctly handles all possible values for arrayName
. The only downside is that his code is more verbose than it needs to be.
Java provides short circuit evaluation of Boolean expressions. Specifically the result of (false && xx)
is false
for all possible values of xx
. Therefore when evaluating the first operand of a Boolean &&
operator, the JVM will ignore the 2nd operand if the 1st evaluates to false.
Exploiting 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 the ternary operator which provides a mechanism for inlining if-then-else expressions. This can improve readability in some circumstances:
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)
);