Basic Java question: String equality

前端 未结 5 1268
孤独总比滥情好
孤独总比滥情好 2020-12-19 11:53
public class A {

    static String s1 = \"I am A\";

    public static void main(String[] args) {
        String s2 = \"I am A\";
        System.out.println(s1 == s         


        
5条回答
  •  伪装坚强ぢ
    2020-12-19 12:13

    You aren't comparing the content of the strings. You are only comparing the object's references. You should use the equal method (which is a member of the String class). Either that or you can use the compareTo method (also under the same String class) to check if the return value is zero.

    Please note the text above was more of a strong suggestion to the orginal state of the question as that it appeared the OP was unaware of the actual process going on behind the scenes.

    The other guys suggesting internalling was right. To answer this question I didn't have enough time to go to the Java Puzzlers book. I did suspect something about setting the same reference at compile time, but I didn't know how to find a reference to that either.

提交回复
热议问题