Reputation: 1403
I am new to Java and was working with simple printing. First, I executed:
System.out.println(1 + 2 + "3");
Output:33
I made up logic that 1 and 2 will be added and 3 will be printed as is.
Then, I tried this:
System.out.println ("1" + 2 + 3);
Output:123
Applying that logic I got answer 15 ,couldn't work-out the correct answer, so I need your help, SO friends.
Upvotes: 1
Views: 423
Reputation: 21449
Operator +
is evaluated from the left so your second example is interpreted this way:
System.out.println (((“1”+2)+3));
====================> "12"+3
====================> "123"
If you want to display 15
then you should do the following:
System.out.println (“1”+(2+3));
This way (2+3)
will be evaluated first.
Upvotes: 5
Reputation: 32731
In the first case Java adds the numbers to get the result 3 and the appending of the string 3 causes it to become the concatenated string: "33".
In the second case the result is a string because of the "1" and the others get concatenated to become "123"
Upvotes: 1
Reputation: 888185
The expression 1 + 2
is an int
.
You're then concatenating "3"
to that int.
The expression "1" + 2
is a String
.
You're then concatenating 3
to that String
.
You're thinking of "1" + (2 + 3)
, which doesn't happen because Java is left-associative.
Upvotes: 2