Variables
A variable is a named, typed storage slot holding either a primitive value or a reference to an object. Java requires you to declare its type before you use it.
Detailed Explanation
Every Java variable has three parts: a type, a name, and a value. The type is fixed at compile time and never changes, which is what "statically typed" means. int attempts = 0; creates a slot that can only ever hold an int. Assigning a String to it is a compile error, not a runtime surprise. That strictness is why large Java codebases survive refactoring.
Java has four kinds of variable, and the differences matter more than beginners expect.
Local variables are declared inside a method, constructor, or block. They live on the thread's stack, disappear when the block ends, and are not shared between threads. They have no default value: the compiler performs definite assignment analysis and rejects any read before an assignment.
Instance fields belong to an object. Each instance gets its own copy, they live on the heap inside the object, and they are initialised to a default automatically: 0 for numbers, false for boolean, null for references. They live as long as the object does.
Static fields belong to the class, not to any instance. There is exactly one copy per class per class loader, created when the class is initialised. They are the closest thing Java has to a global, with all the usual dangers.
Parameters are locals that are assigned by the caller before the body runs.
Scope is the region of code where a name is usable. A local is in scope from its declaration to the closing brace of its block, so a variable declared inside an if is gone afterwards. Java forbids shadowing a local with another local in a nested block, unlike C, which removes a whole category of confusion. A field can be shadowed by a local or parameter, which is why constructors are full of this.name = name;.
Naming is a convention but a strongly enforced one: camelCase for locals, fields, and parameters; UPPER_SNAKE_CASE for static final constants. Names should say what the value means. remainingRetries is better than n for the same reason a variable exists at all.
Two modifiers change the behaviour of a variable rather than its type. final means the binding cannot be reassigned after initialisation, though a final reference can still point at a mutable object. volatile on a field affects visibility between threads under the Java memory model, guaranteeing that a write by one thread is seen by others.
Since Java 10, var lets you omit the type of a local when the initialiser makes it obvious. The variable is still statically typed; the compiler infers it. Fields and parameters still need explicit types.
The costs of variable choices are concrete. Wide scope makes code harder to reason about and keeps objects alive longer, delaying garbage collection. Mutable fields shared across threads need synchronisation. Excessive static mutable state makes testing painful because state leaks between tests. Declare as late as you can, as narrowly as you can, and make it final when nothing needs to reassign it.
Code Examples
public class SessionCounter {
// Static field: one copy shared by the whole class, initialised once.
private static int totalSessionsCreated = 0;
// Instance fields: one copy per object. Defaults apply before the constructor runs.
private final String userId; // final: assigned exactly once, in the constructor
private int requestCount; // defaults to 0 automatically
public SessionCounter(String userId) {
this.userId = userId; // 'this.' distinguishes the field from the parameter
totalSessionsCreated++;
}
public void record() {
int previous = requestCount; // local variable, lives only in this method
requestCount = previous + 1;
}
public static void main(String[] args) {
SessionCounter a = new SessionCounter("ada");
SessionCounter b = new SessionCounter("grace");
a.record();
System.out.println(a.requestCount); // prints: 1
System.out.println(b.requestCount); // prints: 0 — separate instance field
System.out.println(totalSessionsCreated); // prints: 2 — shared static field
}
}public class ScopeRules {
public static void main(String[] args) {
int attempts; // declared but not assigned
// System.out.println(attempts); // compile error: might not have been initialized
attempts = 3;
System.out.println(attempts); // prints: 3
if (attempts > 0) {
String message = "retrying"; // scope is this block only
System.out.println(message); // prints: retrying
}
// System.out.println(message); // compile error: message is out of scope
final int maxRetries = 5;
// maxRetries = 6; // compile error: cannot assign a final variable
// final applies to the reference, not to the object it points at.
final StringBuilder log = new StringBuilder("start");
log.append("-done"); // allowed: the object is mutable
System.out.println(log); // prints: start-done
}
}Common Gotchas
Locals are not auto-initialised
fields default to zero or null, locals do not. Reading one before assignment fails to compile, which is the compiler protecting you rather than being pedantic.
A `final` reference is not an immutable object
`final List<String> items` stops reassignment of the variable but still allows `items.add(...)`. Use `List.copyOf` or an unmodifiable wrapper when you want the contents fixed too.
Mutable `static` fields are shared across everything
including across tests running in the same JVM, which produces order-dependent failures. Reserve `static` for constants and genuinely stateless helpers.
Lambdas and anonymous classes need effectively final locals
a local captured by a lambda must never be reassigned. The compiler enforces this because the captured value is copied, and a changing local would silently diverge from the copy.