Course contentsShow
← Java
Lesson 36 of 2,8702. Variables and Primitive TypesFree lesson

Choosing the Right Integer Type for Your Data

Develop guidelines for selecting between byte, short, int, and long based on range requirements and memory constraints.

Choosing the Right Integer Type for Your Data

What you'll learn: How to decide whether to use byte, short, int, or long based on your data's range and memory needs.

The Decision Framework

You've learned Java offers four integer types, but when should you use each one? Think of it like choosing the right container: you wouldn't use a shipping container to store a single coin, nor would you use a matchbox to hold a boulder.

Guidelines for Selection

Start with int

Default choice: Use int for most general-purpose counting and calculations. It's Java's default integer type, optimized for performance, and handles values from about -2 billion to +2 billion—plenty for typical programming tasks.

Choose long for Large Values

When your data exceeds int's range (like timestamps, file sizes, or astronomical distances), use long. Remember the L suffix for literals: long population = 8000000000L;

Use byte or short for Memory Optimization

These smaller types only make sense when memory is truly constrained—typically when storing large arrays of numbers. A single byte variable saves trivial memory, but an array of one million byte values uses 1 MB versus 4 MB for int values.

Practical Examples

  • Age of a person: byte (0–127 covers it)
  • Year: short (handles -32,768 to 32,767)
  • Loop counters: int (default, fast)
  • Credit card numbers: long (16 digits exceed int range)

Key Takeaway: Default to int for general use; choose long when ranges demand it; reserve byte and short for memory-critical situations like large arrays, not individual variables.