String s1="hi";
String s2="hi";
boolean b1 = true;
boolean b2 = false;
(1) System.out.println(s1==s2); //true
(2) System.out.println(s1==s2 + s1==s2); //false
(3) System.out.println(s1==s2+ " " + s1==s2); //false
(4) System.out.println(b1+b2); //error : bad operand types
(5) System.out.println(b1 + " " + b2); //true false
(6) System.out.println(true +" "+ s1==s2); //false
- What is the difference between (2) & (4)?
- What is the difference between (3) & (5)?
- Why it gives result false in (3) & (6)?
Except for 4, all of these rely on operator precedence.
And in Java, +
has precedence over ==
.
Which means 2 actually "reads":
s1 == ((s2 + s1) == s2)
Therefore the right side operand of the first ==
is a boolean expression which compares two object references to one another (the fact that they are both String
s here is irrelevant) and here they are not the same. Hence the right side operand is boolean false
.
But since the left side operand is a String
, and since ==
is not applicable to operands String
and boolean
, this gives a compile error. JLS, section 15.21:
The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error.
If this really compiles for you, you are using a buggy Java compiler which autoboxes the right side operand to a Boolean
, which it shouldn't. Let me guess: Eclipse's ECJ?
4 is an error since the +
operator doesn't accept boolean
s as operands.
3 reads nearly the same as 2, except that this time it is s2 + " " + s1
which is (attempted to be) compared to s2
. It fails to compile for the same reason.
In 5, booleans are autoboxed because of string concatenation.
6 again relies on the operator priority mentioned in 2; this time it is string true + " " + s1
which is (reference) compared with s2
(and that gives false). See 5 for what happens to true
.
What is the difference between (2) & (4)?
Your second statement simply becomes System.out.println(hi == hihi ==hi);
and the answer is false but your 4th statement is straight forward
What is the difference between (3) & (5)?
This is same as your previous question
Why it gives result false in (3) & (6)?
Your 3rd statement follows the above where as 6th statement convers as System.out.println("true hi" =="hi");
and output is false
P.S : '+' operator comes first in operator precedense
1) What is the difference between (2) & (4) ?
Ans :- == has more precedence over + so 2nd is actually reads as a " s1 == ((s2 + s1) == s2) " where we can't even imagine about ( boolean+boolean )
2) What is the difference between (3) & (5)?
Ans:- 3rd won't even compile and 5th is simple put values b1=true and b2=false and simple String concatenation performed