Learning Objectives
- Distinguish all 8 Java primitive types by bit width and numeric range.
- Explain why stack frames store primitive values directly while holding heap pointers for reference types.
- Prevent silent integer overflow and binary floating-point rounding bugs in financial logic.
- Use Java 10+ local `var` inference cleanly without sacrificing static type safety.
Prerequisites
- JDK 17 or JDK 21 installed locally
- Ability to run a single `Main.java` source file
What Are Variables and Data Types in Java?
Every Java variable reserves a strongly typed slot in memory before your program executes. Unlike dynamically typed languages, the Java compiler (javac) checks every assignment and method call at compile time, catching entire classes of type bugs before production deployment.
Java splits types into two fundamental families: 8 primitive types stored directly as raw values inside the current stack frame (or inline inside object fields), and reference types (classes, interfaces, records, arrays) whose variables hold a reference to an object allocated on the JVM heap.
All 8 Java Primitive Data Types Compared
| Type | Bit Width | Signed Range / Precision | Typical Production Use |
|---|---|---|---|
byte | 8-bit | -128 to 127 | Raw network/file byte streams |
short | 16-bit | -32,768 to 32,767 | Compact legacy binary headers |
int | 32-bit | ~ -2.14B to +2.14B | Loop counters, array indices, small counts |
long | 64-bit | ~ -9.22E18 to +9.22E18 | Database primary IDs, epoch timestamps, ledger paise |
float | 32-bit IEEE 754 | ~6–7 decimal digits | Graphics coordinates, sensor approximations |
double | 64-bit IEEE 754 | ~15–16 decimal digits | Scientific math (never exact money) |
char | 16-bit UTF-16 | '\u0000' to '\uffff' | Single UTF-16 code units |
boolean | JVM-defined | true / false | Branch conditions & feature state flags |
Next Step in the Java Pathway
Once variable types feel natural, continue to Java Classes, Objects and Encapsulation, test yourself in Free Java Mock Tests, or explore our structured Java Backend Development Training Course.
Practical Programming Examples
Safe Arithmetic, Overflow Detection & Exact Money Representation (JDK 21)
Demonstrate binary floating-point drift with double vs exact BigDecimal arithmetic and Math.multiplyExact overflow protection.
import java.math.BigDecimal;
public class DataTypesDemo {
public static void main(String[] args) {
double naive = 0.1 + 0.2;
BigDecimal baseTuition = new BigDecimal("45000.00");
BigDecimal gstRate = new BigDecimal("0.18");
BigDecimal totalPayable = baseTuition.add(baseTuition.multiply(gstRate));
var seatCapacity = 12; // inferred as int at compile time
long maxSafe = Math.multiplyExact(100_000L, 60L);
System.out.println("double 0.1 + 0.2 = " + naive);
System.out.println("Exact tuition + GST = " + totalPayable);
System.out.println("Cohort cap (" + seatCapacity + "), scaled = " + maxSafe);
}
}
double 0.1 + 0.2 = 0.30000000000000004 Exact tuition + GST = 53100.00 Cohort cap (12), scaled = 6000000
- Binary `double` cannot represent base-10 fractions like 0.1 and 0.2 cleanly, printing `0.30000000000000004`.
- Constructing `BigDecimal` from String literals preserves exact base-10 precision for INR currency and tax math.
- `var seatCapacity = 12` infers `int` statically during compilation (`javac`), preserving compile-time checking.
- `Math.multiplyExact` throws `ArithmeticException` instead of silently wrapping around if operands overflow.
Common Mistakes to Avoid
- Comparing `float` or `double` values with `==` or storing INR prices in `double` instead of `BigDecimal` or integer paise (`long`).
- Writing `long id = 100000 * 100000;` — Java multiplies as 32-bit `int` BEFORE widening to `long`; add the `L` suffix (`100_000L`).
- Comparing two boxed `Integer` objects (e.g., `200 == 200`) outside Java’s `-128..127` IntegerCache with `==` instead of `.equals()`.
Production Best Practices
- Use `long` paise (minor units) or `BigDecimal` constructed from `String` for every invoice, GST, and salary ledger calculation.
- Improve readability of large constants with underscores (`45_000_00L`).
- Prefer primitive `int`, `long`, `boolean` on hot paths to avoid unnecessary autoboxing heap allocations.
Technical Interview Relevance
Service and product MNC interviewers frequently ask about String vs Integer caching (`-128..127`), `double` rounding traps, and stack vs heap allocation.
Practice & Self-Check Questions
Why should you pass `"0.1"` (String) instead of `0.1` (double) to `new BigDecimal(...)`?
Passing a double literal forwards the already-inaccurate IEEE-754 approximation (0.10000000000000000555...); passing `"0.1"` parses exact base-10 decimals.
What happens if you assign `int x = 2_000_000_000 + 2_000_000_000;` in Java without `Math.addExact`?
Signed 32-bit two’s complement addition overflows silently and wraps around to a negative number (`-294967296`).