I am messed up with the below Code Cannot able to distinguish between the two code Snippets:
String Check=null;
if(Check!=null && Check.isEmpty()){
System.out.println("Get Inside");
}
Above Code works Fine and Print the Message.
if(Check==null && Check.isEmpty()){
System.out.println("get Inside")
}
this code will throw the NullPointerException.Not able to distinguish between this Code Please Help.
The && operator is a short-circuit, it doesn't evaluate the right hand side if it's not necessary. In this case, it's necessary:
if(Check==null && Check.isEmpty()){
System.out.println("get Inside")
}
If Check is null (and that's the case), you'll continue to check the condition after the &&, and you get Check.isEmpty(). Since Check is null, it's like null.isEmpty() which is a NEP.
Why?
When two expressions have && between them, if the first one is false, the answer will always be false and the other side won't be checked, but when the first is true, you have to continue and check the other side to know if all the expression should be evaluated to true or false.
But when you have:
if(Check!=null && Check.isEmpty()){
System.out.println("get Inside")
}
Then the right side won't be reached, since it's redundant to check it. You already got false, and it doesn't matter if you get true or false on the right side, the result will be false since this is an AND (FALSE && WHATEVER = FALSE). So why checking?
This link might help you.
(I recommend you to follow Java Naming Conventions and make the variables begin with a lowercase).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With