Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 201 ยท Variables and Types

Constants and final

Learn to create constants in Java with final and static final, name them in UPPER_SNAKE_CASE, avoid magic numbers, and understand effectively final variables and lambdas.

Most variables change as a program runs: a counter goes up, a balance goes down. But many values should never change once set: the number of days in a week, a tax rate, the maximum number of login attempts, the name of a file. Java lets you lock such values with the final modifier. Once a final variable has a value, any attempt to assign it again is a compile error.

Constants make code safer, because nobody can overwrite them by accident, and clearer, because MAX_LOGIN_ATTEMPTS explains itself while a bare 5 doesn't. In this lesson you'll learn final local variables, final fields, class-wide static final constants, the naming conventions, and the closely related idea of effectively final variables that lambdas depend on.

final local variables

Put final in front of a declaration to make the variable assignable only once:

Java
final int daysInWeek = 7;
final String greeting = "Welcome";
final var limit = 100;          // works with var too

Trying to change one is caught by the compiler, before the program runs:

Java Reassigning a final variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The error is cannot assign a value to final variable vatRate. Nothing runs, not even the first println, because the whole file must compile first.

Assigning a final variable later

A final variable doesn't have to be initialized on the same line. You can declare it first and assign it exactly once later, which is called a blank final. The compiler checks every path through your code to make sure the variable is assigned exactly once before it's used:

Java
final String category;
if (age < 13) {
    category = "child";
} else if (age < 20) {
    category = "teen";
} else {
    category = "adult";
}
IO.println(category);   // OK: assigned exactly once on every path

If one branch forgets to assign it, you get variable category might not have been initialized. If a path assigns it twice, you get variable category might already have been assigned. This is a nice way to compute a value with if/else and still promise it won't change afterwards. (A switch expression is often even cleaner for this.)

Java A blank final assigned in branches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Change the Input box to 9 or 40 and run again. (? : is the ternary operator, covered in Operator Precedence and the Ternary Operator.)

Constants that belong to a class: static final

A final local variable exists only while its method runs. Most real constants should be shared by the whole class, and often by the whole program. For that, Java combines two modifiers:

  • static means the variable belongs to the class itself, not to each object, so there's one copy (see Static Fields, Methods and Blocks).
  • final means it can't be reassigned.

A static final field is Java's version of a constant. You've already used some from the standard library:

Java
Math.PI                 // 3.141592653589793
Integer.MAX_VALUE       // 2147483647
Long.MIN_VALUE

Here's how you declare your own. This example uses a full class so the static keyword has its traditional home:

Java Class constants with static final

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Choose the access modifier as for any field (see Access Modifiers): public when other classes need it, private when it's an internal detail. A static final field must be assigned exactly once, either on its declaration line or in a static initializer block.

Naming constants

Java has one firm convention: constants are written in UPPER_SNAKE_CASE, all capital letters with underscores between words.

Java
static final int MAX_RETRIES = 5;             // constant: UPPER_SNAKE_CASE
static final String DEFAULT_LANGUAGE = "en";
static final double EARTH_RADIUS_KM = 6_371.0;

final int retries = readRetries();            // final local: normal camelCase

Two details trip people up:

  • The uppercase style is for true constants: static final fields whose value is fixed and, ideally, immutable (numbers, strings, immutable lists). A final local variable or a per-object final field uses normal camelCase.
  • Put the unit in the name when there is one: TIMEOUT_SECONDS, MAX_UPLOAD_BYTES, EARTH_RADIUS_KM. It prevents a whole class of bugs where milliseconds and seconds get mixed up.

Replace magic numbers with constants

A magic number is an unexplained literal in the middle of your logic. It forces readers to guess what it means, and when the value changes you must hunt down every copy:

Java
// Before: what are 0.15 and 3? Are both 3s the same 3?
if (attempts > 3) { lock(); }
double discount = total > 100 ? total * 0.15 : 0;
int pages = (items + 3 - 1) / 3;

// After: the code explains itself, and each value lives in one place
static final int MAX_ATTEMPTS = 3;
static final double BULK_DISCOUNT_RATE = 0.15;
static final double BULK_DISCOUNT_THRESHOLD = 100.0;
static final int ITEMS_PER_PAGE = 3;

Not every literal needs a name. 0, 1, 2 in obvious roles (i = 0, n * 2, count + 1), or 100 in "convert to a percentage", are fine as they are. Name a value when it carries meaning that could change or that a reader wouldn't guess.

When several constants form a fixed set of choices (sizes, states, days of the week), use an enum instead of a group of int constants. Size.LARGE can't be confused with a random 3. See Enums.

final does not mean immutable

final freezes the variable, not the object it refers to. With a primitive, those are the same thing. With a reference type, final only stops you from pointing the variable at a different object. The object itself can still change:

Java A final reference to a changeable object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

So a "constant" like static final List<String> COLORS = new ArrayList<>(); is a trap: any code can call COLORS.add(...). For a truly constant collection use an unmodifiable one such as List.of(...), which throws UnsupportedOperationException on any change. Making whole classes unchangeable is the topic of Immutable Classes.

final fields in objects

A non-static final field gives each object its own value, which is fixed once the object is built. It must be assigned exactly once, either where it's declared or in every constructor:

Java
class Account {
    private final String id;        // set once per account, never changes
    private double balance;         // changes over time

    Account(String id) {
        this.id = id;
    }
}

Forgetting to assign it is a compile error: variable id might not have been initialized. Final fields document which parts of an object are permanent and make objects safer to share between threads. They're covered with Constructors and Encapsulation.

Constant variables and compile-time constants

A final variable of a primitive type or String, initialized with a constant expression, is a constant variable. The compiler knows its value while compiling, which unlocks a few things ordinary variables can't do:

Java What compile-time constants allow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without final, the line byte b = small; would fail with "possible lossy conversion", and the case labels would be rejected with constant expression required. The last line prints true because the compiler joins the constant strings at compile time and both sides refer to the same pooled String object. (Compare strings with equals in real code; Strings explains why.)

There's one practical consequence for larger projects. The compiler copies the values of public static final constant variables into every class that uses them. If you change such a constant in a library, classes compiled against the old version keep the old value until they're recompiled. Build tools usually recompile everything, but it's worth knowing when a "changed" constant seems to have no effect.

Effectively final

A local variable that is never reassigned after initialization is called effectively final, even without the final keyword. The compiler tracks this, and it matters in one important place: lambdas and inner classes can only use local variables that are final or effectively final.

Java
String prefix = "> ";                  // never reassigned: effectively final
List.of("a", "b").forEach(s -> IO.println(prefix + s));   // OK

int count = 0;
List.of("a", "b").forEach(s -> count++);   // error

The second lambda fails with local variables referenced from a lambda expression must be final or effectively final. Java copies a local variable's value into the lambda when the lambda is created, so allowing changes afterwards would create two versions of the variable that disagree. Reassigning a variable anywhere, even after the lambda, breaks effectively-final status:

Java Effectively final and lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The one-element array trick works because the variable total itself never changes; only the array's contents do. It's common in quick scripts, but a stream (see Streams) or a plain for loop is usually clearer. Lambdas are explained in Lambda Expressions.

Should you write final on every local variable that doesn't change? Opinions differ. Some teams do it for safety; others find it noisy because the compiler already tracks effectively final variables. Either way, mark fields final whenever you can: that's where it adds the most value. The final Keyword Everywhere lesson covers final methods, classes and parameters too.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which declaration follows Java's naming convention for a class-wide constant?

    Constants that are static and final use UPPER_SNAKE_CASE. Final local variables and per-object final fields use normal camelCase.
  2. 2. What happens with final int[] data = {1, 2}; data[0] = 9;?

    final only stops data from referring to a different array. The array object itself can still be changed.
  3. 3. Which code compiles?

    A blank final may be assigned later as long as it's assigned exactly once on every path, which the if/else does. The other options assign a final twice or capture a variable that isn't effectively final.
  4. 4. Why does int n = 0; list.forEach(s -> n++); fail to compile?

    A lambda captures a copy of the local variable's value, so the variable may not change. n++ modifies it, so the compiler rejects the lambda.
  5. 5. Without final, why would int small = 100; byte b = small; fail?

    Implicit narrowing is allowed only for constant expressions whose value fits. A non-final variable could hold anything, so a cast is required. Marking it final makes it a constant variable.

Summary

  • final makes a variable assignable only once; reassigning it is a compile error. A blank final can be assigned later, exactly once on every path.
  • static final fields are class-wide constants, like Math.PI. Name them in UPPER_SNAKE_CASE, with units where relevant.
  • Replace magic numbers with named constants, and prefer enums for fixed sets of choices.
  • final freezes the variable, not the object: a final list or array can still change. Use List.of and immutable types for true constants.
  • final fields must be assigned in every constructor and mark the permanent parts of an object.
  • final primitives and strings with constant initializers are compile-time constants: they work as case labels and allow implicit narrowing.
  • Lambdas can use only final or effectively final local variables, ones that are never reassigned.

Next: The Math Class, where you'll use Java's built-in methods for powers, roots, rounding, clamping and random numbers.