String s1 == String s2 (true) but FieldOffset is different

后端 未结 4 1149
生来不讨喜
生来不讨喜 2021-02-08 13:47

As I am studying java, I have learned that the proper way to compare 2 Strings is to use equals and not \"==\". This line

static String s1 = \"a\";
static String s2          


        
4条回答
  •  不思量自难忘°
    2021-02-08 14:43

    String declared in Java code are automatically interned.

    So the result is the same as you would call String.intern() manually.

        String a = "aa";
        String b = new String(a);
        System.out.println("aa" == "aa");
        System.out.println(a == b);
        System.out.println(a.equals(b));
        System.out.println(a.intern() == b.intern());
    

    output:

    true

    false

    true

    true

提交回复
热议问题