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

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.