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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With