Box b1 = new Box();
Box b2 = b1;
Here b1 and b2 refers to same object. So in case of 2 String objects why can't we use ==
to compare them instead of .equals()
methods.
Box b1 = new Box();
Box b2 = b1;
Here b1 and b2 refers to same object. So in case of 2 String objects why can't we use ==
to compare them instead of .equals()
methods.
There is no difference really. When you use ==
to compare objects, you're comparing their memory addresses, not their values. In your example, doing b1 == b2
will return true because they are the same object. However if you instead did:
Box b1 = new Box();
Box b2 = new Box();
Now if you compare them with ==
it will return false despite the fact that the objects are exactly the same. Same goes for Strings.
"==" compares Object references with each other and not their literal values. If both the variables point to same object, it will return true. So,
String s1 = new String("hello");
String s2 = new String("hello");
Here
s1==s2
, will return false
as both are different objects.
When you use equals()
, it will compare the literal values of the content and give its results.
== Compares memory address while .equals() compares the values
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
Output:
False
True