Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Scanner.nextLine() — Read the rest of the current line

`Scanner.nextLine()` returns the rest of the current line without its line separator. Immediately after `nextInt()`, the result can be an empty string.

Version: Java SE 21

Syntax

public String nextLine()

String line = scanner.nextLine();

Scanner.nextLine is an instance method of java.util.Scanner. It takes no arguments and has no overloads. Call it on an object, as in scanner.nextLine(). It returns a String from the current position to the end of the line: it preserves spaces, leaves the line separator out of the result, and moves past that separator if there is one. It can also read a nonempty final line with no terminating separator.

next() and nextInt() read tokens, which are chunks of input separated by the scanner's token delimiter pattern. nextLine() does not use that pattern. nextInt() can read the number only if it forms a complete integer token under the current delimiter pattern. With the default delimiter, 42Ada is a single token, so nextInt() throws InputMismatchException. With a custom delimiter, a line break need not separate tokens. After a successful read, nextInt() leaves the position just after the token. If a line separator starts there, nextLine() returns "", not the text on the following line. If text or spaces remain on the same line, nextLine() returns them. Discard the result only if you mean to skip the rest of that line.

hasNextLine() checks whether a line is available without moving the scanner's position. An empty line with a separator is not end of input. If no line is available, nextLine() throws NoSuchElementException. Both methods throw IllegalStateException if the scanner is closed.

Both methods can block while waiting for input. If the remaining input contains no line separator, nextLine() may buffer all of it. Closing the scanner also closes its source if that source implements Closeable. Do not close a scanner over System.in if the program still needs standard input.

Examples

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner("42\r\nAda Lovelace")) {
            int number = scanner.nextInt();
            String rest = scanner.nextLine();

            System.out.println(number);
            System.out.println("[" + rest + "]");
            while (scanner.hasNextLine()) {
                System.out.println("[" + scanner.nextLine() + "]");
            }
        }
    }
}

Result

42
[]
[Ada Lovelace]

The input comes from a string, not the keyboard. Square brackets show exactly what was returned: `[]` is the empty remainder after `42`, and `[Ada Lovelace]` shows that the final line is read with its space intact even though it has no terminating separator.

Related lessons

  • Java · Lesson 2 · Basic · Version: 2

Sources