Java - Difference Between print() and println()

By Shahnail Khan Last updated : March 14, 2024

In Java programming, both the print() and println() methods are commonly used for displaying the output. While they may seem similar, there are significant differences between them that every Java developer should understand. This article will explain the differences between print() and println() with relevant examples and when to use them.

What is print() Method in Java?

The print() method in Java displays text or variables on the console without moving to the next line. It simply prints the output and keeps the cursor on the same line.

Example of print() Method in Java

public class Main {
  public static void main(String[] args) {
    //Initialise a variable 
    int num = 10;
    System.out.print("The value of num is: ");
    System.out.print(num);
  }
}

The output of the above program is:

The value of num is: 10

In this example, we have a variable num initialized with the value 10.

We use the print() method twice to display text and the value of num on the same line. The first print() statement prints "The value of num is: " without moving to the next line, and the second print() statement prints the value of num (10) right after it. 

As a result, both outputs are displayed on the same line in the console.

What is println() Method in Java?

The println() method is also used to display text or variables on the console, but it automatically moves the cursor to the next line after displaying the output.

Example of println() Method in Java

public class Main {
  public static void main(String[] args) {
    //Initialise a variable 
    int num = 10;
    System.out.println("The value of num is: ");
    System.out.print(num);
  }
}

The output of the above program is:

The value of num is: 
10

In this example, we have the same variable num initialized with the value 10. The first println() statement prints "The value of num is: " and automatically moves to the next line. Then, the print() statement prints the value of num (10) on a new line. 

Therefore, each output is displayed on a separate line in the console.

Difference Between print() and println() in Java

The below table shows the main differences between print() and println() methods in Java:

Sr No Java print() Method Java println() Method
1 Does not move the cursor to the next line. Moves cursor to the next line.
2 Output is displayed on the same line. Output is displayed on a new line.
3 Suitable for printing continuous text. Suitable for printing text followed by a newline character.
4 Doesn't automatically add a newline character. Automatically adds a newline character at the end.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.