Skip to content

Local variables, final and var

โ˜• Java 17 ยท Declaring Variables ยท 2/2

You know how to declare and name a variable. Inside a method, a few more rules apply.

Local variables have no default value

A local variable is declared inside a method or a block, and exists only there. Unlike fields, it gets no default value:

public void playEpisode() {
    int currentSecond;
    System.out.println(currentSecond);   // โŒ doesn't compile: not initialized

    currentSecond = 0;
    System.out.println(currentSecond);   // โœ… prints 0
}

Declaring first and assigning later is fine. Reading before assigning is a compiler error.

final: one assignment only

final means the variable can be assigned once:

public void playEpisode() {
    final int MAX_RETRIES = 3;
    MAX_RETRIES = 5;                     // โŒ doesn't compile
}

final locks the variable, not what it points to. A final reference can't point elsewhere, but the object can still change:

final String[] titles = new String[3];
titles[0] = "Dune";                      // โœ… the array's content changes
titles = new String[5];                  // โŒ the reference can't change

Copying a final variable into another one is fine; only the final one stays locked:

final int MAX_STREAMS = 5;
int current = MAX_STREAMS;
current = 3;
System.out.println(current + " / " + MAX_STREAMS);   // 3 / 5

var: let Java infer the type

Since Java 10, var lets the compiler infer a local variable's type from its value:

public void showDetails() {
    var movieTitle = "Inception";   // String
    var rating = 9.2;               // double
    var episodeCount = 10;          // int
}

The type is decided once, at compile time, and never changes: movieTitle = 42; doesn't compile. var saves typing, not type safety.

var has limits:

โŒ Doesn't compile Why
var genre; no value to infer a type from
var x = null; null has no type
var a = 1, b = 2; one variable per var declaration
private var title; not for fields
void play(var x) { } not for parameters or return types

Use var when the type is obvious from the right-hand side, and write the type when it helps the reader.

๐Ÿ’ป Code: Java17_Part_1_Fundamentals_Core_Syntax on GitHub

โ† Declaring and naming ยท Back to the series


๐ŸŽ“ Preparing the OCP Java 17 exam? Exam traps and practice questions for this section โ†’ (optional)