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 BODMAS Rule
I am showing the Order of precedence below from Higher to Low:
B  - Bracket 
O  - Power
DM - Division and Multiplication
AS - Addition and Substraction
This works from Left to Right if the Operators are of Same precedence
Now
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*y first then printing: +
So the output is 200
Do it like this if you want 200 as output in first case:
System.out.println("printing: "+ (x+y));
The Order of precedence of Bracket is higher to Addition.
Basic math tells you that adding numbers is done each at a time.
So "printing: " + x is computed first. As it s a string + int the result is "printing: 20". Then you add y so "printing: 20" + y equals "printing: 2010".
In the second case, multiplying is prioritary. So first x * y is calculated and equals 200. Then "printing: " + 200 equals "printing: 200".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With