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)
| Type | Size | Approximate range | Typical use |
|---|---|---|---|
byte | 8 bit | −128 to 127 | Compact binary data, IO buffers |
short | 16 bit | −32,768 to 32,767 | Legacy/specialized formats |
int | 32 bit | about ±2.1 billion | Default choice for counts, indexes |
long | 64 bit | very large integers | timestamps, large IDs |
Floating-Point Types (decimals)
| Type | Size | Notes | Typical use |
|---|---|---|---|
float | 32 bit | suffix f on literals | Graphics, memory-sensitive arrays |
double | 64 bit | Default for decimals | prices, science, Math results |
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 literalsTip
When to Choose Which Type
- Whole numbers → start with
int - Very large whole numbers →
long - Decimals →
double - Only use
byte/short/floatwhen 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.
int apples = 12;
int daysLeft = 7;
int total = apples + daysLeft;
System.out.println(total); // 192) long — Large Integers
When values may exceed int range, use long and add L to literals:
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.
double price = 19.99;
double discount = 2.5;
double finalPrice = price - discount;
System.out.println(finalPrice); // 17.494) 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.
float ratio = 0.75f; // f required
double precise = 0.75; // default floating literal is double5) 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:
| Primitive | Wrapper |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
Wrappers let primitives participate in generics and collections (e.g. List<Integer> later).
Autoboxing: primitive → wrapper automatically
Integer boxed = 42; // autoboxing int to Integer
int unboxed = boxed; // unboxing Integer to intInteger 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 valueWarning
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)
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:
double pi = 3.1415926;
System.out.printf("pi ≈ %.2f%n", pi); // pi ≈ 3.14Floating-Point Precision
Some decimal calculations look slightly “wrong”:
System.out.println(0.1 + 0.2); // 0.30000000000000004This 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
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
int big = 2_000_000_000;
big = big + 500_000_000; // overflows; result wraps incorrectlyUse long when sums can grow large.
Mistake 2: Forgetting L or f Suffixes
// 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):
- Three
doubleexam scores - 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.