Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Java 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 program outputs "true". Both are two different identifiers/objects how the output is "true" ?

My understanding is that the JVM will create different reference for each object, if so how the output is true?

like image 436
novice Avatar asked Dec 13 '09 10:12

novice


People also ask

Can you == strings in Java?

To compare these strings in Java, we need to use the equals() method of the string. You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not.

What is string equality in Java?

In Java, the String equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are the same, it returns true. If all characters are not matched, then it returns false.

How do you check if a string is equal to another Java?

Java String equals() Method The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.


1 Answers

Java manages a String literal pool. It reuses these literals when it can. Therefore the two objects are actually the same String object and == returns true.

I believe this is called string interning

like image 131
Neil Foley Avatar answered Sep 27 '22 22:09

Neil Foley