concatenating string and numbers Java
java
Solution
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`.
Problem
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?