Java Scanner nextLine() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Scanner

Definition

In Java, sc.nextLine() advances the scanner past the current line and returns everything from the current position up to (but excluding) the line separator as a String.

It preserves spaces inside the line, can return an empty string "" for blank lines, and throws NoSuchElementException if no characters or line break remain.

An instance method of java.util.Scanner, available since Java 5 (JDK 1.5). A Scanner reads from any source (System.in for keyboard, a String, or a file) with identical parsing logic; pass the source to new Scanner(...) after import java.util.Scanner; and call sc.nextLine(...).

Syntax

Call nextLine() on any Scanner to read a whole line (including spaces) at once.

Java
Scanner sc = new Scanner("25\nAnna Smith");
int age = sc.nextInt();     // 25 (leaves "\n" behind)
sc.nextLine();              // consumes the leftover "\n"
String name = sc.nextLine(); // "Anna Smith"
CallWhat it does
sc.nextLine()Reads through the next newline and returns text without the newline.
sc.hasNextLine()Check if another line exists before calling nextLine().
Integer.parseInt(sc.nextLine().trim())Alternative to nextInt() that avoids leftover newlines.

nextLine() ignores your token delimiter and always looks for a line terminator (\n, \r\n, or \r), or the end of the input if the last line has no trailing newline.

Library declarations
Java
// java.util.Scanner
public String nextLine()

Parameters

ParameterDescription
NonenextLine() takes no parameters.

Return Value

Return ValueDescription
StringThe remainder of the current line without its trailing line break (may be "").
Throws NoSuchElementExceptionIf the scanner has already reached the end of input and no line was found.
Throws IllegalStateExceptionIf the scanner is closed.

Compare with Similar Methods

Reading full lines versus tokens:

MethodHow it differs
next()Stops at whitespace; cannot read multi-word names.
hasNextLine()Returns true when another line is ready.
findInLine(p)Searches inside the current line without crossing newlines.
Console.readLine()Returns null at EOF instead of throwing.

Java Examples

Example 1 — Read Multiple Lines Including Empty Lines

Walk through a multi-line note containing a blank line, then catch NoSuchElementException once the input ends.

Java
import java.util.NoSuchElementException;
import java.util.Scanner;

public class ScannerNextLineMulti {
    public static void main(String[] args) {
        String note = "First line\n\nLast line";
        try (Scanner sc = new Scanner(note)) {
            int row = 1;
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                System.out.println(row + ": [" + line + "]");
                row++;
            }
            try {
                sc.nextLine();
            } catch (NoSuchElementException e) {
                System.out.println("At EOF: " + e.getClass().getSimpleName());
            }
        }
    }
}

How It Works

  1. Adjacent newlines make a blank line. The double \n\n leaves zero characters before the second line break, so line 2 prints as [].
  2. No trailing newline needed. "Last line" ends at the string boundary rather than a \n, yet nextLine() still returns it cleanly.
  3. Exception after last line. Once all characters are consumed, calling nextLine() again throws NoSuchElementException.

Example 2 — Fix the nextInt() Followed by nextLine() Trap

Compare what happens when you forget to clear the leftover newline after nextInt() versus adding a clearing call.

Java
import java.util.Scanner;

public class ScannerNextLinePitfall {
    public static void main(String[] args) {
        String form = "101\nAva Brooks\n202\nLiam Chen";
        try (Scanner sc = new Scanner(form)) {
            int id1 = sc.nextInt();
            String skipped = sc.nextLine();
            String actual1 = sc.nextLine();
            System.out.println("Without fix -> id=" + id1 + ", first nextLine=\"" + skipped + "\", next=\"" + actual1 + "\"");

            int id2 = Integer.parseInt(sc.nextLine().trim());
            String actual2 = sc.nextLine();
            System.out.println("Line-only fix -> id=" + id2 + ", name=\"" + actual2 + "\"");
        }
    }
}

How It Works

  1. Cursor stops before newline. Reading 101 with nextInt() leaves the \n right after 101 still sitting in the buffer.
  2. Consuming the empty tail. The very next sc.nextLine() swallows that \n and returns "", shifting "Ava Brooks" to the call after it.
  3. Parse lines directly. Calling nextLine() for "202" and passing it to Integer.parseInt removes the newline immediately so "Liam Chen" follows naturally.

Example 3 — Read a Multi-Word Line from System.in

Prompt the user for a full street address and city name using System.in.

Java
import java.util.Scanner;

public class ScannerNextLineKeyboard {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your full name:");
        String fullName = sc.nextLine();
        System.out.println("Enter your city:");
        String city = sc.nextLine();
        System.out.println("Shipping to: " + fullName + ", " + city);
    }
}

How It Works

  1. Spaces stay intact. Both "Elena Torres" and "San Jose" contain a space that nextLine() preserves inside each string.
  2. Prompt before blocking. Printing the prompt line before calling nextLine() lets the user see what to type while the program waits for Enter.
  3. Consistent line reads. Mixing no nextInt() calls keeps every Enter key paired cleanly with its own nextLine().

Frequently Asked Questions

nextInt() stops before the newline character from pressing Enter. The nextLine() right after reads the empty text up to that newline and returns "". Add an extra sc.nextLine() to clear it, or read lines and parse with Integer.parseInt.
No. It consumes the line separator and returns only the text before it.
Yes. If the user presses Enter on an empty line, or right after a token read like nextInt(), nextLine() returns "".
It throws NoSuchElementException if there are no more characters or lines left to read. Check hasNextLine() first.
No. nextLine() always splits on line terminators rather than the token delimiter.

Next: nextLong()

Read the next token as a long.

nextLong() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful