🌱BeginnerVariables & Data Types

Constants (final keyword)

Use the final keyword to declare constants - values that can be set once and never changed.

Overview

A constant is a variable whose value cannot be changed after it is assigned. In Java, you create a constant by adding the final keyword before the type. Attempting to reassign a final variable results in a compile error. Constants make code safer (no accidental changes), more readable (a name is clearer than a magic number), and easier to maintain (change the value in one place and it updates everywhere). By convention, Java constant names use UPPER_SNAKE_CASE: MAX_SIZE, PI, DEFAULT_TIMEOUT.

Key Points

  • •final variables can only be assigned once - any re-assignment causes a compile error
  • •Convention: name constants in UPPER_SNAKE_CASE (e.g., MAX_RETRIES, TAX_RATE)
  • •final can be applied to variables, method parameters, methods, and classes
  • •static final - a class-level constant shared by all instances (the most common pattern)
  • •Constants eliminate "magic numbers" - unnamed numeric literals scattered through code
  • •final does not make object contents immutable - only the reference cannot be reassigned

Examples

Declaring and using constants

public class Main {
    // Class-level constant - shared by all instances
    static final double PI = 3.14159265358979;
    static final int MAX_SPEED = 200;
    static final String APP_NAME = "MyApp";

    public static void main(String[] args) {
        double radius = 5.0;
        double area = PI * radius * radius;
        System.out.println("Area: " + area);
        System.out.println("Max speed: " + MAX_SPEED + " km/h");
        System.out.println("App: " + APP_NAME);
    }
}

static final combines "one copy per class" (static) with "never changes" (final).

Constants prevent accidental changes

public class Config {
    static final int TIMEOUT_SECONDS = 30;
    static final String BASE_URL = "https://api.example.com";

    public static void main(String[] args) {
        System.out.println("Timeout: " + TIMEOUT_SECONDS + "s");
        System.out.println("URL: " + BASE_URL);

        // TIMEOUT_SECONDS = 60; // COMPILE ERROR: cannot assign to final variable
    }
}

The compiler prevents you from accidentally overwriting a constant.

Constants vs magic numbers

// BAD: magic numbers - what does 0.18 mean?
double tax = price * 0.18;
double fine = speed > 120 ? speed * 0.18 : 0;

// GOOD: named constants
static final double TAX_RATE = 0.18;
static final int SPEED_LIMIT = 120;

double tax = price * TAX_RATE;
double fine = speed > SPEED_LIMIT ? speed * TAX_RATE : 0;

Constants give meaning to numbers. If TAX_RATE changes, you update it in one place.

Common Mistakes

  • Using lowercase names for constants: `final double pi = 3.14` - convention is `PI`
  • Thinking final on a List or array prevents its contents from changing - it only prevents reassigning the reference
  • Declaring a final variable without initialising it at declaration and then forgetting to assign it before use

Note

Group related constants in their own class or interface (e.g., `AppConstants`, `HttpStatus`). This creates a single, easy-to-find place for all constant values.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

What keyword makes a Java variable a constant?