Wednesday, September 3, 2025
HomeLanguagesJavaScanner hasNextLine() method in Java with Examples

Scanner hasNextLine() method in Java with Examples

The hasNextLine() method of java.util.Scanner class returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.

Syntax:

public boolean hasNextLine()

Parameters: The function does not accepts any parameter.

Return Value: This function returns true if and only if this scanner has another line of input

Exceptions: The function throws IllegalStateException if this scanner is closed.

Below programs illustrate the above function:

Program 1:




// Java program to illustrate the
// hasNextLine() method of Scanner class in Java
// without parameter
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        String s = "gfg 2 geeks!";
  
        // new scanner with the
        // specified String Object
        Scanner scanner = new Scanner(s);
  
        // use US locale to interpret Lines in a string
        scanner.useLocale(Locale.US);
  
        // iterate till end
        while (scanner.hasNextLine()) {
  
            // print what is scanned
            System.out.println(scanner.nextLine());
        }
  
        // close the scanner
        scanner.close();
    }
}


Output:

gfg 2 geeks!

Program 2: Program to demonstrate exception




// Java program to illustrate the
// hasNextLine() method of Scanner class in Java
// without parameter
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
        try {
  
            String s = "gfg 2 geeks!";
  
            // new scanner with the
            // specified String Object
            Scanner scanner = new Scanner(s);
  
            // use US locale to interpret Lines in a string
            scanner.useLocale(Locale.US);
  
            scanner.close();
  
            // iterate till end
            while (scanner.hasNextLine()) {
  
                // print what is scanned
                System.out.println(scanner.nextLine());
            }
  
            // close the scanner
            scanner.close();
        }
        catch (IllegalStateException e) {
            System.out.println("Exception is: " + e);
        }
    }
}


Output:

Exception is: java.lang.IllegalStateException: Scanner closed

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine()

RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11854 POSTS0 COMMENTS
Shaida Kate Naidoo
6746 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS