pele pele - 26 days ago 9
Java Question

Java: Could you explain this simple statement (System.out.println)?

System.out.println(1 + 2 + "3");


Output:
33

System.out.println("1" + 2 + 3);


Output:
123

Answer

Well, it's a thing called order of operations.

1 + 2 is calculated to equal 3 and then the string "3" is appended to it converting the first 3 to a string and printing "33".

In your second instance, "1" is already a string so adding numbers will convert them to strings to match, so appending "2" and then appending "3" and printing "123".

P.S. Strings take precedence because they have a higher casting priority than integers do, therefore it will convert integers to strings but not strings to integers, as with the second example.

Comments