为什么抛出空指针异常?

com*_*mit 0 java nullpointerexception

我已经在这里问了一个矛盾问题 为什么这不会抛出NullPointerException?

但这是我想知道的不同类型和行为之一,请查看下面的示例

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;
    }


}
Run Code Online (Sandbox Code Playgroud)

所以在这里,场景2可以正常工作但是当我在场景1中使用其他字符串连接尝试它时它为什么不起作用?

Eya*_*der 5

"ERROR HERE " + abc!=null?abc.getS1():"" 
Run Code Online (Sandbox Code Playgroud)

相当于

("ERROR HERE " + abc!=null)?abc.getS1():""
Run Code Online (Sandbox Code Playgroud)

(从不评估为假,因此你获得NPE)

你的意思是:

"ERROR HERE " + (abc!=null?abc.getS1():"")
Run Code Online (Sandbox Code Playgroud)

  • 运算符优先级规则在这里:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html (3认同)