简体   繁体   English

为什么抛出空指针异常?

[英]Why is this throwing null pointer exception?

I have already asked one of the contradiction question here Why is this not throwing a NullPointerException? 我已经在这里提出了一个矛盾问题, 为什么这不引发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 ? 因此,这里的方案2可以正常工作,但是当我与方案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) (它永远不会评估为false,因此您会得到NPE)

You meant: 你的意思是:

"ERROR HERE " + (abc!=null?abc.getS1():"")

您将需要将其分开(用方括号括起来),以便将其作为一个完整的单独语句阅读

System.out.println("ERROR HERE " + (abc != null ? abc.getS1() : ""));

+1 vote for Eyal and Ross. 为Eyal和Ross +1票。

After seeing both that answer and comment by Tenner, I have concluded that, 在看到Tenner的回答和评论后,我得出结论,

it is throwing nullPointerException because != operator priority is lower than + . 它抛出nullPointerException因为!=运算符优先级低于+

So compiler is calling toString method of Abc class and hence abc is null it is throwing nullPointerException . 因此,编译器正在调用Abc类的toString方法,因此abcnull它将nullPointerException

Please correct me if I am wrong. 如果我错了,请纠正我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM