The <code>short</code> Primitive in Java β 16-bit Integer
short is a 16-bit signed integer, range -32 768 to 32 767. In modern code you almost never reach for it β int is the same speed (usually faster, because the JVM aligns to 32 bits) and doesn't overflow as easily.
When it still matters
Only one scenario: large arrays. A short[1_000_000] uses 2 MB; an int[1_000_000] uses 4 MB. For an audio buffer, image pixel channel, or network protocol struct, the memory win justifies the type.
Declaration
short s = 1000;
short max = Short.MAX_VALUE; // 32767
// short s = 40000; // β compile error β out of range
short cast = (short) 40000; // -25536 β wraps silently
Arithmetic promotes to int
short a = 10, b = 20;
short sum = a + b; // β compile error β result is int
short sum2 = (short) (a + b); // β
cast needed
Common mistakes
- Using
shortfor "small" values β there's no performance benefit overintand you lose almost half your range. - Forgetting the cast on arithmetic results β Java always widens to
int. - Assuming unsigned behaviour β it's signed. For unsigned 16-bit, use
intwith a(short) (x & 0xFFFF)pattern.
Related
Pillar: Java primitives. Prefer int in most cases. See also byte.