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.
byte b = 100; short s = 30_000; byte[] buffer = new byte[1024];
Try it
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.
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
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 + bon two bytes is anint; assign back with a cast, or use+=, which casts for you. - Casting wraps, it does not clamp.
(byte) 200is -56 because only the low 8 bits are kept. - Bytes are signed. To treat a byte as 0-255, use
b & 0xFForByte.toUnsignedInt(b). Java 8 addedByte.toUnsignedInt()andShort.toUnsignedInt(). - Memory. A
byte[]really uses one byte per element, which makes it the standard buffer type for I/O, hashing and encoding. A singlebytelocal variable saves nothing. - Method overloads.
list.remove(someByte)on aList<Integer>picks the index-basedremove(int); box deliberately when needed. - Constants.
final intconstants that fit may be assigned tobytewithout a cast (final int k = 10; byte b = k;compiles). - There is no unsigned
byteorshort;charis the only unsigned 16-bit type.
Related
- int
- char
- Type conversions
- Bitwise operators
- Tutorial: Primitive types