JavaTip : Null inside ‘if’ condition check

 

If condition evaluates for true or false. (boolean) in case if we use Boolean it could have null assignment as well.

Question : If true is not evaluated in if condition, then it should skip the block. Actually if it neither true or false then does it skip or gives exception.

public static void main(String[] args) {
    Boolean flag = null;
    if (flag)
        System.out.println(“reflect “);
}

Answer : It will give below exception

Exception in thread “main” java.lang.NullPointerException
    at TestMain.main(TestMain.java:9)

So solution is :

public static void main(String[] args) {
    Boolean flag = null;
    if (flag != null && flag)
        System.out.println(“reflect “);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s