Difference between next() and nextLine()

In Java, the Scanner class available in the java.util.package is one of the easiest ways for obtaining input of the primitive data types such as int, double, and strings. In competitive programming, time is a constraint, and using the Scanner class is not an efficient way for scenarios where time is a constraint.

Let's understand both the methods one by one with an example:

next() Method

The next() method of the Scanner class is used for getting input from the user. In order to use the next() method of the Scanner class, an instance of the Scanner class needs to be created. The next() method stops reading input from the user until it receives a white space(" "). So, it returns the next complete token from the Scanner.

Let's take an example to understand how the next() method is used for taking input from the user.

NextExample.java

Output:

Difference between next() and nextLine()

nextLine() Method

The nextLine() method of the Scanner class is also used for taking input from the user. In order to use the nextLine() method, we also need to create an instance of the Scanner class. The nextLine() method is capable of reading input till the end of the line. So, it stops reading input from the user when the user presses the enter key or line change.

Let's take an example to understand how the nextLine() method is used for taking input from the user.

NextLineExample.java

Output:

Difference between next() and nextLine()

Difference between the next() and the nextLine()

The given table describe the difference b/w the next() and the nextLine() methods:

S.No.next()nextLine()
1.It reads input till the space character.It reads input till the line change.
2.It is unable to read those words having space in them.The words having space in them can be read by this method.
3.It stops reading the input when it founds space.It stops reading the input when it founds '\n' or presses enter.
4.After reading the input, the method places the cursor on the same line.After reading the input, the method places the cursor in the next line.
5.Space is the escaping sequence of the next() method.The '\n' is the escaping sequence of the nextLine() method.
6.Syntax:
Scanner sc = new Scanner(System.in);
sc.next();
Syntax:
Scanner sc = new Scanner(System.in); sc.nextLine();





Latest Courses