I have two strings,
String one = new String("word");
String two = new String("word");
Why does
System.out.println(one.equals(two));
Return true given that one and two are two different String objects.

Recommended Answers

mind that the == comparison in this specific case can't be relied upon to return false.
The runtime (and even the compiler in this simplified scenario) might determine to optimise things in such a way that both point to the same String as stored on the String constant pool in …

Jump to Post

All 2 Replies

Because they have same value if you set one to "word1" and two to "word2" it will return false.
If you want to compare one and two as objects try this:

String one = new String("word");
String two = new String("word");

System.out.println(one.equals(two));
System.out.println(one == two);

mind that the == comparison in this specific case can't be relied upon to return false.
The runtime (and even the compiler in this simplified scenario) might determine to optimise things in such a way that both point to the same String as stored on the String constant pool in permgen space.

Which teaches an important lesson: never rely on == in case of Strings :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.