-3

Why the below statement in Java prints "2 + 2 = 22"

System.out.println("2 + 2 = " + 2 + 2);
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Praveen Kishor
  • 2,413
  • 1
  • 23
  • 28

4 Answers4

9

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)
P.J.Meisch
  • 18,013
  • 6
  • 50
  • 66
Pierre
  • 34,472
  • 31
  • 113
  • 192
5

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));
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
4

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.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
1

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.

JLS 15.18.1

Community
  • 1
  • 1
St.Antario
  • 26,175
  • 41
  • 130
  • 318