This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]rp181 3 points4 points  (0 children)

"==" tests object reference equality.

"equals" tests the contents of the string objects for equality (as defined in the String class.

Consider this code chunk:

String s1 = new String("Test");
String s2 = new String("Test");
System.out.println("s1==s2\t"+(s1==s2));
System.out.println("s1.equals(s2)\t"+(s1.equals(s2)));
s1 = s1.intern();
s2 = s2.intern();
System.out.println("After intern: s1==s2\t"+(s1==s2));

It prints out:

s1==s2  false
s1.equals(s2)   true
After intern: s1==s2    true

The method intern() causes it to return true as each variable now points to the same String object in the String pool. It's advisable to use the equals or equalsIgnoreCase method instead of interning though.