0
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.

subash poudel
  • 37
  • 1
  • 7
  • 1
    Yes, some strings are able to be equal without .equals(). However, in the general case, .equals() works for all strings. – NomadMaker Apr 04 '20 at 05:26
  • 1
    You can. If you want to know whether they are the same object (I even did in a piece of production code recently, but had to insert a comment clearly stating why I did). Only 99 times out of 100 we are comparing strings, we want to know whether they are equal. String objects are value objects, so we should concern ourselves with equality, not object identity. – Ole V.V. Apr 04 '20 at 05:36
  • There is a lot of explanation in this question: [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) I wonder if it answers yours too? – Ole V.V. Apr 04 '20 at 05:44
  • 2
    Does this answer your question? [What is the difference between == and equals() in Java?](https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java) – Nikos Tzianas Apr 04 '20 at 05:46

3 Answers3

6

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Kourpa
  • 86
  • 2
2

"==" 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.

Anoop R Desai
  • 712
  • 5
  • 18
Dhruv Saksena
  • 209
  • 2
  • 13
1

== 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