I have already asked one of the contradiction question here Why is this not throwing a NullPointerException?
But this is one of different type and behavior I want to know about, please look for my example below
package com;
public class test {
public static void main(String[] args) {
Abc abc = null;
//Scenario 1
System.out.println("ERROR HERE " + abc!=null?abc.getS1():""); //This is throwing null pointer exception
//Scenario 2
String s1 = abc!=null?abc.getS1():"";
System.out.println("This is fine " + s1);
}
}
class Abc {
String s1;
public String getS1() {
return s1;
}
public void setS1(String s1) {
this.s1 = s1;
}
}
So here Scenario 2 will work fine but why it is not working when I am trying it with other string concatenation in Scenario 1 ?
"ERROR HERE " + abc!=null?abc.getS1():""
is equivalent to
("ERROR HERE " + abc!=null)?abc.getS1():""
(which never evaluates to false and therefore you get NPE)
You meant:
"ERROR HERE " + (abc!=null?abc.getS1():"")
您将需要将其分开(用方括号括起来),以便将其作为一个完整的单独语句阅读
System.out.println("ERROR HERE " + (abc != null ? abc.getS1() : ""));
+1 vote for Eyal and Ross.
After seeing both that answer and comment by Tenner, I have concluded that,
it is throwing nullPointerException
because != operator priority is lower than + .
So compiler is calling toString
method of Abc class and hence abc is null it is throwing nullPointerException
.
Please correct me if I am wrong.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.