Skip to content
Laviyx Learn

Try

Java course menu

Java Constants: final Variables and static final Constants

Learn to create values that cannot change in Java: final local variables, static final class constants, naming constants in UPPER_SNAKE_CASE, avoiding magic numbers, and what final means for objects.

Beginner7 min readUpdated
On this page

Some values should never change once set: a tax rate, the number of days in a week, the maximum number of login attempts. In Java you mark them with the keyword final, and the compiler stops any code from changing them.

final local variables#

A final variable can be assigned once:

Java
public class Main {
    public static void main(String[] args) {
        final double gstRate = 0.18;
        final int daysPerWeek = 7;

        double price = 1000;
        System.out.println("Tax: " + price * gstRate);
        System.out.println("Hours in a week: " + daysPerWeek * 24);
    }
}
Output
Tax: 180.0
Hours in a week: 168

Changing it later is a compile error:

Java
public class Main {
    public static void main(String[] args) {
        final int maxUsers = 100;
        maxUsers = 200;   // error: cannot assign a value to final variable maxUsers
    }
}

A final local variable may also be assigned after its declaration, as long as it happens exactly once, for example in each branch of an if.

Class constants: static final#

Constants used across a class are declared as static final fields, outside any method. By convention their names use UPPER_SNAKE_CASE:

Java
public class Pricing {
    static final double GST_RATE = 0.18;
    static final int MAX_ITEMS_PER_ORDER = 20;

    static double priceWithTax(double price) {
        return price * (1 + GST_RATE);
    }

    public static void main(String[] args) {
        System.out.println(priceWithTax(500));
        System.out.println("Limit: " + MAX_ITEMS_PER_ORDER + " items");
    }
}
Output
590.0
Limit: 20 items
  • static means there is one copy shared by the whole class, not one per object.
  • final means the value cannot change.
  • Make a constant public static final if other classes should use it, such as Math.PI and Integer.MAX_VALUE in the standard library.

Avoid magic numbers#

A magic number is an unexplained literal in the middle of code. Compare:

Java
// What do 1.18 and 3 mean?
double total = price * 1.18;
if (attempts > 3) { lockAccount(); }
Java
static final double GST_RATE = 0.18;
static final int MAX_LOGIN_ATTEMPTS = 3;

double total = price * (1 + GST_RATE);
if (attempts > MAX_LOGIN_ATTEMPTS) { lockAccount(); }

The second version explains itself, and when a rule changes you update one line.

final does not make objects immutable#

For reference types, final fixes which object the variable refers to, not the object's contents:

Java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        final List<String> cart = new ArrayList<>();
        cart.add("Milk");        // allowed: the list itself can change
        cart.add("Bread");
        System.out.println(cart);
        // cart = new ArrayList<>();   // error: cart cannot point to another list
    }
}
Output
[Milk, Bread]

To make a list that cannot be modified at all, use List.of(...), which creates an unmodifiable list:

Java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        final List<String> days = List.of("Mon", "Tue", "Wed");
        try {
            days.add("Thu");
        } catch (UnsupportedOperationException e) {
            System.out.println("days cannot be changed");
        }
    }
}
Output
days cannot be changed

Strings are already immutable, so a final String is a true constant.

When constants form a fixed set of choices, such as order statuses or days of the week, an enum is better than several int constants. See Records and Enums.

Common mistakes#

Practice#

Practice exercise

A cinema has 12 rows of 18 seats. Store both numbers as static final constants, and print the total number of seats and how many remain after 150 tickets are sold.

Show solution
Java
public class Cinema {
    static final int ROWS = 12;
    static final int SEATS_PER_ROW = 18;

    public static void main(String[] args) {
        int totalSeats = ROWS * SEATS_PER_ROW;
        int sold = 150;
        System.out.println("Total: " + totalSeats);
        System.out.println("Remaining: " + (totalSeats - sold));
    }
}
Output
Total: 216
Remaining: 66

The parentheses around totalSeats - sold are needed; without them, + would join the strings first.

Key takeaway#

Finished this lesson?