Java Scanner nextLong() Method

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

Definition

In Java, sc.nextLong() parses the next token into a 64-bit signed long (from -9223372036854775808 to 9223372036854775807). You can also supply a radix from 2 to 36.

Use nextLong() instead of nextInt() for file sizes in bytes, account IDs, populations, or timestamps that exceed 2.1 billion.

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.nextLong(...).

Syntax

Read base-10 large integers with nextLong(), or pass a radix such as 16 for 64-bit hex strings.

Java
Scanner sc = new Scanner("8100000000 7fffffffffffffff");
long population = sc.nextLong();     // 8100000000L
long maxVal = sc.nextLong(16);       // 9223372036854775807L
CallWhat it does
sc.nextLong()Reads the next token as a long in the scanner's current radix.
sc.nextLong(16)Parses a 64-bit hexadecimal integer token.
sc.hasNextLong()Tests whether the next token fits in a long without throwing.

Do not put Java's literal L suffix in input text: "42L" throws InputMismatchException in base 10 because 'L' is not a base-10 digit.

Library declarations
Java
// java.util.Scanner
public long nextLong()
public long nextLong(int radix)

Parameters

ParameterDescription
radix (optional)Number base (2 to 36) for interpreting the token.

Return Value

Return ValueDescription
longThe parsed 64-bit signed integer.
Throws InputMismatchExceptionIf the token has invalid characters or falls outside Long.MIN_VALUE..Long.MAX_VALUE.
Throws NoSuchElementExceptionIf no more tokens remain.
Throws IllegalStateExceptionIf the scanner has been closed.

Compare with Similar Methods

Whole-number readers in Scanner:

MethodHow it differs
nextInt()32-bit integers up to ~2.14 billion.
hasNextLong()Checks if the token fits in a long beforehand.
nextBigInteger()Arbitrary-precision integers with no upper limit.
Long.parseLong(s)Converts an already-read String to a long.

Java Examples

Example 1 — Total Byte Sizes Exceeding int Range

Add multi-gigabyte file sizes from a log summary into a long accumulator.

Java
import java.util.Scanner;

public class ScannerNextLongBytes {
    public static void main(String[] args) {
        String sizes = "3500000000 4250000000 1200000000";
        long total = 0L;
        try (Scanner sc = new Scanner(sizes)) {
            while (sc.hasNextLong()) {
                total += sc.nextLong();
            }
        }
        System.out.println("Total bytes: " + total);
    }
}

How It Works

  1. Beyond 32 bits. Each of the first two numbers is over 3 billion, which would fail nextInt().
  2. Checked accumulation. hasNextLong() confirms each token fits in 64 bits before nextLong() adds it to total.
  3. Clean 64-bit sum. The combined 8.95 billion bytes prints accurately without integer wrap-around.

Example 2 — Parse 64-Bit Hexadecimal Tokens with nextLong(16)

Read signed and maximum positive 64-bit hexadecimal values using radix 16.

Java
import java.util.Scanner;

public class ScannerNextLongHex {
    public static void main(String[] args) {
        String hexIds = "7fffffffffffffff 1a2b3c4d5e -10";
        try (Scanner sc = new Scanner(hexIds)) {
            long maxSigned = sc.nextLong(16);
            long sample = sc.nextLong(16);
            long neg = sc.nextLong(16);
            System.out.println("Max long: " + maxSigned);
            System.out.println("Sample:   " + sample);
            System.out.println("Negative: " + neg);
        }
    }
}

How It Works

  1. Signed 64-bit ceiling. Fifteen f digits after 7 equal Long.MAX_VALUE, the largest positive value nextLong(16) accepts.
  2. Arbitrary hex token. Base 16 turns 1a2b3c4d5e into decimal 112394521950 directly.
  3. Optional minus sign. A leading - works in any radix, so "-10" in base 16 parses as -16.

Example 3 — Why "42L" and 20-Digit Numbers Throw InputMismatchException

Observe how nextLong() rejects a trailing L suffix and numbers larger than Long.MAX_VALUE.

Java
import java.util.InputMismatchException;
import java.util.Scanner;

public class ScannerNextLongRejects {
    public static void main(String[] args) {
        String inputs = "42L 99999999999999999999 42";
        try (Scanner sc = new Scanner(inputs)) {
            while (sc.hasNext()) {
                try {
                    System.out.println("Accepted: " + sc.nextLong());
                } catch (InputMismatchException e) {
                    System.out.println("Rejected (" + e.getClass().getSimpleName() + "): " + sc.next());
                }
            }
        }
    }
}

How It Works

  1. Java suffixes are invalid input. Unlike Java source code, text read by Scanner treats L in "42L" as a non-digit character and rejects it.
  2. Overflow triggers mismatch. Twenty 9s exceed Long.MAX_VALUE, producing InputMismatchException rather than wrapping silently.
  3. Advancing past errors. Consuming each rejected token with sc.next() lets the loop reach and parse the trailing 42.

Frequently Asked Questions

From -9223372036854775808 (Long.MIN_VALUE) to 9223372036854775807 (Long.MAX_VALUE).
The letter L is Java source code syntax, not a digit. Scanner throws InputMismatchException on "100L".
No. Anything outside signed 64-bit range throws InputMismatchException. Use nextBigInteger() instead.
Yes. Call sc.nextLong(radix) with any radix between 2 and 36, or set a default with useRadix().
No. Like nextInt(), it stops before the delimiter, so call an extra nextLine() before reading a full line afterwards.

Next: nextShort()

Read the next token as a short.

nextShort() 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.

7 people found this page helpful