Java Variables, Constants, var and final Explained
How to declare and initialize variables in Java, the naming rules, why the compiler rejects uninitialized variables, local type inference with var, constants with final and static final, and a first look at enumerated types.
kvi5hnuCode Sprout team member11 min readOn this page
A variable is a named place in memory that holds a value. In Java every variable has a type, fixed when you declare it, and the compiler makes sure only values of that type go in. A constant is a variable whose value, once set, never changes.

Declaring Variables
You declare a variable by writing its type, then its name, then a semicolon:
double salary;
int vacationDays;
long earthPopulation;
boolean done;
The semicolon is required because a declaration is a complete statement, and every Java statement ends with ;.
Naming rules, in full
A variable name is an identifier, following the same rules as class names:
- It consists of letters, digits, currency symbols and "connector" punctuation, and must not start with a digit.
- Java's idea of "letter" and "digit" is broad: any Unicode letter counts (
ä,π,ж,中), as does any Unicode digit. Currency symbols include$,€and¥. Connectors include the underscore_and a few exotic characters. - Symbols such as
+,-,©or@and spaces are not allowed. - Case matters:
startdateandstartDateare two different variables. - Length is essentially unlimited.
- Keywords (
class,int,new,if…) are not allowed. A lone underscore_is also reserved: since Java 22 it means "a variable I must declare but will never use" (see below).
In practice, programmers stick to A–Z, a–z, 0–9 and _. Avoid $, which is meant for names generated by the compiler and tools.
You may declare several variables of the same type in one statement:
int i, j; // both are int
It's legal, but declaring each variable on its own line is easier to read and comment, and it's what most style guides recommend.
Initializing Variables
Declaring a variable doesn't give it a usable value. You must assign a value before you read the variable, and the compiler enforces this:
int vacationDays;
System.out.println(vacationDays); // ERROR
error: variable vacationDays might not have been initialized
This check, called definite assignment, is the compiler proving that on every possible path through your code, the variable has received a value before it's read. It eliminates a whole class of bugs that are common in C and C++, where an uninitialized local variable simply contains whatever garbage was in memory.
You assign with =: the variable on the left, an expression on the right:
int vacationDays;
vacationDays = 12;
Usually you declare and initialize in one step:
int vacationDays = 12;
Declarations can appear anywhere in a method, not only at the top. Good style is to declare each variable as close as possible to where it's first used, ideally with its initial value:
public class Solution {
public static void main(String[] args) {
int vacationDays; // declaration: type + name
vacationDays = 12; // assignment
double salary = 65000.0; // declaration with initialization
var bonusPercent = 7.5; // type inferred: double
var employeeName = "Grace"; // type inferred: String
System.out.println(employeeName + " has " + vacationDays + " vacation days");
System.out.println("Bonus: " + salary * bonusPercent / 100);
vacationDays = vacationDays + 3; // a variable can change
System.out.println("Now: " + vacationDays);
}
}
Grace has 12 vacation days
Bonus: 4875.0
Now: 15
Note vacationDays = vacationDays + 3. This isn't an equation (which would be impossible); = means "compute the right side, then store it in the variable on the left". It reads the current value 12, adds 3, and stores 15.
Local Type Inference with var
Since Java 10, you can write var instead of the type when declaring a local variable with an initial value. The compiler infers the type from that value:
var vacationDays = 12; // int
var salary = 65000.0; // double
var greeting = "Hello"; // String
var population = 8_100_000_000L; // long
Important facts about var:
| Fact | Explanation |
|---|---|
| The type is still static | var doesn't make Java dynamic like JavaScript. var greeting = "Hello" declares a String variable for good; assigning 42 to it later is a compile error. |
| It needs an initializer | var x; fails with "cannot infer type for local variable x". |
Not with null alone | var y = null; fails: null doesn't tell the compiler which type you mean. |
| Only for local variables | Also allowed in for loops, the enhanced for loop, try-with-resources and lambda parameters. Not allowed for fields, method parameters or return types. |
var isn't a keyword | It's a reserved type name, so old code that used var as a variable name still compiles. You just can't name a class var. |
When is var a good idea? For numbers and strings it saves little. It really pays off with long object types, as you'll see in the next part:
HashMap<String, List<Employee>> byDepartment = new HashMap<String, List<Employee>>(); // repetitive
var byDepartment = new HashMap<String, List<Employee>>(); // clear and short
Constants: final
The keyword final marks a variable that can be assigned only once. After that its value is fixed for good:
final double CM_PER_INCH = 2.54;
CM_PER_INCH = 3; // ERROR: cannot assign a value to final variable CM_PER_INCH
By convention, constants are named in all uppercase, with underscores between words: CM_PER_INCH, MAX_USERS.
Class constants: static final
A final variable inside a method is visible only in that method. More often you want a constant that's available to all methods of a class, or even to other classes. Such a class constant is declared outside any method, with static final:
public class Solution {
public static final double CM_PER_INCH = 2.54; // class constant
public static void main(String[] args) {
final double paperWidth = 8.5; // local constant (inches)
final double paperHeight = 11;
System.out.println("Letter paper in cm: "
+ paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH);
System.out.println("A4 width in inches: " + 21.0 / CM_PER_INCH);
}
}
Letter paper in cm: 21.59 by 27.94
A4 width in inches: 8.26771653543307
staticmeans the constant belongs to the class itself rather than to individual objects (explained fully in the static fields article).finalmeans it can't change.publicmeans other classes can use it too, asSolution.CM_PER_INCH. The JDK is full of such constants:Math.PI,Integer.MAX_VALUE,Double.NaN.
Why use constants? CM_PER_INCH documents what 2.54 means, prevents typos (writing 2.45 in one place), and lets you change a value in one place instead of hunting for every occurrence. Numbers that appear unexplained in code are called magic numbers, and replacing them with named constants is one of the easiest ways to improve code.
Enumerated Types: A First Look
Sometimes a variable should only ever hold one of a small, fixed set of values: a coffee roast, a day of the week, a traffic-light colour. You could encode roasts as 1, 2, 3, 4 or 'L', 'M', 'D', 'F', but nothing stops a variable from holding a wrong value like 0 or 'x'.
An enumerated type (enum) defines the allowed values by name:
public class Solution {
enum Roast { LIGHT, MEDIUM, DARK, FRENCH }
public static void main(String[] args) {
Roast order = Roast.MEDIUM;
System.out.println("Ordered: " + order);
System.out.println("Position: " + order.ordinal());
Roast fromText = Roast.valueOf("DARK");
System.out.println(fromText == Roast.DARK);
for (Roast r : Roast.values()) {
System.out.print(r + " ");
}
System.out.println();
}
}
Ordered: MEDIUM
Position: 1
true
LIGHT MEDIUM DARK FRENCH
A variable of type Roast can hold only Roast.LIGHT, Roast.MEDIUM, Roast.DARK, Roast.FRENCH, or the special value null, meaning "no value at all". (null is explained in the objects and classes part.) The compiler rejects anything else. Enums print their names, can be compared with ==, and, as you'll see in the enum classes article, can have fields, methods and constructors of their own.
Unused Variables: _ (Java 22+)
Sometimes Java's syntax forces you to declare a variable that you never use, for example the exception variable in a catch you don't inspect, or a loop variable when you only care about the number of iterations. Since Java 22 you can name such a variable with a single underscore to make the intent explicit:
for (var _ : orders) { // we only count, never use the element
count++;
}
This is mainly useful with lambdas, exceptions and pattern matching, and you'll see examples in those articles.
Common questions
Can I use var for fields, parameters or return types?
No. var works only for local variables that have an initializer, enhanced for loop variables, classic for loop indexes, try-with-resources variables and lambda parameters (Java 11). Fields, method parameters and return types must name their type, because they are part of a class's public contract.
Does var make Java dynamically typed?
No. The compiler infers a fixed type once, at compile time. After var count = 10;, count is an int for good, and count = "ten"; is a compile error. The class file contains exactly the same code as if you had written int.
What type does var x = 'a' + 1; get?
int, because char + int is an int. Likewise var d = 10; gives an int and var big = 10L; gives a long. With var, the literal you write decides the type, so add suffixes (L, F, .0) when you need a different type.
Does final make an object unchangeable?
No. final only stops the variable from being reassigned. After final var list = new ArrayList<String>();, you can still call list.add("x"). To make the contents unchangeable, use an immutable object, for example List.of(...) or a record with immutable components.
Is var a keyword?
It is a reserved type name, not a full keyword. You can still have a variable or method called var, so old code keeps compiling, but you can't name a class or interface var.
Summary
- Declare a variable with type name;. Every variable has a fixed type.
- Names: letters, digits,
_,$(avoid), no leading digit, no keywords, case-sensitive. Use lowerCamelCase and meaningful names. - Local variables must be assigned before use; the compiler checks this (definite assignment).
- Declare variables close to where they're first used, preferably with an initial value.
varinfers the type of a local variable from its initializer. The type is still fixed at compile time.finalmakes a variable assignable only once. Class constants arestatic finaland named in UPPER_SNAKE_CASE.constis reserved but unused.- Enums restrict a variable to a fixed set of named values, plus
null. - Java 22+ lets you name intentionally unused variables
_.
Practice Questions
Which of these are valid variable names: totalCost, 2ndTry, total-cost, _count, café, class, $value?
Valid: totalCost, _count, café, $value (legal, but $ should be avoided). Invalid: 2ndTry (starts with a digit), total-cost (hyphen), class (keyword).
What's wrong with this code? int total; if (args.length > 0) { total = 10; } System.out.println(total);
If args.length is 0, total is never assigned, so it's not definitely assigned at the println. The compiler reports "variable total might not have been initialized". Fix it by initializing total when declaring it, or by adding an else branch that assigns it.
After var count = 10;, can you write count = 2.5;? Why or why not?
No. var count = 10; declares count as an int, permanently. Assigning 2.5 (a double) to an int variable is a compile error ("possible lossy conversion from double to int"). var infers the type once; it doesn't make the variable dynamically typed.
Why does var x = null; not compile?
null has no specific type, as it can be assigned to any reference type, so the compiler can't infer which type x should have.
You need the tax rate 0.18 in five methods of a class. How should you declare it?
As a class constant: private static final double TAX_RATE = 0.18; (or public if other classes need it). Declare it outside all methods, then use TAX_RATE everywhere instead of repeating the magic number 0.18.
Why is an enum Roast { LIGHT, MEDIUM, DARK } safer than storing roasts as int codes 1, 2, 3?
With int codes, any integer (0, 7, −1) can be stored by mistake, and the compiler can't help. A Roast variable can only hold one of the declared constants (or null). Invalid values are compile errors, and the code is self-documenting: Roast.DARK is clearer than 3.
Previous: Java char, Unicode and boolean: Characters, Escape Sequences and Truth Values
Next: Java Arithmetic Operators and the Math Class: Division, Remainder, floorMod and More
Related reading
- Java Keywords Reference: Every Keyword, Contextual Keyword and Literal
- Java Module Services, requires transitive and static, and Module Tools
- Java Automatic Modules, the Unnamed Module and Migration Flags
- Modular JARs and Reflective Access in Java: opens and open modules
- Java Module requires and exports: Dependencies and Exported Packages

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.