Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)
Variable rules for the OCP Java 21 exam: legal identifiers and reserved words, declaring several variables in one statement, final locals, definite assignment, default values for fields, method parameters, every rule of var, and Java 22's unnamed variables.
kvi5hnuCode Sprout team member10 min readOn this page
A variable is a named piece of memory with a type. You declare it by stating the type and a name, and you initialize it by giving it its first value:
String cityName = "Lisbon"; // declared and initialized in one statement
This article covers the rules the exam tests: which names are legal, how many variables a statement declares, which variables get default values, when the compiler insists on initialization, and exactly where var is allowed.
Identifiers
An identifier is a name you choose for a variable, method, class, interface, record, enum or package. Four rules decide whether it's legal:
- It must start with a letter, a currency symbol (
$,€,£,¥and so on) or_. - After the first character, it may also contain digits.
- A single underscore
_on its own is not a legal name. - It can't be a reserved word, and it can't be the literal
true,falseornull.
"Letter" includes letters from any alphabet, so café and größe are legal names. Java is case-sensitive, so Class, NULL and Public are legal (and terrible) names.
| Legal | Not legal |
|---|---|
okName | 3dPoint: starts with a digit |
$price2 | hollywood@vine: @ isn't allowed |
_alsoOk | *$coffee: starts with * |
__ (two underscores) | _: a single underscore |
€uro | public: a reserved word |
var | true: a literal |
Reserved words
Java reserves these keywords. You don't need to memorize the list, but you should recognize the common ones:
abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while _
Some notes:
constandgotoare reserved but do nothing. They exist so that code written in the style of other languages fails to compile.strictfpis obsolete. Since Java 17 all floating-point arithmetic is strict, so the modifier has no effect andjavacwarns when it's used. It's still reserved.true,falseandnullare literals, not keywords, but they can't be used as names either.- Contextual keywords have special meaning only in certain places. They include
var,yield,record,sealed,non-sealed,permits,when,module,requires,exports,opens,to,uses,provides,with,openandtransitive. Most of them are legal variable and method names, soint record = 1;compiles. Two exceptions:non-sealedcan never be an identifier because of its hyphen, andvar,yield,record,sealedandpermitscan't be used as the name of a class, interface, enum or record.
Naming conventions
The exam ignores conventions in identifier questions, but follows them everywhere else, and so should you:
- camelCase with a lowercase first letter for variables and methods:
ticketPrice,toUpperCase(). - camelCase with an uppercase first letter for types:
ArrayList,TicketOffice. - UPPER_SNAKE_CASE for constants and enum values:
MAX_SEATS. - Lowercase, dot-separated names for packages:
com.example.zoo.
Declaring several variables in one statement
One statement can declare several variables, if they share one type written once:
String s1, s2; // two Strings, neither initialized
String s3 = "yes", s4 = "no"; // two Strings, both initialized
int i1, i2, i3 = 0; // three ints, but only i3 is initialized
Each comma-separated part is its own little declaration. In the last line, = 0 belongs to i3 alone. That's the trap: i1 and i2 are declared but not initialized.
Which of these compile?
boolean b1, b2; // yes
String s1 = "1", s2; // yes: s1 initialized, s2 not
double d1, double d2; // NO: the type may appear only once
int i1; int i2; // yes: two separate statements on one line
int i3; i4; // NO: "i4;" on its own is not a statement
int num, String value; // NO: one statement can't declare two types
When a line contains several semicolons, split it into separate lines in your head and check each statement on its own.
Local variables
A local variable is declared inside a method, constructor or initializer block. Local variables have no default value. The compiler refuses to let you read one until it's definitely assigned:
int y = 10;
int x;
int reply = x + y; // DOES NOT COMPILE: variable x might not have been initialized
The compiler tracks every possible path through the code:
public void pickPrice(boolean member) {
int price;
int unused; // never read, so it never needs a value
int onlyIfTrue;
if (member) {
onlyIfTrue = 5;
price = 8;
} else {
price = 12;
}
System.out.println(price); // OK: assigned on both paths
System.out.println(onlyIfTrue); // DOES NOT COMPILE: might not have been initialized
}
The compiler doesn't evaluate your conditions. Even if member is always true in practice, the compiler only sees that the else path leaves onlyIfTrue unassigned. On the exam, take a second look at any local variable declared without a value.
final local variables
A final local variable can be assigned only once:
final int limit = 10;
limit = 20; // DOES NOT COMPILE
final int[] scores = new int[3];
scores[0] = 95; // OK: the array object can change
scores = new int[5]; // DOES NOT COMPILE: the reference can't
final freezes the variable, not the object it refers to. A final local can also be declared first and assigned later, exactly once. A variable that is never reassigned after initialization is effectively final even without the keyword, which matters for lambdas and inner classes in later chapters.
Method and constructor parameters
Parameters behave like local variables that the caller has already initialized. Inside the method you can always read them. The caller, however, must pass values that are themselves initialized:
public void showPrice() {
boolean flag;
pickPrice(flag); // DOES NOT COMPILE: flag might not have been initialized
}
Instance and class variables
Variables declared in a class but outside any method are fields:
- An instance variable belongs to one object. Each object has its own copy.
- A class variable is declared
staticand is shared by the class and all its instances. The methods chapter coversstaticin depth.
Fields always start with a default value, so you never have to initialize them:
| Type | Default |
|---|---|
byte, short, int, long | 0 |
float, double | 0.0 |
boolean | false |
char | '\u0000' (the NUL character) |
| any reference type | null |
That's the key difference to remember: fields get defaults, local variables never do.
var: local variable type inference
Since Java 10 you can write var instead of a type when declaring a local variable. The compiler infers the type from the initializer:
var name = "Hello"; // String
var size = 7; // int
var total = 7 * 2L; // long
var ratio = 7 / 2.0; // double
var is not dynamic typing. The type is fixed at compile time, exactly as if you had written it:
var number = 7;
number = 4; // OK, still an int
number = "five"; // DOES NOT COMPILE: String can't be converted to int
Where var is allowed
| Allowed | Not allowed |
|---|---|
| Local variables with an initializer | Fields (instance or static variables) |
for loop variables: for (var i = 0; ...) | Method and constructor parameters |
Enhanced for variables: for (var s : list) | Method return types |
try-with-resources variables | catch parameters |
Lambda parameters: (var x, var y) -> x + y | Type names: you can't declare class var |
Rules for the initializer
The type must be clear from the declaration itself, so:
var a; // DOES NOT COMPILE: no initializer
a = 1;
var b = null; // DOES NOT COMPILE: null has no type to infer
var c = (String) null; // OK: the cast gives the type String
var d = 1, e = 2; // DOES NOT COMPILE: var can't be used in a compound declaration
int f, var g = 3; // DOES NOT COMPILE
var h = {1, 2}; // DOES NOT COMPILE: an array initializer needs a type
var i = new int[]{1, 2}; // OK: int[]
var j[] = new int[2]; // DOES NOT COMPILE: var can't have brackets
var k = () -> 1; // DOES NOT COMPILE: a lambda needs a target type
Branches don't help. Even when an if/else assigns the variable on every path, a var declared without an initializer doesn't compile. With an explicit type, the same code would be fine.
Two more inference results are worth knowing:
- After
var s = "text";you may assigns = null;later, becausesis aString, a reference type. Aftervar n = 1;,n = null;fails becausenis anint. var list = new ArrayList<>();infersArrayList<Object>, because there's nothing to fill in the diamond. It compiles, but you lose type safety. Write the type argument, as innew ArrayList<String>().
var is a reserved type name
var is not a keyword. It's a reserved type name: you can't name a class, interface, enum or record var, but you can use it for anything else. So this compiles, painfully:
package var;
public class Var {
public void var() {
var var = "var";
Var other = new Var();
}
}
What's current
- Java 22 finalized unnamed variables (
_, JEP 456). On Java 21_is a compile error as an identifier. var(Java 10, and lambda parameters since Java 11) is unchanged through Java 25.
Exam traps from this article
A complete example
The typeOf overloads show the type that the compiler inferred for each var, because overload resolution happens at compile time.
import java.util.ArrayList;
public class Solution {
// Instance and class variables get default values automatically.
int visitors;
boolean open;
String name;
static double rating;
// Overloads reveal the compile-time type that var inferred.
static String typeOf(int x) { return "int"; }
static String typeOf(long x) { return "long"; }
static String typeOf(double x) { return "double"; }
static String typeOf(char x) { return "char"; }
static String typeOf(String x) { return "String"; }
static String classify(boolean weekend) {
String label; // declared, not yet initialized
if (weekend) {
label = "busy";
} else {
label = "quiet";
}
return label; // OK: every path assigned it
}
public static void main(String[] args) {
Solution zoo = new Solution();
System.out.println("defaults: " + zoo.visitors + " " + zoo.open + " " + zoo.name + " " + rating);
int a, b, c = 3; // three ints, only c initialized
a = b = 1; // assignment is an expression: b = 1, then a = 1
System.out.println("a b c: " + a + " " + b + " " + c);
final int[] scores = {70, 80};
scores[0] = 95; // the array contents can change...
// scores = new int[2]; // ...but the final reference cannot
System.out.println("scores[0]: " + scores[0]);
var count = 7;
var big = count * 2L;
var ratio = count / 2.0;
var initial = 'Z';
var text = "seven";
System.out.println("count " + typeOf(count) + ", big " + typeOf(big)
+ ", ratio " + typeOf(ratio) + ", initial " + typeOf(initial)
+ ", text " + typeOf(text));
var mixed = new ArrayList<>(); // diamond with var: ArrayList<Object>
mixed.add(1);
mixed.add("two");
System.out.println("mixed: " + mixed);
final var small = 5; // a constant int...
byte fits = small; // ...so it can narrow to byte
System.out.println("fits: " + fits);
var var = "var is a legal variable name";
System.out.println(var);
System.out.println(classify(true) + " / " + classify(false));
}
}
Output:
defaults: 0 false null 0.0
a b c: 1 1 3
scores[0]: 95
count int, big long, ratio double, initial char, text String
mixed: [1, two]
fits: 5
var is a legal variable name
busy / quiet
Points to notice:
count * 2Lis alongandcount / 2.0is adouble.vartakes the type of the whole expression, following the promotion rules covered in the operators chapter.final var small = 5;is a constant of typeint, so it may be assigned to abytewithout a cast. Withoutfinal,byte fits = small;would not compile.var var = ...compiles becausevaris only reserved as a type name.
Common questions
Is var slower or less safe than writing the type?
No. The compiler replaces it with the inferred type, so the bytecode is identical. It's purely a source-code shortcut.
Why can't fields use var?
Fields are part of a class's API and can be initialized in several places. The language designers limited inference to locals, where the declaration and initializer are always together.
Why is _ not allowed as a name but __ is?
A single underscore was turned into a keyword in Java 9 to reserve it for unnamed variables, which arrived in Java 22. Two or more underscores are ordinary identifiers.
Can I declare a variable without using it? Yes. An uninitialized local that's never read compiles fine. The compiler complains only when you read it before assigning it.
Do I need to memorize every reserved word?
No. The exam uses common keywords such as class, public, new, for and int when testing identifiers. Also remember that true, false and null are off-limits and that contextual keywords like var and record are legal names.
Does final make an object immutable?
No. final stops the variable from being reassigned. The object it refers to can still change unless its class is designed to be immutable.
Summary
- Identifiers start with a letter,
$, another currency symbol or_, may contain digits afterwards, and can't be_alone, a reserved word ortrue/false/null. - One statement can declare several variables of one type. Each initializer belongs only to its own variable.
- Local variables have no defaults and must be definitely assigned on every path before they're read. Fields default to
0,0.0,false,'\u0000'ornull. finallocals can be assigned once. Afinalreference can still point to a changing object.varworks only for local variables (including loop and resource variables, and lambda parameters) with an initializer that has a type. It can't benull, an array initializer, a lambda or a compound declaration.varis a reserved type name, not a keyword. Java 22+ allows_for unnamed variables.
Practice quiz
Test yourself with the variables, identifiers and var quiz: 10 exam-style questions with explanations.
Previous: Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
Related reading
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
- OCP Java 21 Exam Guide (1Z0-830): Format, Objectives, Strategy and Study Plan
- FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
- Swing Choice Components: Check Boxes, Radio Buttons, Borders, Combo Boxes and Sliders

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.