Java Scanner hasNextLine() method example

HQ ┬╗ Java Tutorial ┬╗ java.util ┬╗ Scanner ┬╗ hasNextLine() method example
Java Scanner hasNextLine() method example 2018-02-20T12:10:22+00:00

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 :

DataType Parameter Description
N/A N/A N/A

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 :

 

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close