Java Local and Instance Variables, Effectively Final and Varargs (OCP 21)
Variables inside and around Java methods for the OCP 21 exam: the only local variable modifier (final), deferred final assignment, effectively final variables and lambdas, final/volatile/transient instance fields, and the rules for declaring and calling varargs methods.
kvi5hnuCode Sprout team member8 min readOn this page
A method works with two kinds of variables:
- Local variables are declared inside the method, including its parameters. They exist only while their block runs.
- Instance variables (fields) belong to the object, and every object gets its own copy.
public class Lift {
int trips = 0; // instance variable: one per Lift object
int run(int floors) { // floors: a parameter, which is a local variable
int start = 1; // local variable
if (floors > 3) {
long wait = floors * 2L; // local to the if block
trips++;
}
return start + floors; // wait is out of scope here
}
}
When run returns, the local variables floors, start and wait are gone. A value returned from the method lives on, and so does any object that a local variable referred to, as long as something else still refers to it.
Local variable modifiers: only final
A local variable can have exactly one modifier: final. Access modifiers and static belong to class members, so they're not allowed inside a method:
void plan() {
final int a = 1;
final var b = "ok"; // final and var can be combined
private int c = 2; // DOES NOT COMPILE
static int d = 3; // DOES NOT COMPILE
}
A final local doesn't have to be assigned on the line where it's declared. It must be definitely assigned exactly once before it's read:
void fare(boolean peak) {
final int price;
if (peak) price = 4; else price = 3;
System.out.println(price); // fine: assigned on every path
}
void fare2(boolean peak) {
final int price;
if (peak) price = 4;
System.out.println(price); // DOES NOT COMPILE: might not have been initialized
}
final applies to the variable, not to the object it refers to. A final array or StringBuilder can still be changed. You just can't point the variable at a different object:
final int[] counts = new int[3];
final StringBuilder log = new StringBuilder();
counts[1] = 7; // fine: changes the array's contents
log.append("boarded"); // fine: changes the builder's contents
counts = null; // DOES NOT COMPILE
log = new StringBuilder(); // DOES NOT COMPILE
Effectively final
A local variable (or parameter) is effectively final if it's never assigned again after it gets its first value. The final keyword isn't needed. The quick test is to add final to the declaration in your head: if the code would still compile, the variable is effectively final.
String route(int stops) {
String name = "Blue"; // effectively final
var size = 10; // NOT: incremented below
boolean express; // effectively final: assigned once, later
if (stops > 100) size++;
name.toUpperCase(); // result discarded; name isn't reassigned
express = stops < 5;
return name + size + express;
}
nameis effectively final. Calling a method on it doesn't reassign it, and strings are immutable anyway.sizeisn't, becausesize++is an assignment, even though it only runs whenstops > 100.expressis effectively final, because a single deferred assignment is fine.stops(a parameter) is also effectively final, because the method never assigns to it.
Why does this matter? Lambdas and local or anonymous classes may only use local variables that are final or effectively final:
void board() {
int riders = 10;
Runnable r = () -> System.out.println(riders); // DOES NOT COMPILE
riders++; // this assignment makes riders not effectively final
}
The error message is "local variables referenced from a lambda expression must be final or effectively final". It doesn't matter whether the assignment comes before or after the lambda. Any second assignment anywhere in the method breaks the rule. Lambdas are covered in Chapter 8, and local classes in Chapter 7.
Instance variable modifiers
Fields can have any of the four access levels (article 27) plus these specifiers:
| Specifier | Meaning | Covered in |
|---|---|---|
final | must be assigned exactly once for each object | here and Chapter 6 |
static | one copy shared by the class, not one per object | Article 28 |
volatile | reads and writes go straight to main memory, so all threads see them | Chapter 13 |
transient | skipped when the object is serialized | Chapter 14 |
final and volatile can't be combined: a value that never changes has no need for thread visibility rules.
final instance variables
Normal fields get default values (0, false, null). A final field doesn't get a default value. The compiler requires it to be assigned exactly once, in one of these places:
- in its declaration,
- in an instance initializer block, or
- in every constructor, unless that constructor calls another constructor with
this(...)that does the assignment.
public class Ticket {
final String route = "Harbor Line"; // 1. declaration
final int zone;
final String holder;
{ zone = 2; } // 2. instance initializer
Ticket(String holder) { this.holder = holder; } // 3. constructor
Ticket() { this("guest"); } // delegates, so holder is still assigned once
}
Things that don't compile:
final int a; // and no constructor assigns it: "not initialized in the default constructor"
final int b = 1; { b = 2; } // assigned twice
static final fields follow the same idea, but they're assigned in the declaration or in a static initializer block. Chapter 6 covers exactly when each initializer runs.
Varargs
You've used varargs to call methods like String.format. Now let's write our own. A varargs parameter (Type... name) accepts zero or more arguments, and inside the method it's an ordinary array.
Declaring: two rules
- A method can have at most one varargs parameter.
- The varargs parameter must be the last parameter.
void hop1(int... steps) {}
void hop2(String who, int... steps) {}
void hop3(int ...steps) {} // spacing around ... doesn't matter
void hop4(int[]... grid) {} // each argument is an int[]
void hop5(int... steps, String who) {} // DOES NOT COMPILE: not last
void hop6(int... a, int... b) {} // DOES NOT COMPILE: two varargs
void hop7(int.. steps) {} // DOES NOT COMPILE: needs three dots
The error for hop5 and hop6 is "varargs parameter must be the last parameter". In hop6, the first varargs parameter isn't last, so the rule catches both problems.
Calling: five ways

static String trip(String rider, int... stops) { ... }
trip("A"); // stops = new int[0] (never null!)
trip("B", 4); // stops = {4}
trip("C", 4, 9, 12); // stops = {4, 9, 12}
trip("D", new int[] {1, 2}); // stops IS the caller's array
trip("E", (int[]) null); // stops = null
Key points:
- No arguments produce an empty array of length 0, not
null, sostops.lengthis safe. - Passing an existing array passes that array itself, so changes inside the method are visible to the caller.
- Passing
nullgives anullarray, andstops.lengththen throwsNullPointerException. Withint...,trip("E", null)compiles without a warning, becausenullcan't be anintand must be the array itself. With an object type such asString...orObject...,javac -Xlintwarns that the call is ambiguous and suggests a cast. - You can't mix the two forms:
trip("F", new int[] {1}, 2)doesn't compile. - The array shortcut
{1, 2}isn't allowed in a call. Writenew int[] {1, 2}.
The individual arguments are converted to the element type as usual: an int argument may widen for long... or box for Integer.... An int[] is never converted to a long[] or an Integer[], though.
static void sum(long... n) {}
sum(1, 2); // ints widen to long
sum(new int[] {1}); // DOES NOT COMPILE: int[] is not long[]
Accessing the elements
Inside the method, you work with the varargs parameter as an array:
static int second(int... values) {
return values[1]; // ArrayIndexOutOfBoundsException if fewer than 2 were passed
}
second(11, 77); // 77
Because varargs is an array underneath, void w(int... a) and void w(int[] a) have the same signature and can't both be declared in one class. How Java chooses between varargs and non-varargs overloads is covered in article 30.
What's current
- The effectively final and varargs rules are unchanged through Java 25.
- Java 22's unnamed variables (
_) can replace locals you never read, but not method parameters.
Exam traps from this article
A complete example
The program uses a deferred final local, captures effectively final variables in a lambda, changes the contents of final references, initializes final fields in all three allowed places, and calls a varargs method in every supported way.
import java.util.Arrays;
import java.util.function.Supplier;
public class Solution {
// final instance fields: each must be assigned exactly once per object.
static class Ticket {
final String route = "Harbor Line"; // at the declaration
final int zone; // in an instance initializer
final String holder; // in every constructor
{
zone = 2;
}
Ticket(String holder) {
this.holder = holder;
}
Ticket() {
this("guest"); // delegating constructor assigns it
}
@Override
public String toString() {
return holder + " on " + route + ", zone " + zone;
}
}
// A varargs parameter must be the last one, and there can be only one.
static String trip(String rider, int... stops) {
if (stops == null) {
return rider + ": stops array is null";
}
return rider + ": " + stops.length + " stop(s) " + Arrays.toString(stops);
}
static int total(int first, int... more) {
int sum = first;
for (int m : more) {
sum += m;
}
return sum;
}
public static void main(String[] args) {
System.out.println("== final and effectively final locals");
final int fare; // assigned later, exactly once
boolean peak = args.length > 5; // false when run without arguments
if (peak) {
fare = 4;
} else {
fare = 3;
}
String line = "Blue"; // never reassigned: effectively final
int riders = 10;
riders++; // reassigned: NOT effectively final
Supplier<String> label = () -> line + " line, fare " + fare;
System.out.println(label.get() + ", riders " + riders);
final int[] counts = new int[3]; // final reference, mutable contents
counts[1] = 7;
final StringBuilder log = new StringBuilder("log:");
log.append(" boarded");
System.out.println(Arrays.toString(counts) + " " + log);
System.out.println("\n== final instance fields");
System.out.println(new Ticket("Ana"));
System.out.println(new Ticket());
System.out.println("\n== varargs calls");
System.out.println(trip("A"));
System.out.println(trip("B", 4));
System.out.println(trip("C", 4, 9, 12));
System.out.println(trip("D", new int[] {1, 2}));
System.out.println(trip("E", (int[]) null));
System.out.println("total = " + total(5) + ", " + total(5, 6, 7));
}
}
Output:
== final and effectively final locals
Blue line, fare 3, riders 11
[0, 7, 0] log: boarded
== final instance fields
Ana on Harbor Line, zone 2
guest on Harbor Line, zone 2
== varargs calls
A: 0 stop(s) []
B: 1 stop(s) [4]
C: 3 stop(s) [4, 9, 12]
D: 2 stop(s) [1, 2]
E: stops array is null
total = 5, 18
Points to notice:
fareis declaredfinalwithout a value and is assigned once in each branch, so the lambda can use it.lineis captured without thefinalkeyword because it's effectively final.ridersis printed directly instead, sinceriders++means it's not effectively final.- The no-argument
Ticket()constructor never assignsholderitself. It delegates withthis("guest"), which counts as the one assignment. trip("A")gets an empty array, whiletrip("E", (int[]) null)getsnull, which the method checks for before reading the length.
Common questions
Is it good practice to mark every local variable final?
Opinions differ. Some teams require it, but many consider it noise, because the compiler already tracks effectively final variables. Marking a variable final is most useful in long methods where an accidental reassignment would be hard to spot.
Are parameters effectively final? Yes, unless the method assigns to them. A parameter is a local variable that the caller initializes.
Can I use var with varargs?
No. var is only for local variables with an initializer, not for parameters (except lambda parameters, Chapter 8).
What did Java 22 add here?
Unnamed variables (JEP 456, final in Java 22) let you write _ for a local variable, catch parameter, lambda parameter or pattern variable that you never use, such as for (var _ : list) count++;. They aren't on the Java 21 exam.
Summary
- Local variables (including parameters) live only while their block runs, and their only possible modifier is
final. - A
finallocal must be assigned exactly once before it's used. A variable that's never reassigned is effectively final, and only final or effectively final locals can be used in lambdas and local classes. - Instance variables can be
final,volatileortransient(plusstatic). Afinalfield must be assigned exactly once, in its declaration, in an initializer or in every constructor. - A varargs parameter must be the last one and can appear only once. Inside the method, it's an array.
- A varargs call can pass nothing (empty array), individual values, an existing array or
null, but it can't mix values with an array.
Practice quiz
Test yourself with the local and instance variables and varargs quiz: 10 exam-style questions with explanations.
Previous: Java Method Declarations: Access Modifiers, Specifiers, Return Types and Parameters (OCP 21)
Next: Java Access Modifiers: private, Package, protected and public (OCP 21)
Related reading
- Java Method Declarations: Access Modifiers, Specifiers, Return Types and Parameters (OCP 21)
- Java Period, Duration, Instant and Daylight Saving Time (OCP 21)
- Java Date and Time: LocalDate, LocalTime, LocalDateTime and ZonedDateTime (OCP 21)
- Java Math API, BigInteger and BigDecimal (OCP 21)
- Java Arrays: equals, compare, mismatch, Varargs and Multidimensional Arrays (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.