Numbers in Java: Types, Ranges, and Wrappers

Introduction

In Variables you met int, double, and other types briefly. This chapter goes deeper into numeric types in Java: ranges, when to choose each type, wrapper classes, and autoboxing. Declaration and assignment basics are not repeated here—focus is on types and numeric behavior.

Prerequisites

Java Numeric Types Overview

Integer Types (whole numbers)

TypeSizeApproximate rangeTypical use
byte8 bit−128 to 127Compact binary data, IO buffers
short16 bit−32,768 to 32,767Legacy/specialized formats
int32 bitabout ±2.1 billionDefault choice for counts, indexes
long64 bitvery large integerstimestamps, large IDs

Floating-Point Types (decimals)

TypeSizeNotesTypical use
float32 bitsuffix f on literalsGraphics, memory-sensitive arrays
double64 bitDefault for decimalsprices, science, Math results
java
int studentCount = 30;
double averageScore = 88.5;
long worldPopulation = 8_100_000_000L;  // L suffix for long literals
float temperature = 36.6f;              // f suffix for float literals

Tip

When to Choose Which Type

  • Whole numbers → start with int
  • Very large whole numbers → long
  • Decimals → double
  • Only use byte / short / float when you have a specific reason (size, API, hardware)

Underscores in literals (8_100_000_000L) improve readability; the compiler ignores them.

1) int — Default Integer

Use int for quantities that are always whole numbers.

java
int apples = 12;
int daysLeft = 7;
int total = apples + daysLeft;
System.out.println(total);  // 19

2) long — Large Integers

When values may exceed int range, use long and add L to literals:

java
long fileSizeBytes = 5_000_000_000L;

Without L, a huge literal may not compile as int.

3) double — Default Decimal

Use double for prices, measurements, and most math with fractions.

java
double price = 19.99;
double discount = 2.5;
double finalPrice = price - discount;
System.out.println(finalPrice);  // 17.49

4) float vs double

float uses less memory but less precision. In application code, double is more common. Use float when an API requires it or memory matters at large scale.

java
float ratio = 0.75f;   // f required
double precise = 0.75; // default floating literal is double

5) byte and short

Rare in everyday business logic; appear in low-level IO, protocols, and some libraries. Know they exist; default to int unless documentation says otherwise.

Wrapper Classes and Autoboxing

Each primitive has a wrapper class in the java.lang package:

PrimitiveWrapper
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble

Wrappers let primitives participate in generics and collections (e.g. List<Integer> later).

Autoboxing: primitive → wrapper automatically

java
Integer boxed = 42;        // autoboxing int to Integer
int unboxed = boxed;       // unboxing Integer to int
java
Integer a = 100;
Integer b = 100;
System.out.println(a == b);  // may be true for small cached values
 
Integer x = 1000;
Integer y = 1000;
System.out.println(x == y);        // false — different objects
System.out.println(x.equals(y));   // true — same numeric value

Warning

For wrapper objects, compare values with .equals(), not ==, except when you intentionally compare references. This mirrors String behavior you will see in Strings.

Useful Numeric Operations

Math class (common methods)

java
System.out.println(Math.abs(-12));      // 12
System.out.println(Math.max(78, 95));   // 95
System.out.println(Math.min(78, 95));   // 78
System.out.println(Math.pow(2, 10));    // 1024.0
System.out.println(Math.round(3.6));    // 4 (long returned)

Rounding decimals for display

For formatted output, you will use String formatting in Strings. Quick approach:

java
double pi = 3.1415926;
System.out.printf("pi ≈ %.2f%n", pi);  // pi ≈ 3.14

Floating-Point Precision

Some decimal calculations look slightly “wrong”:

java
System.out.println(0.1 + 0.2);  // 0.30000000000000004

This is expected with binary floating-point—not a Java bug. For money, teams often use BigDecimal (advanced topic); for learning, know the limitation exists.

Real Mini Example: Shopping Subtotal

java
public class ShoppingTotal {
    public static void main(String[] args) {
        double unitPrice = 19.99;
        int quantity = 3;
        double discountRate = 0.10;
 
        double subtotal = unitPrice * quantity;
        double discountAmount = subtotal * discountRate;
        double finalTotal = subtotal - discountAmount;
 
        System.out.printf("Subtotal: $%.2f%n", subtotal);
        System.out.printf("Final total: $%.2f%n", finalTotal);
    }
}

Hard-coded values here; Sum of Two Numbers introduces reading input with Scanner.

Common Beginner Mistakes

Mistake 1: Integer Overflow

java
int big = 2_000_000_000;
big = big + 500_000_000;  // overflows; result wraps incorrectly

Use long when sums can grow large.

Mistake 2: Forgetting L or f Suffixes

java
// long seconds = 9999999999;  // may not compile — too big for int literal
long seconds = 9999999999L;

Mistake 3: Comparing Integer with ==

Prefer .equals() for wrapper objects when comparing values.

Practice Challenge

Build a score summary (hard-coded or with Scanner if you already read ahead):

  1. Three double exam scores
  2. Print average (two decimals), highest, and lowest using Math.max / Math.min

What’s Next

Read user input and add two numbers in Sum of Two Numbers.

FAQ

Should I always use double for safety?

No. Use int for whole counts; use double when fractions matter. Clear types document intent.

Why does 0.1 + 0.2 not equal exactly 0.3?

Binary floating-point cannot represent every decimal exactly. Use rounding for display; use BigDecimal for strict financial rules later.

What is the difference between int and Integer?

int is a primitive; Integer is an object wrapper. Autoboxing bridges them when needed.

When do I need long instead of int?

When values may exceed about ±2.1 billion, or when APIs use long (timestamps in milliseconds).

Do I need to memorize every type’s byte size?

Not immediately. Remember int + double as defaults; look up others when a library or problem requires them.