concatenating string and numbers Java

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.

Leave a Comment