public class A { static String s1 = "I am A"; public static void main(String[] args) { String s2 = "I am A"; System.out.println(s1 == s2); } }
Above the outputs of the program "true". Both are two different identifiers / objects, how is the output true?
My understanding is that the JVM will create a different link for each object, if so, how is the result true?
Java manages the literal pool String. He repeats these literals whenever possible. Therefore, two objects are actually the same object String, but ==returns true.
String
==
I believe this is called string interning
== , . , , , , . , .
String s = new String("foo"); String t = new String("foo");
== false s.equals(t) true.
Java :
- , , , (ยง15.28) - "", , String.intern.
- , ... , String (.. - String, String) String, Strings , == , .
Strings
" " 13 " "... . :
" , String [JLS 15.28]. , String, , ... , -, . Interning , ... equals, ==, , ."
equals
... 30 - 31 .
. . equal ( String). , compareTo ( String), , .
, , , -, , .
, , . , , Java Puzzlers. - , , .