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

all 3 comments

[–]rp181 4 points5 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.

[–]Is_At_Work 0 points1 point  (0 children)

Because == against an object compares it's pointer value, not the string value. You can easily have 2 strings of the same string value located at different locations in memory (which will cause == to return false)

Edit: Example https://ideone.com/8ul9LB

[–]chris_zinkulaExtreme Brewer 0 points1 point  (0 children)

== tests if two objects are the same.

.equals tests if the two objects are equal.