iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Variables

Java variables: primitive vs reference, var inference, final, default values, and the scoping rules that bite.

Java — variables

EXAMPLE
// ===== 1. Primitive types =====
int    age       = 30;
long   id        = 4_000_000_000L;
short  s         = 32_000;
byte   b         = 127;
float  ratio     = 0.75f;
double pi        = 3.14159;
boolean ok       = true;
char   ch        = 'A';

// Defaults if uninitialised AS A FIELD (not local):
// int=0, long=0L, double=0.0, boolean=false, char='\u0000'
// Local variables MUST be assigned before use; compile error otherwise.

// ===== 2. Reference types =====
String name = "Alex";
java.util.List<Integer> nums = new java.util.ArrayList<>();
nums.add(1); nums.add(2);

// Default for reference fields is null.

// ===== 3. var (local type inference, Java 10+) =====
var ages = new java.util.HashMap<String, Integer>();
ages.put("alex", 30);
// Inferred as HashMap<String, Integer>.

// Rules: var only on local variables (not fields/params/returns).
// Must have an initialiser. No 'var null', no 'var x[]'.

// ===== 4. final =====
final int LIMIT = 100;          // local final
final String NAME;              // 'blank final' — must be assigned exactly once
NAME = "hello";

// Constants are usually static final on a class:
public class Config {
    public static final int MAX_RETRIES = 3;
}

// final on a reference: the binding is immutable; the OBJECT may still be mutable.
final var list = new java.util.ArrayList<Integer>();
list.add(1);   // ok: the list mutates
// list = ...; // error: cannot reassign the binding

// ===== 5. Scope =====
public void demo() {
    int outer = 1;
    {
        int inner = outer + 1;
        // both visible here
    }
    // inner not visible here
}

// ===== 6. Wrapper types and autoboxing =====
Integer ageBoxed = 30;            // autobox int -> Integer
int back = ageBoxed;              // auto-unbox Integer -> int
// Beware NullPointerException on unboxing a null wrapper.

// ===== 7. Equality (subtle) =====
String a = "hi";
String b = "hi";
String c = new String("hi");
System.out.println(a == b);          // true (string pool intern)
System.out.println(a == c);          // false (different object)
System.out.println(a.equals(c));     // true (value equality)
// Use .equals() for objects; == on references compares identity.

// ===== 8. Modifiers on fields =====
public class Money {
    public final long cents;         // immutable
    private String currency;         // mutable, private
    public static final Money ZERO = new Money(0, "AUD");

    public Money(long cents, String currency) {
        this.cents = cents;
        this.currency = currency;
    }
}

// ===== 9. Records (modern field-bag) =====
public record User(int id, String name) {}
// Auto-generated: constructor, accessors id() name(), equals, hashCode, toString.

// ===== Patterns to internalise =====
// - Default to final on locals/params; it documents intent and helps refactors
// - Prefer var when the right-hand side already names the type clearly
// - Use records for plain value carriers; Money/Order/Address style
// - Watch for autoboxing in hot loops: unboxing nulls throws; boxing churn allocates
// - Equality: == for primitives + identity; .equals() for content

// ===== Pitfalls =====
// - Using == to compare strings -> works for literals, breaks for new String(...)
// - var with a too-clever right-hand side -> reader can't infer the type
// - Forgetting to initialise a local before reading -> compile error
// - Integer == Integer beyond [-128, 127] is false: cached range only
// - Mutating a 'final' reference's contents and assuming immutability

Why it matters

final + var + records are how Java code reads cleanly in 2026. Default to final, use var when it helps readability, and reach for records for value carriers. The classic primitive vs reference and equality traps still bite — once they are reflex, Java stops surprising.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
int age = 36;
double pi = 3.14159;
String name = "Ada";
final int MAX = 100;
Try it Yourself »

Exercise

Declare an immutable int.

int MAX = 100;

Discussion

Loading…