Java Scanner hasNextLong() Method

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

Definition

In Java, sc.hasNextLong() tests if the next token can be parsed as a 64-bit signed long (-9223372036854775808..9223372036854775807) without consuming it.

The overload hasNextLong(int radix) checks digits against a chosen base between 2 and 36.

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

Syntax

Check 64-bit integer validity with hasNextLong() or hasNextLong(radix).

Java
Scanner sc = new Scanner("5000000000 deadbeef");
boolean fits = sc.hasNextLong();
sc.next();
boolean fitsHex = sc.hasNextLong(16);
CallWhat it does
sc.hasNextLong()Tests if the next token fits in a signed long (current radix).
sc.hasNextLong(16)Checks whether the token is a valid signed 64-bit hex number.

Like nextLong(), hasNextLong() returns false for tokens ending in L (like "10L").

Library declarations
Java
// java.util.Scanner
public boolean hasNextLong()
public boolean hasNextLong(int radix)

Parameters

ParameterDescription
radix (optional)Base from 2 to 36 used to validate the token.

Return Value

Return ValueDescription
booleantrue if a token exists and fits in long; false otherwise.
Throws IllegalStateExceptionIf the scanner is closed.
Throws IllegalArgumentExceptionIf radix is outside 2..36.

Compare with Similar Methods

64-bit lookahead alongside adjacent integer checks:

MethodHow it differs
nextLong()Consumes the verified 64-bit integer.
hasNextInt()Checks smaller 32-bit int bounds.
hasNextBigInteger()Returns true for whole integers of any size.

Java Examples

Example 1 — Classify Tokens into int, long, or BigInteger

Inspect each number without consuming until we know the tightest integer type that fits.

Java
import java.util.Scanner;

public class ScannerHasNextLongClassify {
    public static void main(String[] args) {
        String nums = "42 5000000000 99999999999999999999";
        try (Scanner sc = new Scanner(nums)) {
            while (sc.hasNext()) {
                if (sc.hasNextInt()) {
                    System.out.println("int:        " + sc.nextInt());
                } else if (sc.hasNextLong()) {
                    System.out.println("long:       " + sc.nextLong());
                } else if (sc.hasNextBigInteger()) {
                    System.out.println("BigInteger: " + sc.nextBigInteger());
                } else {
                    System.out.println("Other:      " + sc.next());
                }
            }
        }
    }
}

How It Works

  1. Tiered lookahead stays put. Failing hasNextInt() leaves 5000000000 untouched for hasNextLong() to inspect next.
  2. 64-bit tier catches 5 billion. hasNextLong() succeeds and nextLong() consumes 5000000000.
  3. 20-digit fallback. When hasNextLong() rejects the 20-digit token, hasNextBigInteger() accepts it.

Example 2 — Filter Valid Hexadecimal Tokens with hasNextLong(16)

Scan mixed tokens and sum only those valid in hexadecimal base 16.

Java
import java.util.Scanner;

public class ScannerHasNextLongHex {
    public static void main(String[] args) {
        String log = "ff invalid 100000000 zzz";
        long sum = 0L;
        try (Scanner sc = new Scanner(log)) {
            while (sc.hasNext()) {
                if (sc.hasNextLong(16)) {
                    sum += sc.nextLong(16);
                } else {
                    System.out.println("Skipped: " + sc.next());
                }
            }
        }
        System.out.println("Hex sum in decimal: " + sum);
    }
}

How It Works

  1. Base-16 filter. ff (255) and 100000000 (2^32 = 4294967296) both pass hasNextLong(16).
  2. Non-hex words skipped. Tokens with letters outside a-f return false and are cleared by sc.next().
  3. Exact 64-bit total. Adding 255 + 4294967296 gives 4294967551 without overflowing.

Example 3 — Sum Large Transaction Values While Skipping Status Text

Add large account transfers while cleanly bypassing "pending" markers.

Java
import java.util.Scanner;

public class ScannerHasNextLongTx {
    public static void main(String[] args) {
        String feed = "2500000000 pending 1500000000 failed 100L";
        long cleared = 0L;
        try (Scanner sc = new Scanner(feed)) {
            while (sc.hasNext()) {
                if (sc.hasNextLong()) {
                    cleared += sc.nextLong();
                } else {
                    sc.next();
                }
            }
        }
        System.out.println("Cleared total: " + cleared);
    }
}

How It Works

  1. Ignore status words. "pending" and "failed" fail hasNextLong() and are discarded silently.
  2. L-suffix rejected. Even "100L" returns false because Java literal suffixes are invalid in text input.
  3. Combined result. The two numeric entries add cleanly to 4000000000.

Frequently Asked Questions

9223372036854775807 (Long.MAX_VALUE), and down to -9223372036854775808 (Long.MIN_VALUE).
No. The trailing L makes it fail integer parsing, so hasNextLong() returns false.
Yes, via sc.hasNextLong(2) or sc.hasNextLong(16).
hasNextLong() simply returns false without throwing an exception.
No. Call nextLong() to read it, or next() to skip it when hasNextLong() is false.

Next: hasNextShort()

Check whether the next token fits in a signed short.

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

11 people found this page helpful