Why is the output different in these cases ?
int x=20,y=10;
System.out.println("printing: " + x + y); ==> printing: 2010
System.out.println("printing: " + x * y); ==> printing: 200
Why isn’t the first output 30? Is it related to operator precedence ? Like first “printing” and x are concatenated and then this resulting string and y are concatenated ? Am I correct?
Its the
BODMASRuleI am showing the Order of precedence below from Higher to Low:
This works from
Left to Rightif the Operators are of Same precedenceNow
System.out.println("printing: " + x + y);"printing: ": Is a String”"+": Is the only overloaded operator in Java which will concatenate Number to String.As we have 2 “+” operator here, and x+y falls after the
"printing:" +as already taken place, Its considering x and y as Strings too.So the output is 2010.
System.out.println("printing: " + x * y);Here the
"*": Has higher precedence than+So its
x*yfirst thenprinting: +So the output is 200
Do it like this if you want 200 as output in first case:
The Order of precedence of
Bracketis higher toAddition.