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

后端 未结 3 652
生来不讨喜
生来不讨喜 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: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.

提交回复
热议问题