Difference between next() and nextLine()

next() and nextLine() methods are available in java.util.Scanner class; which is a simple text scanner class to parse primitive types and strings using regular expressions. The next() and nextLine() methods are used for getting inputs from User.

A Scanner class breaks its input into tokens using a delimiter pattern, which by default matches white-space.
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns the input that was skipped.

next() can read the input only till the space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line n). Once the input is read, nextLine() positions the cursor in the next line.

Below Program demonstrates the functionality of next() method,


having a look at output, We see when the input for str1 is given as Java Artifacts, it will not read the entire input Java Artifacts. next() reads only Java and places the cursor after the alphabet a. Now, when value for str2 is got using next(), it will not get new value. Rather, it takes the value after the current cursor position(since the cursor is after str1, Artifacts is assigned to str2 and the cursor stays after s).

Implementing the Above Example using the nextLine() method in place of next()


Since nextLine() is used for reading input for str1, the entire line is read and hence Java Artifacts is stored in str1 and the cursor is placed in the next line. Now when str2 is read using next() or nextLine(), the cursor will be in the next line and hence the input for str2 is read and is placed in str2.

This is the basic difference between the next() and nextLine() method but if you still want to use the next() method then use the scanner.nextLine() after next() method to move the cursor to the next Line.

For Example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.