Understanding System.out.print() and System.out.println() in Java

Print vs Println: What Gets Printed in Java?

When working with Java, it's important to understand the difference between System.out.print() and System.out.println(). Let's consider the following code segment:

System.out.print("The ");
System.out.println("Spartans ");
System.out.println("Rule ");
System.out.print("the South Side. ");

What will be the output of this code segment?

a) The Spartans Rule the South Side.
b) The Spartans
Rule
the South Side.
c) The Spartans
Rule the South Side.
d) The
Spartans
Rule
the South Side.
e) Nothing, this will produce an error.

Question:

What is printed as a result of executing the code segment?

Answer:

The answer to this question is B.

Explanation:

The reason that the answer is B is that in Java, using System.out.print() is going to print a line of code without escaping to a new line, while System.out.println() will print to the current line and then move to a new line.

Input:

System.out.print("The "); //Print to current line

System.out.println("Spartans "); // Print to current line then escape to new line

System.out.println("Rule "); // Print to current line then escape to new line

System.out.print("the South Side. "); // Print to current line

Output:

The Spartans

Rule

the South Side.

← How to verify the integrity of an rpm package without checking the signature or headers How to unhide worksheets in microsoft excel →