In Java, the ==
operator compares object references rather than the content of the objects. In the code snippet you provided
public static void main(String[] args) {
System.out.println("Hello" == new String("Hello"));
}
Here’s a breakdown of what’s happening:
"Hello"
: This is a string literal. In Java, string literals are interned, meaning they are stored in a common pool and reused.new String("Hello")
: This creates a newString
object with the same content as the string literal, but it is a different object in memory.
When you use ==
to compare these two, you're comparing their memory addresses (references), not their contents. Since "Hello"
and new String("Hello")
are different objects, their references are different, and the ==
comparison returns false
.
Therefore, the output of the program will be
false
If you want to compare the actual contents of the strings, you should use the .equals()
method:
public static void main(String[] args) {
System.out.println("Hello".equals(new String("Hello")));
}
This will compare the contents of the strings, and in this case, it will return true
.