Comparing two strings with “==”: when will it work?

后端 未结 3 566
生来不讨喜
生来不讨喜 2020-12-15 00:11

Say you have three strings,

String s1 = \"string one\";
String s2 = new String(\"string one\");
String s3 = \"string one\";

I know it is tr

相关标签:
3条回答
  • 2020-12-15 00:53

    Yes, that is true, because string literals are all interned. Read the documentation for String.intern() for more details.

    As a consequence, these are all the same object (and will compare equal with ==):

    s1
    s3
    s1.intern()
    s2.intern()
    s3.intern()
    
    0 讨论(0)
  • 2020-12-15 00:57

    above is HOW.

    and You should know why.

    A) string varaible declared in compile time ref to constant in constant pool

    B) string varaible result by method ref to Object in heap space .

    it all because JVM specfication and it's memory design.

    A) is because strings are immutable。when java compile class and jvm load class , jvm found one String variable declared by your in coding time。 cause it is constant, jvm put the constant to "Runtime Constant Pool" memory area. and, constant is unique.

    B) is verysimple. because jvm runtime variable use heap space.

    0 讨论(0)
  • 2020-12-15 00:59

    String literals are interned automatically. Hence s1 == s3 is true. Strings can either be created in the string constant pool or they can be created in the heap space. If you intern a string created in the heap, the string will be in the string constant pool.

    When you create a string literal (String s1 = "string one"), the string is created in the string constant pool. Additionally, the string constant pool doesn't store duplicates. So when you say,

    String s1 = "string one";
    String s3 = "string one";
    

    Both s1 and s3 will be pointing to the same instance of the string in the string constant pool. So s1.equals(s3) will be true. And s1 == s3 also is true; since both the pointers are the same.

    However, when you instantiate a string using the "new" constructor

    String s2 = new String("string one");
    

    then s2 is created in the heap space. The heap space is a different area of memory than the string constant pool

    So while s1.equals(s2) is true, s1 == s2 is false; since they will be pointing to different areas of memory.

    However, you can convert a string created using the "new" constructor to make it move to the string constant pool by invoking the intern() function. So s2.intern() will return a string in the string constant pool; although s2 was originally created in the heap.

    0 讨论(0)
提交回复
热议问题