Skip to main content

Command Palette

Search for a command to run...

Understanding Range in Java Data Types (Complete Guide)

Updated
3 min readView as Markdown

Introduction

When learning Java, one important concept related to data types is range. Many beginners learn data types but don’t understand what range actually means and why it is important.

In simple words:

Range = The minimum and maximum value a data type can store.

Every variable in Java is stored in memory, and memory is limited. Because of this limited memory, each data type can store values only within a fixed limit. This limit is called the range.


Why Range is Important in Java

Range is important because:

  • It helps us choose the correct data type.

  • It prevents overflow errors.

  • It helps optimize memory usage.

  • It is often asked in interviews.

Example:
If you store a value outside the range, Java will give an error or unexpected output.

public class RangeDemo {
    public static void main(String[] args) {
        byte b = 127;
        b++;
        System.out.println(b);
    }
}

Output:

-128

This is called Overflow because the value exceeded the range of byte.


Range of Primitive Data Types in Java

Data 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 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 bytes ±3.4 × 10³⁸
double 8 bytes ±1.7 × 10³⁰⁸
char 2 bytes 0 to 65,535
boolean JVM dependent true / false

How Range is Calculated

The range of integer data types in Java is calculated using the formula:

Range = -2^(n-1) to 2^(n-1) - 1

Where:

  • n = number of bits

Example 1: byte

  • byte = 8 bits

  • Range = -2⁷ to 2⁷ − 1

  • Range = -128 to 127

Example 2: int

  • int = 32 bits

  • Range = -2³¹ to 2³¹ − 1


Understanding Overflow and Underflow

Overflow

When a value becomes greater than the maximum range, it resets to the minimum value.

Example:

127 + 1 = -128

Underflow

When a value becomes smaller than the minimum range, it resets to the maximum value.

Example:

-128 - 1 = 127

Real-Life Example to Understand Range

Think of range like a container capacity:

Data Type Container Size
byte Small cup
short Glass
int Bucket
long Water tank

If you try to store more water than the container → Overflow.


When to Use Which Data Type

Situation Best Data Type
Age byte
Marks short
Population int
Distance in meters long
Decimal values double
Single character char
True/False boolean

Key Points to Remember

  • Range depends on memory size.

  • More memory → Larger range.

  • char stores only positive values.

  • float and double store decimal numbers.

  • Overflow happens when range exceeds.

  • Underflow happens when value goes below range.

More from this blog

Amit singh's blog

235 posts