Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

java - Difference between these two conditions?

Sorry if my question is silly or not it doesnot matter. But i just want to know what will happen in these two conditions.

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

Both are giving same results only. But i know there is some reasons.I dont know about that. What is difference between these two conditions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are no difference between them at all. Many programmers use the 2nd way just to make sure that they don't get a NullPointerException. That's all.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...