🎯 What you will learn

Before you can write a loan calculator, a currency converter, or a user-login check, you need to know what kinds of values Java can store and how memory handles them. Java is a statically typed language — every variable has a type that is fixed at compile time. That means the compiler catches type errors before your code ever runs.

Two worlds of types in Java:
Primitives — byte, short, int, long, float, double, char, boolean — stored directly on the stack.
Reference types — String, arrays, objects — the reference lives on the stack, the actual data on the heap.

💼 Interview reality: "What is the default value of an int? Of a boolean? Of a reference type?" — asked constantly in campus placements. Defaults are 0, false, and null respectively. Local variables (inside methods) have no default — using an uninitialised local is a compile error.

🔢 The eight primitive types

TypeSizeRange / NotesExample literal
byte1 byte-128 to 127byte b = 100;
short2 bytes-32 768 to 32 767short s = 30000;
int4 bytes~-2.1B to 2.1Bint i = 1_500_000;
long8 bytes±9.2 × 10¹⁸long l = 9_000_000_000L;
float4 bytes~7 decimal digitsfloat f = 3.14f;
double8 bytes~15 decimal digitsdouble d = 8.75;
char2 bytes0 to 65 535 (Unicode)char c = 'A';
boolean1 bit logicaltrue / falseboolean ok = true;

Notice the underscore in 1_500_000 — Java allows underscores in numeric literals (Java 7+) to improve readability for large numbers. They have no runtime effect.

javac Primitives.java && java Primitives
Primitives.javaLesson 01 · all eight primitives
verified output
byte : 127 short : 32000 int : 1500000 long : 9000000000 float : 3.14 double : 3.141592653589793 char : A boolean : true

🔄 Type casting — widening vs narrowing

Widening conversions (smaller → larger type) are automatic — Java does them for you because no data is lost. Narrowing conversions (larger → smaller) require an explicit cast, and you can lose data.

javac TypeCasting.java && java TypeCasting
TypeCasting.javaLesson 01 · widening & narrowing
verified output
int salary: 85000 long salary: 85000 double salary: 85000.0 double rate : 8.75 int rate : 8 ← decimal truncated

✨ The var keyword (Java 10+)

var lets the compiler infer the type from the right-hand side. It is not dynamic typing — the type is still fixed at compile time. It is just less typing for the developer.

javac VarKeyword.java && java VarKeyword
VarKeyword.javaLesson 01 · local type inference
verified output
Account : SB-2024-78921 Balance : ₹120500.75 Branch : 40 KYC OK : true var types are inferred once and then fixed.

🏦 Real-world scenario

🏦
Real-world scenario · SouthBank India
Arjun models account data with the right types

Arjun's tech lead tells him: "We are storing loan amounts up to ₹5 crore. Account IDs are strings. Verified flags are booleans. Don't use int for money." Arjun must pick the right types. Here is what he writes — and why primitives vs references matter for memory and correctness.

javac ReferencesVsPrimitives.java && java ReferencesVsPrimitives
ReferencesVsPrimitives.javaSouthBank India · stack vs heap demo
verified output
a after changing b: 1000 bank1: SouthBank India bank2: NairaSwift null ref: null

🧠 Stack vs heap — visual

When you write int age = 28, the value 28 lives directly in the stack frame. When you write String name = "Arjun", the reference (a pointer) lives on the stack, but the actual "Arjun" string object is allocated on the heap.

Stack (per thread) primitives + references int balance = 85000; String id = ref→ boolean ok = true; Heap (shared) objects (new / String literals) "SB-2024-78921"

🧩 Mini challenge

Three variable exercises
Task 1 — Overflow demo

Declare byte limit = 127 then do limit++. Print the result — you will see it wraps to -128. This is integer overflow. Now explain why you should use int instead of byte for general counters.

Task 2 — Casting gotcha

Write a program that stores the loan EMI as double emi = 14_333.67. Cast it to int with and without rounding ((int) emi vs (int) Math.round(emi)). Print both. Observe the difference.

Task 3 — var inference

Rewrite the VarKeyword example using explicit types instead of var. Confirm both compile to identical bytecode. Then decide: when is var helpful and when does it hurt readability?

🎤 Interview Q&A

EasyWhat is the difference between int and Integer in Java?
+

int is a primitive type — it stores the value directly on the stack and cannot be null. Integer is a wrapper class (a reference type) that boxes the int value inside an object on the heap. You need Integer when working with generics (List<Integer> — you cannot write List<int>), when you need null to represent "no value", or when calling methods like Integer.parseInt(). Java auto-boxes and auto-unboxes between the two, but repeated boxing inside loops creates unnecessary heap objects.

EasyWhat are the default values for Java primitive types?
+

Class-level (instance/static) fields get default values: int/short/byte/long → 0; float/double → 0.0; char → '\u0000'; boolean → false; any reference type → null. Local variables (inside methods) do NOT get default values — the compiler forces you to initialise them before use or it refuses to compile.

MediumWhy should you use long or BigDecimal instead of double for financial amounts?
+

double uses binary floating point (IEEE 754), which cannot represent many decimal fractions exactly. 0.1 + 0.2 in double gives 0.30000000000000004 — a tiny rounding error that compounds when you sum thousands of transactions. For currency: store amounts as paise/kobo/cents in a long (divide by 100 for display), or use java.math.BigDecimal with exact decimal arithmetic. In a real banking app like SouthBank India's ledger, a rounding error of ₹0.01 per transaction across 10 million accounts is a ₹100,000 reconciliation nightmare.

MediumWhat does var do — does it make Java dynamically typed?
+

No. var (Java 10+) is local variable type inference — the compiler infers the type from the initialiser at compile time. The type is still fixed and strongly typed. You cannot reassign a var-declared variable to a different type later. It cannot be used for method parameters, return types, or fields. It is a developer convenience feature, not dynamic typing. Python's type system is dynamic; Java's is not.

HardExplain string interning and the string pool. When does == work for String comparison?
+

Java maintains a String pool (part of the heap in modern JVMs). String literals ("SouthBank") are interned — the JVM stores one copy and reuses it. Two literals with the same value share the same pool object, so == (reference equality) returns true for them. But new String("SouthBank") always creates a new heap object outside the pool, so == returns false even if the content is identical. Always use .equals() to compare String content — never ==. The pool can be manually queried with String.intern().

📝 Quiz — 5 questions

Question 1 of 5
Which primitive type is 8 bytes and can store values up to ±9.2 × 10¹⁸?
Question 2 of 5
What happens when you cast double loanRate = 8.75 to int?
Question 3 of 5
What is the default value of a boolean field in a Java class?
Question 4 of 5
What does var do in Java 10+?
Question 5 of 5
Why should you NOT use double for financial calculations?
0
/ 5
Quiz complete!

Next up: operators and expressions →

⚠️ Common mistakes

Missing L suffix on long literals
long aadhaarNum = 9876543210; fails — the literal exceeds int range. Add L: 9876543210L. Without it, the compiler treats the literal as int and reports "integer number too large".
Missing f suffix on float literals
float rate = 8.5; fails — 8.5 is a double literal by default. You need float rate = 8.5f;. Without the f, Java reports "possible lossy conversion from double to float".
Comparing Strings with ==
if (name == "Arjun") compares references, not content. Use name.equals("Arjun") or "Arjun".equals(name) (safer — avoids NullPointerException if name is null).
Using double for money
Store rupee amounts as paise in a long (₹1.00 = 100L) or use BigDecimal. Double causes rounding drift across summations. A loan EMI miscalculated by ₹0.01 across 1 million accounts is ₹10,000 in reconciliation error.

✅ Key takeaways

  • Java has 8 primitive types: byte, short, int, long, float, double, char, boolean — all stored by value on the stack.
  • Reference types (String, arrays, objects) store a pointer on the stack; the actual object lives on the heap.
  • Widening casts (int→long, int→double) are automatic; narrowing casts require explicit (type) syntax and can lose data.
  • var infers the local variable type at compile time — Java is still statically typed, just less verbose.
  • Never use double for currency — use long (paise/cents) or BigDecimal for exact decimal math.
  • Always compare String content with .equals(), never with == (which checks reference identity).
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

From javac to production Spring Boot

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →