Java Utility Library

Java Scanner - nextLine() Method



The java.util.Scanner.nextLine() method is used to advance the scanner past the current line and returns the input that was skipped. The method returns the rest of the current line, excluding any line separator at the end, and set the position to the beginning of the next line.

Since the method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

Syntax

public String nextLine()

Parameters

No parameter is required.

Return Value

Returns the line that was skipped.

Exception

  • Throws NoSuchElementException, if no line was found.
  • Throws IllegalStateException, if this scanner is closed.

Example:

In the example below, the java.util.Scanner.nextLine() method returns the content of the scanner line by line.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {

    //String to scan
    String MyString = "Hello \nWorld \nLearn Programming.";

    //creating a Scanner
    Scanner MyScan = new Scanner(MyString);

    while(MyScan.hasNextLine()) {
      //print the line while there is a nextLine token
      System.out.println(MyScan.nextLine());
    }

    //close the scanner
    MyScan.close();
  }
}

The output of the above code will be:

Hello 
World 
Learn Programming.

❮ Java.util - Scanner