Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

Output: 33

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

Output: 123

like image 602
pele Avatar asked Mar 02 '10 08:03

pele


People also ask

What is System out Println in Java meaning?

In Java, System. out. println() is a statement which prints the argument passed to it. The println() method display results on the monitor. Usually, a method is invoked by objectname.

What is the output System out Println?

println() output to a file in Java. JavaObject Oriented ProgrammingProgramming. The filed named out of the System class represents a standard output Stream, an object of the PrintStream class. The println() method of this accepts any a value ( of any Java valid type), prints it and terminates the line.

How do you write System out Println in Java?

To get System. out. println() line in eclipse without typing the whole line type sysout and press Ctrl + space.


1 Answers

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.

like image 130
animuson Avatar answered Oct 29 '22 15:10

animuson