0

I am trying to understand the equality (==) equals() method but couldn't reason out this behavior. Can someone explain this behavior with the following println statements.

String a="Hai";
String b="Hai";
int c=5, d=5;

System.out.println("Check1 : " + (c==d)); //prints  "Check1 : true"

System.out.println("Check2 : " + a==b); //prints false. It didn't print the string "Check2 : "

System.out.println("Check3 : " +a.equals(b)); //prints "Check3 : true"

System.out.println(" c==d : " + c==d);   //compile time error - incomparable types: java.lang.String and int

Many Thanks.

GnyG
  • 151
  • 1
  • 2
  • 11

3 Answers3

6

It's because of orders of operations, in this part:

" c==d : " + c == d  

There are no parenthesis, so the compiler goes:

(" c==d : " + c) == d  

And you get an error because string == int is not defined. It's the same idea for the other example:

"Check2 : " + a == b → ("Check2 : " + a) == b → "Check2 : Hai" == "Hai" → false
Maljam
  • 6,244
  • 3
  • 17
  • 30
1

You need to add parenthesis before doing the integer operation

Do in this way :

System.out.println(" c==d : " + (c==d));
0

I'll try to explain it one by one.

System.out.println("Check1 : " + (c==d));

This will print true as it is int comparison and both c as well as d has the same value.

System.out.println("Check2 : " + a==b);

It is printing false because concatenated String Check2 : + a is not equals to String b. If you change a==b to (a==b) then it will start printing true as both a and b points to the same reference in the String Pool.

System.out.println("Check3 : " + a.equals(b));

This will print true because the content of String a is equal to the content of String b.

System.out.println(" c==d : " + c==d);   

This will throw an error as it will be parsed as String c==d concatenated with int c converted to String (Because of Overload) is equal to int d and as you know we can't compare String with Integer and hence this will throw an error.

user2004685
  • 9,548
  • 5
  • 37
  • 54