Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Variable Declaration: Syntax, Scope, and var

Learn how Java variable declaration works: syntax, initialization, scope, final variables, and local variable type inference with var.

~5 min readJava
#Java#variable declaration#type inference#final keyword
Illustration of Java variable declaration showing a code snippet with type and variable name

In Java, a variable declaration introduces a name and binds it to a type. The way you write it determines where the variable lives, what it can hold, and how the compiler treats it. This article covers the syntax and semantics of Java variable declaration, from primitives and references to final and var.

Basic Syntax and Initialization

The simplest declaration combines a type and a name:

java
int count; String label;

A declaration without an initializer leaves an instance or static field in its default state: zero, false, or null depending on the type. Local variables are not automatically initialized; the compiler requires explicit initialization before use.

java
class Example { int count; // defaults to 0 boolean flag; // defaults to false String name; // defaults to null }

Inside a method, the following does not compile:

java
void method() { int value; System.out.println(value); // error: variable value might not have been initialized }

This rule prevents a class of bugs where a local variable is read before a value is assigned. It also makes the flow of data explicit.

Scope and Lifetime

A variable's scope is the block of code where it can be referenced. In Java, scope is determined by the enclosing braces. A variable declared inside a method is visible from its declaration to the end of that block. A variable declared in a traditional for-loop header is scoped to the loop statement: it can be used in the condition and update expressions as well as the body, and it is out of scope after the loop.

java
void process() { for (int i = 0; i < 3; i++) { int doubled = i * 2; // i and doubled are both in scope here } // i and doubled are out of scope here }

Shadowing occurs when an inner block declares a variable with the same name as an outer one. The inner declaration hides the outer one. While legal, shadowing often makes code harder to follow. If you find yourself naming a local variable the same as a field, consider renaming one of them.

Local Variable Type Inference with var

Java 10 introduced local variable type inference with var. It lets you omit the explicit type when the compiler can infer it from the initializer. The type is still static and decided at compile time.

java
var count = 0; // int var names = new ArrayList<String>(); // ArrayList<String> var map = Map.of("a", 1); // Map<String, Integer>

var is not a keyword that makes Java dynamically typed. It is a reserved type name that the compiler replaces with the inferred type. The inferred type is fixed for the lifetime of the variable.

Use var when the type is obvious from the initializer, such as var list = new ArrayList<String>();. Avoid it when the type is not clear from the right-hand side, for example var result = someMethod(); where the method's return type is not immediately obvious. In that case, an explicit type improves readability.

final Variables and Constants

Declaring a variable as final prevents reassignment. For primitives, the value cannot change. For references, the reference cannot point to a different object, but the object itself can be mutated.

java
final int MAX_SIZE = 1024; final List<String> tags = new ArrayList<>(); tags.add("java"); // allowed tags = new ArrayList<>(); // error: cannot assign a value to final variable

A local variable that is not declared final but is never reassigned after initialization is called effectively final. This property matters for lambda expressions and anonymous classes, because those constructs can only capture variables that are final or effectively final.

Compile-time constants are final variables of primitive or String type that are initialized with a constant expression. They can be inlined by the compiler, so changing them can require recompiling dependent classes. In a public API, be cautious about exposing compile-time constants; a static final field initialized with a non-constant expression is not a compile-time constant and avoids that kind of inlining.

Common Mistakes and Compile-Time Errors

A frequent error is attempting to assign a value of a wider type to a narrower one without a cast. Java requires explicit casting for narrowing conversions.

java
long big = 100L; int small = big; // error: incompatible types int correct = (int) big; // explicit cast

Another mistake is confusing declaration with assignment. A declaration like int a, b; declares two variables. You cannot use int a = b = 1; unless b is already declared. The correct way is int a = 1, b = 1;.

Local variables that are declared but never read are not a compile error, but they often indicate dead code. Some static analysis tools flag them. Remove unused declarations to keep the codebase clean.

Performance and Memory Considerations

Variable declaration itself has negligible runtime cost. The compiler maps local variables to slots in the JVM stack frame, and no heap allocation occurs for primitives or references. The cost appears when you initialize a reference type with new. That allocates an object on the heap, which later becomes garbage if unreachable.

Choosing between var and an explicit type does not affect performance. The bytecode is identical because the type is resolved at compile time. Similarly, marking a variable final has no runtime overhead; it is purely a compile-time constraint that helps the compiler and future maintainers reason about the code.

One practical performance consideration is object allocation. If you declare a variable inside a loop and assign a new object each iteration, you create many objects. Moving the declaration outside the loop and reusing one mutable object can reduce allocation pressure, but only if the object can be reset for each iteration. For immutable types, each iteration still needs a new instance.

Choosing Between Explicit Types and var

The decision between an explicit type and var is a readability tradeoff. Use explicit types when the type is important for understanding the code, such as when the initializer is a method call with a non-obvious return type. Use var when the type is evident from the right-hand side, like var reader = new BufferedReader(...);.

Consider how these two forms differ. With var, the reader may need to inspect the right-hand side:

java
var items = service.getItems(); // what is the type?

With an explicit type, the contract is visible immediately:

java
List<Item> items = service.getItems(); // clear

The explicit version communicates the contract. Use explicit types in method signatures and public APIs; var is only available for local variables and does not express a contract. Inside a short method body, var can reduce clutter without hurting clarity.

Similarly, prefer final for variables that must not be reassigned. It signals intent and prevents accidental changes. Many style guides recommend marking local variables as final when they are effectively final, though this can add noise. Find a balance that your team agrees on.

Where Declaration Style Affects Maintainability

Variable declaration style has a direct effect on how easily a codebase can be read and modified. A well-named variable with a clear type and an appropriate initializer reduces the cognitive load. On the other hand, overusing var with obscure method calls forces readers to inspect the return type, slowing down code review and maintenance.

When you declare a variable, also consider its lifecycle. A variable that is only used inside a small block should be declared there. A variable that must persist across iterations should be declared outside the loop. These choices affect not only readability but also the ability to refactor the code later.

In Java, the declaration is also the first opportunity to document the variable's purpose. A good name and a clear type often remove the need for a comment. If you find yourself writing a comment to explain what the variable holds, consider whether the name or type could be improved instead.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.