Why the below statement in Java prints "2 + 2 = 22"
System.out.println("2 + 2 = " + 2 + 2);
Why the below statement in Java prints "2 + 2 = 22"
System.out.println("2 + 2 = " + 2 + 2);
because java '+' operator is first assigned on the left : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
so
"2 + 2 = " + 2 + 2
is first evaluated to
"2 + 2 = 2" + 2
and then
"2 + 2 = 22"
Precedence rules can be overridden by explicit parentheses, you want
"2 + 2 = " + (2 + 2)
You have to give the precedence order here. This way your brackets having the summation is executed first and then the concatenation. Otherwise it is evaluating from the left to right. Left most literal is a String
and you concatenate your numbers to the String
literal leading to the above result which is "2 + 2 = 22"
.
System.out.println("2 + 2 = " + (2 + 2));
If either of the arguments to +
are a string, the return will be a string as well.
With that in mind, breaking this down you get:
"2 + 2 = " + 2
=> "2 + 2 = 2"
"2 + 2 = 2" + 2
=> "2 + 2 = 22"
If you want the math to happen before the String concatenation, you need to make sure it happens first, as @Ravindra's answer shows.
Check out this:
15.18.1. String Concatenation Operator +
If only one operand expression is of type String, then string conversion (ยง5.1.11) is performed on the other operand to produce a string at run time.