Overview
short is an integer data type that stores whole numbers in
2 bytes (16 bits) of memory. Its range is -32,768 to 32,767.
It holds much larger values than byte and uses half the memory of int.
Like byte, a short needs no suffix. Java accepts short a = 100; because 100 is a constant that fits within the short range.
Step-by-Step Explanation
1
Declare and Initialise short Variables
Values must be between -32,768 and 32,767.
short a = 100;
short b = -50;
short is the data type, and a and b are the variable names. Both values fit within the range, so they're stored without any problem.
2
Print the Values
Text and values joined with +.
System.out.println("a = " + a);
System.out.println("b = " + b);
The + operator joins the label and the value, so the output is a = 100 and b = -50.
3
Range of short
The largest and smallest values.
System.out.println("Max short value = " + Short.MAX_VALUE);
System.out.println("Min short value = " + Short.MIN_VALUE);
Short is the wrapper class for short. Short.MAX_VALUE is 32767 and Short.MIN_VALUE is -32768.
With 16 bits, a short can store $$2^{16} = 65536$$ different values, from $$-2^{15}$$ to $$2^{15} - 1$$.
4
short + short Gives an int
Type promotion in arithmetic.
int sum = a + b;
System.out.println("sum = " + sum);
Before doing arithmetic, Java converts short values to int. So a + b is an int, and the result 50 is stored in an int variable.
Writing short sum = a + b; gives a compile error.
5
Overflow with a Cast
Values outside the range wrap around.
short overflow = (short) 40000;
System.out.println("(short) 40000 = " + overflow);
40000 is larger than 32767, so short overflow = 40000; won't compile. The (short) cast forces it, and the value wraps around:
$$40000 - 65536 = -25536$$
short at a Glance
| Property |
Value |
| Size |
2 bytes (16 bits) |
| Range |
-32,768 to 32,767 |
| Default value (fields) |
0 |
| Literal suffix |
None |
| Wrapper class |
Short |
Java Integer Types Compared
| Type |
Size |
Range |
byte |
1 byte |
-128 to 127 |
short |
2 bytes |
-32,768 to 32,767 |
int |
4 bytes |
-2,147,483,648 to 2,147,483,647 |
long |
8 bytes |
About ±9.22 × 1018 |
Output
a = 100
b = -50
Max short value = 32767
Min short value = -32768
sum = 50
(short) 40000 = -25536
Common Mistakes
Assigning a value outside the range
short a = 40000; gives the error incompatible types: possible lossy conversion from int to short.
Storing short arithmetic in a short
short sum = a + b; doesn't compile because a + b is an int. Use an int variable or cast the result with (short).
Casting without checking the range
A cast hides the error but doesn't fix it. (short) 40000 silently becomes -25536.
Good practice
Use int for everyday whole numbers. Use short only when memory matters, such as large arrays of small values or binary file formats.
Key Takeaway
short stores whole numbers from -32,768 to 32,767 in 2 bytes.
Arithmetic on shorts gives an int, and casting a value outside the range makes it wrap around.