Course contentsShow
← Java
Lesson 70 of 2,8702. Variables and Primitive TypesFree lesson

The final Keyword for Variables

Using final to create constants and prevent reassignment after initialization.

The final Keyword for Variables

What you'll learn: How to use final to lock a variable's value after initialization, creating constants that cannot be reassigned.

What Does final Mean?

When you declare a variable with the final keyword, you're telling Java: "This value can only be set once." After initialization, any attempt to reassign that variable will cause a compilation error.

Think of final like a safety seal on a product—once applied, it cannot be removed or changed. This prevents accidental modifications to values that should remain constant throughout your program.

Basic Syntax

final int MAX_PLAYERS = 4;
final double PI = 3.14159;
final char GRADE = 'A';

Once initialized, these variables become constants—their values are locked:

final int MAX_USERS = 100;
MAX_USERS = 200;  // Compilation error! Cannot reassign

Declaration Without Immediate Initialization

You can declare a final variable without initializing it immediately, but you must initialize it before use, and you get only one chance:

final int count;
count = 10;      // OK - first assignment
count = 20;      // Compilation error! Already assigned

Why Use final?

Constants make your code safer and more readable. When you see final, you know that value won't change, making debugging easier and preventing accidental modifications. By convention, constant names are often written in UPPERCASE_WITH_UNDERSCORES.

Key Takeaway: The final keyword creates constants by preventing reassignment after initialization—use it to protect values that should never change during program execution.