Java Scanner nextShort() Method

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

Definition

In Java, sc.nextShort() reads the next token and parses it into a 16-bit signed short, covering values from -32768 to 32767. An optional radix parameter lets you read binary, octal, or hexadecimal values.

Any valid integer outside -32768..32767 (such as 40000) causes InputMismatchException rather than truncating bits.

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

Syntax

Read 16-bit signed numbers directly with nextShort() or nextShort(radix).

Java
Scanner sc = new Scanner("2026 -15 7fff");
short year = sc.nextShort();         // 2026
short offset = sc.nextShort();       // -15
short hexMax = sc.nextShort(16);     // 32767
CallWhat it does
sc.nextShort()Reads a short in the scanner's current radix.
sc.nextShort(16)Parses a 16-bit hex value up to 7fff (32767).
sc.hasNextShort()Checks whether the next token fits inside short bounds.

Even though Java's Short.parseShort throws NumberFormatException internally, Scanner catches it and throws InputMismatchException consistently for all bad or out-of-range tokens.

Library declarations
Java
// java.util.Scanner
public short nextShort()
public short nextShort(int radix)

Parameters

ParameterDescription
radix (optional)The base (2 to 36) used to parse the digits.

Return Value

Return ValueDescription
shortA 16-bit signed integer between -32768 and 32767.
Throws InputMismatchExceptionIf the token is non-numeric or outside Short.MIN_VALUE..Short.MAX_VALUE.
Throws NoSuchElementExceptionIf no more tokens exist.
Throws IllegalStateExceptionIf the scanner has been closed.

Compare with Similar Methods

Small-integer readers and guards:

MethodHow it differs
hasNextShort()Verifies 16-bit bounds before reading.
nextByte()Even smaller 8-bit signed integer (-128 to 127).
nextInt()32-bit signed integer; needed for values above 32767.
Short.parseShort(s)Parses a String; throws NumberFormatException.

Java Examples

Example 1 — Read Elevation Readings into a short Array

Store compact 16-bit sensor elevation values without wasting int storage.

Java
import java.util.Arrays;
import java.util.Scanner;

public class ScannerNextShortElevations {
    public static void main(String[] args) {
        String readings = "-120 0 1450 32767";
        short[] levels = new short[4];
        try (Scanner sc = new Scanner(readings)) {
            for (int i = 0; i < levels.length; i++) {
                levels[i] = sc.nextShort();
            }
        }
        System.out.println("Elevations: " + Arrays.toString(levels));
    }
}

How It Works

  1. Within 16-bit bounds. Every value from -120 up to Short.MAX_VALUE (32767) parses cleanly into a short.
  2. Array population. Four consecutive nextShort() calls fill each slot of levels in order.
  3. Formatted summary. Arrays.toString prints all four stored shorts inside brackets.

Example 2 — Catch Overflow at 40000 and Fall Back to nextInt()

See how 40000 fails nextShort() with InputMismatchException while remaining untouched for nextInt().

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

public class ScannerNextShortOverflow {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("8080 40000")) {
            for (int i = 0; i < 2; i++) {
                try {
                    short port = sc.nextShort();
                    System.out.println("short port: " + port);
                } catch (InputMismatchException e) {
                    System.out.println("nextShort threw " + e.getClass().getSimpleName() + "; nextInt = " + sc.nextInt());
                }
            }
        }
    }
}

How It Works

  1. Port 8080 succeeds. Because 8080 is below 32767, the first read stores it as a short.
  2. Port 40000 exceeds signed short. nextShort() throws InputMismatchException without consuming "40000".
  3. Immediate int fallback. Inside catch, sc.nextInt() reads that unconsumed "40000" token cleanly.

Example 3 — Parse 16-Bit Hexadecimal Flags with nextShort(16)

Read hexadecimal register codes using base 16 and check that negative hex values also work.

Java
import java.util.Scanner;

public class ScannerNextShortHex {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("00ff 7fff -8000")) {
            short mask = sc.nextShort(16);
            short hi = sc.nextShort(16);
            short lo = sc.nextShort(16);
            System.out.println("00ff -> " + mask);
            System.out.println("7fff -> " + hi);
            System.out.println("-8000 -> " + lo);
        }
    }
}

How It Works

  1. Leading zeros allowed. Hex token "00ff" ignores leading zeros and evaluates to 255.
  2. Exact 16-bit limits. 7fff equals Short.MAX_VALUE (32767) and -8000 equals Short.MIN_VALUE (-32768).
  3. Unsigned 8000 would fail. Without the minus sign, 8000 in hex is 32768, one above short capacity.

Frequently Asked Questions

Signed 16-bit integers from -32768 to 32767 inclusive.
InputMismatchException, because 50000 is outside the signed short range (-32768..32767).
Yes. Pass the radix as an argument, such as sc.nextShort(2) or sc.nextShort(16).
Scanner converts internal number-format errors into InputMismatchException so all type-mismatch errors have one consistent exception type.
No, because ports go up to 65535 while short stops at 32767. Use nextInt() and validate 0..65535 instead.

Next: radix()

Return the scanner's default number base (10 by default).

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

8 people found this page helpful