views:

66

answers:

3

An array of Strings, names, has been declared and initialized. Write the statements needed to determine whether any of the the array elements are null or refer to the empty String. Set the variable hasEmpty to true if any elements are null or empty-- otherwise set it to false.

   hasEmpty=false;
   for (int i=0;i<names.length;i++)
   if (names[i].trim().equals("") || names[i]==null)
   hasEmpty=true;

Whats wrong with my code?

+1  A: 

Calling trim() first will result in a NullPointerException should a member of the array be null. Reverse the order of the conditions - the short-circuiting nature of || will then ensure that trim is only called on a real String object.

Ani
A: 

Consider names[i].trim().

When names[i] is a String, you really have something like someString.trim() which works fine.

When names[i] is a null, however, you really have something like null.trim(). You've already discovered that null doesn't allow a trim() method. (In fact, I'm not even really sure what 'null' is.)

Therefore, you must check for null before you invoke trim().

When you have a && b, where a and b are expressions, the checks are made left-to-right and the parser stops as soon as the issue is settled. So for the logical and operator (&&), if a is false then b is never checked. This is what allows

if (a != null && a.trim().length() > 0) { ... }

to work. if a is null, the a.trim() part is not executed since it would be pointless from a logical point of view; the value of the conditional has been decided.

Similarly for

if (a == null || a.trim().length() == 0) { ... }

if a is null then the a.trim() part is never performed and we don't get an error.

Tony Ennis
@Tony - *" In fact, I'm not even really sure what 'null' is."* - See http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.1
Stephen C
hehe I looked it up immediately upon posting. It was pretty much what I thought but reading it is good.
Tony Ennis
A: 

You can use the Apache Commons Lang's isBlank() to check a String:

if (StringUtils.isBlank(names[i]) {
    ...
}

StringUtils.isBlank is checking if the String is null or empty (i.e. if it is equals to "" when all blank characters are removed).

codaddict