Java Scanner hasNextShort() Method

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

Definition

In Java, sc.hasNextShort() returns true if the next token parses as a signed 16-bit short between -32768 and 32767, without consuming any input.

Pass an optional radix (2 to 36) with hasNextShort(int radix) to validate binary, octal, or hexadecimal 16-bit values.

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

Syntax

Verify 16-bit bounds safely before calling nextShort().

Java
Scanner sc = new Scanner("32767 32768");
boolean ok = sc.hasNextShort();       // true
sc.next();
boolean tooBig = sc.hasNextShort();   // false
CallWhat it does
sc.hasNextShort()Checks signed 16-bit range in current radix.
sc.hasNextShort(16)Checks signed 16-bit range in hexadecimal (up to 7fff).

Even though "40000" is a valid integer, hasNextShort() returns false because 40000 exceeds Short.MAX_VALUE (32767).

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

Parameters

ParameterDescription
radix (optional)Number base (2 to 36) for parsing digits.

Return Value

Return ValueDescription
booleantrue if the next token fits in -32768..32767; false otherwise.
Throws IllegalStateExceptionIf the scanner is closed.
Throws IllegalArgumentExceptionIf radix is outside 2..36.

Compare with Similar Methods

16-bit lookahead compared with adjacent widths:

MethodHow it differs
nextShort()Consumes the verified 16-bit short.
hasNextByte()Stricter 8-bit check (-128..127).
hasNextInt()Wider 32-bit check accepting 32768..65535.

Java Examples

Example 1 — Test Exact Short Minimum and Maximum Boundaries

Check values right on and just past -32768 and 32767 without throwing.

Java
import java.util.Scanner;

public class ScannerHasNextShortBounds {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("-32769 -32768 32767 32768")) {
            while (sc.hasNext()) {
                boolean fits = sc.hasNextShort();
                System.out.println(sc.next() + " -> hasNextShort? " + fits);
            }
        }
    }
}

How It Works

  1. Exact endpoints pass. -32768 and 32767 are the exact signed 16-bit edges and return true.
  2. Off-by-one edges fail safely. -32769 and 32768 return false without crashing.
  3. Single-pass consumption. Printing sc.next() after testing advances cleanly to the next candidate.

Example 2 — Check Signed 16-Bit Hex Tokens with hasNextShort(16)

Test why 7fff and -8000 pass base-16 short validation while 8000 fails.

Java
import java.util.Scanner;

public class ScannerHasNextShortHex {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("7fff 8000 -8000")) {
            while (sc.hasNext()) {
                if (sc.hasNextShort(16)) {
                    System.out.println("Valid short hex -> " + sc.nextShort(16));
                } else {
                    System.out.println("Too large for signed short: " + sc.next());
                }
            }
        }
    }
}

How It Works

  1. Positive hex ceiling. 7fff equals 32767 and passes hasNextShort(16).
  2. Unsigned 8000 overflows. Positive hex 8000 equals 32768, returning false for signed short.
  3. Negative hex floor fits. Adding the minus sign to -8000 yields -32768, matching Short.MIN_VALUE.

Example 3 — Extract Valid Short Values from Mixed Status Logs

Keep only tokens within signed 16-bit range from a mixed telemetry line.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ScannerHasNextShortFilter {
    public static void main(String[] args) {
        String log = "200 ok 32000 50000 -10";
        List<Short> kept = new ArrayList<>();
        try (Scanner sc = new Scanner(log)) {
            while (sc.hasNext()) {
                if (sc.hasNextShort()) {
                    kept.add(sc.nextShort());
                } else {
                    sc.next();
                }
            }
        }
        System.out.println("Kept shorts: " + kept);
    }
}

How It Works

  1. Skip text and oversized numbers alike. Both "ok" and 50000 return false and are discarded by sc.next().
  2. Boxed into List<Short>. Valid tokens 200, 32000, and -10 are autoboxed into the list.
  3. Clean filtered list. All three in-range shorts appear in input order.

Frequently Asked Questions

Signed 16-bit integers from -32768 to 32767 inclusive.
Java short is signed with a maximum of 32767, so 65535 is out of range.
No. Any decimal point causes hasNextShort() to return false.
Yes, call sc.hasNextShort(16).
No. Call nextShort() afterwards to consume it.

Next: ioException()

Return the last IOException thrown by the underlying Readable, or null.

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

12 people found this page helpful