-1

When is a == b is true but a.equals(b) is false, or vice versa?

I know that equals() is used to compare the values of the Strings and the == to check if two variables point at the same instance of a String object. But in which case will these two be different ?

nbro
  • 15,395
  • 32
  • 113
  • 196
MagicBeans
  • 343
  • 1
  • 5
  • 18
  • 1
    "when a==b is true but a.equals(b) is false" no, properly implemented `equals` method always returns true for `x.equals(x)`, "or vice versa" read two same strings from file and compare them. – Pshemo Jan 05 '16 at 18:49

3 Answers3

7

Consider this code,

String str1 = "ABC";
String str2 = new String("ABC");
System.out.println(str1==str2); // false
System.out.println(str1.equals(str2)); //true

The reason for this is that when you write String str1="ABC" this string is kept in string pool and String str2 = new String("ABC") creates the new object in heap and it won't check the string pool if it is already present. But as contents of the both string are same, equals method returns true.

Mandeep Rajpal
  • 1,667
  • 2
  • 11
  • 16
2

While most compilers will intern strings so that

a = "Foo";
b = "Foo";
System.out.println(a == b);

will generally print True, you can always construct strings that you know to be identical but the compiler does not:

a = "Foo";
b = "Fo";
c = "o";
System.out.println((a == b + c));

This will just about always print False, while a.equals(b + c) will always be True. Basically, there is no guarantee that strings with the same content will point to the same object.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

Strings are immutable in nature. So, when we do this,

String a1 = "a";
String a2 = "a";

Actually in memory, only one instance of String "a" is created. Both a1 and a2 will point to the same instance.

That's why, a1 == a2 and a1.equals(a2) are both true.

But, in this,

String a1 = "a";
String a2 = new String("a");

We created a new String instance explicitly. So, a1.equals(a2) will be true. But a1 == a2 will not.

Msp
  • 2,493
  • 2
  • 20
  • 34