Difference Between next() and nextLine() Methods From Java Scanner Class

Farkhanda Athar Oct 12, 2023
  1. the next() Method in Java Scanner
  2. the nextLine() Method in Java Scanner
  3. Difference Between next() and nextLine() Methods in Java
Difference Between next() and nextLine() Methods From Java Scanner Class

The Scanner class, part of the java.util package, is used to obtain the inputs of basic types such as double, int, and string. It’s the most efficient method of reading input in the Java program. Still, it is not highly efficient if you are looking for an input method that can be used in scenarios where time is an issue, such as competition programming. The Scanner class comprises of next() and nextLine() methods. This article explains we will discuss the difference between these two techniques will be examined.

the next() Method in Java Scanner

The next() method in Java is available in the Scanner class and can be used to obtain the user’s input. To utilize this method, the Scanner object must be constructed. This method can read input until it comes across a space that is found. Also, it retrieves the next token complete in the scanner. Here is an illustration of how the next() method works in Java.

Example code:

import java.util.Scanner;

class ABC {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String Inpt = sc.next();
    System.out.println(Inpt);
  }
}

Input:

Welcome To 
Party

Output:

Party

the nextLine() Method in Java Scanner

The nextLine() is a method in Java that is available in the Scanner class and is utilized to obtain the user’s input. It is necessary to create a Scanner object that must be constructed before using this method. This method can read input up to the end of the line. Also, it reads input until the line changes or a new line and then ends the input with \n or pressing enter. Here is an illustration that shows how the nextLine() method works in Java.

Example code:

import java.util.Scanner;

class ABC {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String Inpt = sc.nextLine();
    System.out.println(Inpt);
  }
}

Input:

Welcome To 
Party

Output:

Welcome To

Difference Between next() and nextLine() Methods in Java

next() nextLine()
It reads input from an input device up to it reaches the character space. It reads input from the device that is input until the line changes.
It can’t read the words with space. It can read the words with space.
It stops reading input after it has gotten space. It will stop reading input once it has gotten \n or pressing enter.
The cursor is placed in the same place after receiving input. The cursor will be placed on the next line following reading the input.
The sequence that escapes the next() refers to space. The escape sequence of the nextLine() is \n.
Syntax for scanning input: Scanner.next() Syntax to scan input: Scanner.nextLine()

Related Article - Java Scanner