String s1="bool";
String s2="bool";
System.out.println((s1==s2)+" bool");
System.out.println(s1==s2+" bool");
Can you help me why are different output.
String s1="bool";
String s2="bool";
System.out.println((s1==s2)+" bool");
System.out.println(s1==s2+" bool");
Can you help me why are different output.
In the first scenario, you have 2 string compared, then " bool"
appended.
In the second scenario, you have " bool"
appended to s2
first.
Here it is in expanded form:
1.
boolean b = s1==s2;
String result = b + " bool";
2.
String s = s2 + " bool";
boolean result = s1 == s;
To learn more about Order of operations in Java, visit This link.
In first case (s1==s2) + " bool"
:
(s1 == s2)
evaluates to true (since both are String literals).true + "bool"
this is a concatenation, where true
is converted to "true"
then it's appended to " bool"
. The result is "true bool"
.In second case s1==s2+" bool"
:
+
has higher priority than ==
, thus s2+" bool"
evaluates first to "boolbool"
.s1 == "boolbool"
is evaluated which obviously evaluates to false
.In the first line (s1==s2)+" bool"
, you are explicitly comparing s1
to s2
first (by putting parenthesis around the expression) and adding bool
to the result. This will compare s1
to s2
, or bool
== bool
and then add the String bool
to the resultant boolean expression.
In the second line, there are no parenthesis around the comparison expression and therefore the plus operation happens before the comparison. Based on the rules of Java, it will evaluated as if written as s1== (s2+" bool")
. This will compare s2 + " bool"
or bool bool
, to s1
, bool
.
In short, the first expression will result in a String, while the second, will result in a boolean.
System.out.println(s1==s2+" bool");
Concatenation, +
, takes precedence over comparison, ==
, so concatenation evaluates first.
System.out.println((s1==s2)+" bool");
Grouping, ()
, takes precedence over concatenation, +
, so comparison evaluates first.
More visual notation is:
System.out.println((s1 == s2) + " bool");
System.out.println(s1 == (s2+" bool"));
Important note: strings must be compared with equals
method:
s1.equals(s2)
Without the parenthesis to control the order of operation, this
System.out.println(s1 == s2 + " bool");
Evaluates like
System.out.println(s1 == (s2 + " bool"));
And thus you get false
. One way to mitigate this type of issue is to use formatted output. Something like
System.out.printf("%b bool%n", s1 == s2); // <-- %b is for a boolean
Of course, it would behave the same way if s1
and s2
were primitive values.
(s1==s2) +" bool"
checks for s1 ansd s2 are same. If it's same or not same , it would print the result (in our case it's true
) plus the string bool
s1==s2 + " bool"
check fors1
and s2+bool
are same (ie, bool
== bool bool
). In our case, it's false.
The reason is that operator +
has precedence over operator ==
(check this). SO in the second case, you are first computing a string addition resulting on "bool bool" and then comparing it to S1.