Java core question: string equality

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?

+5
source share
5 answers

Java manages the literal pool String. He repeats these literals whenever possible. Therefore, two objects are actually the same object String, but ==returns true.

I believe this is called string interning

+20
source

== , . , , , , . , .

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

== false s.equals(t) true.

+6

Java :

- , , , (ยง15.28) - "", , String.intern.

+5

- , ... , String (.. - String, String) String, Strings , == , .

" " 13 " "... . :

" , String [JLS 15.28]. , String, , ... , -, . Interning , ... equals, ==, , ."

... 30 - 31 .

+5

. . equal ( String). , compareTo ( String), , .

, , , -, , .

, , . , , Java Puzzlers. - , , .

+1

All Articles