The short Type: Small Range Integers
What you'll learn: How to use the short type to store smaller whole numbers while saving memory.
What is short?
You've already met int (Java's standard integer) and long (for extra-large numbers). The short type goes the opposite direction—it's a 16-bit integer designed for situations where you need whole numbers but don't need the full range of int.
Think of it like choosing the right container: you wouldn't use a shipping truck to deliver a sandwich. Similarly, if you're storing numbers that never exceed a few thousand, short uses less memory than int.
The Range of short
A short can hold values from -32,768 to 32,767. That's much smaller than int (which goes into the billions), but sometimes that's all you need.
Declaring and Using short
short age = 25;
short temperature = -40;
short year = 2024;
Notice you declare it just like int, but use the keyword short instead.
When Should You Use short?
Use short when:
- You're working with thousands of numbers and need to save memory
- You're certain your values will stay within -32,768 to 32,767
- Memory efficiency matters (like in large data structures)
For everyday programming, stick with int. But when you're handling large arrays or data sets where every byte counts, short can make a real difference—it uses half the memory of an int (2 bytes vs. 4 bytes).
Key Takeaway: The short type stores 16-bit integers ranging from -32,768 to 32,767, offering a memory-efficient alternative to int when you're certain your values will stay small.