Basic Java question: String equality

前端 未结 5 1269
孤独总比滥情好
孤独总比滥情好 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:36

    == checks that the variables are pointing at the exact same instance of an object. The two string literals you have created point to the same place in memory and therefore the are equal. String literals are interned so that the same string literal is the same object in memory.

    If you were to do

    String s = new String("foo");
    String t = new String("foo");
    

    Then == would return false and s.equals(t) would return true.

提交回复
热议问题