Skip to main content
Beginner Step-by-Step Tutorial 9 min read Java 21 LTS (Applicable Java 8–21)

Java Variables and Data Types Explained with Memory Examples

Understand Java primitive types, object references, overflow guards, BigDecimal for money calculations, and Java 10+ local var inference.

Written by MockAttempt Engineering Editorial Desk (Curriculum & Code Verification Review Panel) Reviewed by Ravi Shankar Mishra
Last updated: Verification Policy

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

TypeBit WidthSigned Range / PrecisionTypical Production Use
byte8-bit-128 to 127Raw network/file byte streams
short16-bit-32,768 to 32,767Compact legacy binary headers
int32-bit~ -2.14B to +2.14BLoop counters, array indices, small counts
long64-bit~ -9.22E18 to +9.22E18Database primary IDs, epoch timestamps, ledger paise
float32-bit IEEE 754~6–7 decimal digitsGraphics coordinates, sensor approximations
double64-bit IEEE 754~15–16 decimal digitsScientific math (never exact money)
char16-bit UTF-16'\u0000' to '\uffff'Single UTF-16 code units
booleanJVM-definedtrue / falseBranch 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.

JDK 21 LTS (javac / java)
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);
    }
}
Expected Output
double 0.1 + 0.2 = 0.30000000000000004
Exact tuition + GST = 53100.00
Cohort cap (12), scaled = 6000000
Step-by-Step Execution
  1. Binary `double` cannot represent base-10 fractions like 0.1 and 0.2 cleanly, printing `0.30000000000000004`.
  2. Constructing `BigDecimal` from String literals preserves exact base-10 precision for INR currency and tax math.
  3. `var seatCapacity = 12` infers `int` statically during compilation (`javac`), preserving compile-time checking.
  4. `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`).

Optional Next Step

Have Questions About Learning Core Java Structured Cohorts?

Request the JBCP syllabus & weekend batch schedule from an Academic Counselor.

View JBCP Details →
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.