Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenating string and numbers Java

Tags:

java

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?

like image 699
h4ck3d Avatar asked Aug 19 '12 18:08

h4ck3d


2 Answers

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.

like image 63
Kumar Vivek Mitra Avatar answered Oct 02 '22 16:10

Kumar Vivek Mitra


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".

like image 37
Samson Avatar answered Oct 02 '22 16:10

Samson