这两个条件的区别?

Ami*_*Ami 4 java string if-statement

对不起,如果我的问题很愚蠢或无关紧要.但我只是想知道在这两种情况下会发生什么.

public class Test {
    public static void main(String[] args) 
    {
        String str="test";
        if(str.equals("test")){
            System.out.println("After");
        }
        if("test".equals(str)){
            System.out.println("Before");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

两者都只给出相同的结果.但我知道有一些原因.我不知道.这两个条件有什么区别?

Roh*_*ain 12

它们之间没有任何区别.许多程序员使用第二种方式只是为了确保他们没有得到NullPointerException.就这样.

    String str = null;

    if(str.equals("test")) {  // NullPointerException
        System.out.println("After");
    }
    if("test".equals(str)) {  // No Exception will be thrown. Will return false
        System.out.println("Before");
    }
Run Code Online (Sandbox Code Playgroud)