Java Null Pointer Exception guard by using short circuit operators

Most common and horrible exception is NPE  null pointer exception.
Several time programmers evaluate the expression without providing the null guard on the object. It causes null pointer exception if by mistake null argument is passed.

public void doSomething(Object obj){
if(obj.isWoman){
Sysout.out.println(“do shopping”);
}else{
Sysout.out.println(“pay the bill “);
}
}

You are sure that the caller method will pass the some object when calling this method, but some if this method is passed with null value than null pointer exception will spoil the look and grace of your software. so to mitigate that, java short circuit are there for rescue. You just need to add the null gurad with short circuit operator and you have got protection against null.

public void doSomething(Object obj){
if((obj != null) && (obj.isWoman)){
Sysout.out.println(“do shopping”);
}else{
Sysout.out.println(“pay the bill “);
}
}

Here is how it works.
The && and || operators are short circuit operators. A short circuit operator is one that doesn’t
necessarily evaluate all of its operands. Take, for example, the operator &&. What happens when Java  executes the following code?

if (0 == 1 && 2 + 2 == 4) {
out.println(“This line won’t be printed.”);
}

You might expect Java to ask itself if 0 equals 1, and then ask if 2 + 2 equals 4. But with Java’s &&
operator, that’s not what happens. Instead, Java does the following:
Evaluate 0 == 1, discovering that 0 == 1 is false.
Realize that the condition (0 == 1 && whatever) can’t possibly be true, no matter what
the whatever condition happens to be.
Return false (without bothering to check if 2 + 2 == 4).
The condition (0 == 1 && whatever) has to be false, because 0 == 1 is false. (Remember,
the && operator wants both conditions, on its left and right sides, to be true.)
So when Java finds the value on the left side of an && operator to be false, then Java gives up and
declares the entire expression to be false. That’s called short circuit expression evaluation.  The same
kind of thing happens with the || operator (another short circuit operator) when the value on the
operator’s left side is true.

if (2 + 2 == 4 || 0 == 1) {
out.println(“This line will be printed.”);
}

Realize that the condition (2 + 2 == 4 || whatever) must be true, no matter what
the whatever condition happens to be.

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