There is this question that I am stuck on:
The answer is Version 3 but I am unsure why. I tried testing it with a test string assigned null, heres version 2 I used:
String str = null;
if (str != null || !str.equals("")){
System.out.println(str);
}
And it was giving me a null pointer exception for all versions except version 3 which I am really confused about.
CodePudding user response:
If you do any operation on a null String, it gives null pointer exception. ( Here you are comparing it with !str.equals(""))
Another point to note is : in || condition , if first condition is true, the second wont be evaluated.
whereas in && , if the first condition is false , the second condition is not evaluated.
For this reason, Both of these are called short circuit operators.
CodePudding user response:
The conditions in your if
-statements have to be checked. So, if you have str != null || !str.equals("")
in your if
-statement, then you will check str != null
and then check !str.equals("")
if the first statement is false
. Let's say that the string is null
. The first condition is false
and the second condition tries to check !str.equals("")
. Then you get a NullPointerException, because you can't compare null
to a string.
However, if you use str != null && !str.equals("")
, then str != null
will be checked first and the second statement !str.equals("")
will only be checked if the first one is true
. Meaning, the code will never get to !str.equals("")
if the string is null
. So, you never get the NullPointerException.
You can't use str.equals("")
because null
doesn't have an equals method. By using ==
you check the reference of your string. Everything that is null
has the same reference, so if your string is null
, then it will point to the null
reference, and ==
can be used to check that refernce.