java.util.Scanner nextLine()

Description :

This java tutorial shows how to use the nextLine() method of Scanner class of java.util package. This method returns a String which corresponds to the skipped line of the Scanner object.

Method Syntax :

public String nextLine()

Parameter Input :

[table]
DataType|Parameter|Description
N/A|N/A|N/A
[/table]

Method Returns :

This method simply returns the string the current line.

Compatibility Version :

Requires Java 1.5 and up

Exception :

NoSuchElementException

– The NoSuchElementException is thrown if and only if there is no available token

IllegalStateException

– This exception is thrown if the scanner is already closed before invoking the nextLine() method.

Discussion :

The Scanner nextLine() method returns the line skipped during method invocation and the Scanner object moves in to the succeeding line. This method alongside with hasNextLine() method of Scanner is helpful in reading a file line by line.

Java Code Example :

This java example source code demonstrates the use of nextLine() method of Scanner class. Basically this example source makes use of hasNextLine() and nextLine() method of Scanner class to iterate through the contents of a file line by line.

The following are the contents of the file:

Sample Output :

Running the nextLine() method example source code of Scanner class will give you the following output

java scanner nextline method example

java scanner nextline method example

Exception Scenario :

Similar Method :

  • N/A

Suggested Reading List :

References :