Why the below statement in Java prints “2 + 2 = 22” instead of “2 + 2 = 4”

  • A+
Category:Languages

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

System.out.println("2 + 2 = " + 2 + 2); 

 


because java '+' operator is firts 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) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: