0

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?

Community
  • 1
  • 1
commit
  • 4,777
  • 15
  • 43
  • 70

3 Answers3

5
"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():"")
Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
2

You will need to separate it (with brackets) so that it's read as a whole separate statement

System.out.println("ERROR HERE " + (abc != null ? abc.getS1() : ""));
Ross Drew
  • 8,163
  • 2
  • 41
  • 53
0

+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.

commit
  • 4,777
  • 15
  • 43
  • 70