Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Types and Literals

The short and byte types

Reference for Java short (16-bit) and byte (8-bit): ranges, casting rules, compound assignment, signed bytes and masking with 0xFF.

byte is an 8-bit signed integer (-128 to 127) and short is a 16-bit signed integer (-32,768 to 32,767). They exist to save memory in large arrays and to represent raw binary data. For ordinary variables, prefer int: the CPU works with 32-bit values anyway, and arithmetic on byte and short is performed as int regardless.

The main surprise is that there are no byte or short literals. A constant like 100 is an int, and the compiler only allows it in an assignment to a byte or short when it can prove the value fits.

Java
byte b = 100;
short s = 30_000;
byte[] buffer = new byte[1024];

Try it

Java Ranges, promotion and casts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Bytes are signed: masking with 0xFF

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
byte b = 127;
short s = -32768;
Type Size Minimum Maximum Wrapper Default
byte 8 bits Byte.MIN_VALUE (-128) Byte.MAX_VALUE (127) Byte 0
short 16 bits Short.MIN_VALUE (-32,768) Short.MAX_VALUE (32,767) Short 0

Usage notes

  • Arithmetic gives int. a + b on two bytes is an int; assign back with a cast, or use +=, which casts for you.
  • Casting wraps, it does not clamp. (byte) 200 is -56 because only the low 8 bits are kept.
  • Bytes are signed. To treat a byte as 0-255, use b & 0xFF or Byte.toUnsignedInt(b). Java 8 added Byte.toUnsignedInt() and Short.toUnsignedInt().
  • Memory. A byte[] really uses one byte per element, which makes it the standard buffer type for I/O, hashing and encoding. A single byte local variable saves nothing.
  • Method overloads. list.remove(someByte) on a List<Integer> picks the index-based remove(int); box deliberately when needed.
  • Constants. final int constants that fit may be assigned to byte without a cast (final int k = 10; byte b = k; compiles).
  • There is no unsigned byte or short; char is the only unsigned 16-bit type.