Moon Light Box

Time is Money

Java - NULL

| Comments

We usually use below statements to check a variable whether it is null or not.

This is using C language concept and it is a worng statement.

if (food == "") {
    // do something here

}

This is using Java API equals, but it is still a worng statement.

if (food.equals("")) {
    // do something here

}

And this is the same situation.

if (food != null) {
    // do something here

}

Why? Because food is possible not to be an instance when checking.

Actually, it will cause NullPointerException and we always forget using try-catch to handle.

To avoid NPE, we must modify statement in a better way.

if ("".equals(food)) {
    // do something here

}

or

if (null != food) {
    // do something here

}

Comments

comments powered by Disqus