Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

  1. The expression 1 + 2 is an int.
    You're then concatenating "3" to that int.

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

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"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top