java.util.Scanner hasNextLine()

Description :

This java tutorial shows how to use the hasNextLine() method of Scanner class of java.util package. This method returns a boolean data type which corresponds to the existence of new line on the String tokens which the Scanner object holds.

Method Syntax :

public boolean hasNextLine()

Parameter Input :

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

Method Returns :

This method simply returns true if there is another line on the scanner input, otherwise this method returns false

Compatibility Version :

Requires Java 1.5 and up

Exception :

IllegalStateException

– The IllegalStateException exception will be thrown by the hasNextLine() if this method has been invoked after the scanner has been closed.

Discussion :

The Scanner hasNextLine() method is helpful method especially in reading a file line by line. This method will serve as a flag that there is a token after the current line.

The methods available on the Scanner class is very rich that you can do same logic using different combination of API’s. For all the methods in the Scanner class this is my favorite since I have been used it many times in combination with the nextLine() method.

Java Code Example :

This java example source code demonstrates the use of hasNextLine() method of Scanner class. Basically this example code reads all the names that it can find on the text file.

Contents of the file

Sample Output :

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

java scanner hasnextline method example

java scanner hasnextline method example

As you would have noticed on the sample file there is one line that has two names on it. This is the main reason why we have used the next() method instead of the nextLine() in order for us to tokenize the elements per line thus on our output result we have list down all names that is listed on the file.

Exception Scenario :

Similar Method :

  • N/A

Suggested Reading List :

References :