Swipe
SwipeSwipe
Swipe Apps

Paths

Motivation

Information

Constants & Type Casting · Lesson 27 of 28

Constants (final)

A free lesson from Swipe Coding · Java, level 2 · updated October 2026

By the Swipe team, founded by Colin · how we make lessons

🤖
Some values should just never change — final makes that a promise. 🔒

Sometimes a value should never change once it's set — think of the number of days in a week, or the maximum number of players allowed in a game. Java lets you mark a variable as a constant using the final keyword, which tells the compiler this variable's value must never change after it is assigned.

final double PI = 3.14159;
System.out.println(PI);
Declaring a constant with final — PI can be read, but never reassigned.
🤖
ALL_CAPS names make constants impossible to miss in your code. 🔠

By convention, constant names are written in UPPER_SNAKE_CASE: every letter capitalized, with underscores separating words, such as MAX_PLAYERS or DAYS_IN_WEEK. This makes constants instantly recognizable in your code, setting them apart at a glance from regular camelCase variables.

final int MAX_PLAYERS = 4;
System.out.println(MAX_PLAYERS);
MAX_PLAYERS follows the UPPER_SNAKE_CASE convention for constants.
🤖
This is exactly the kind of bug a good constant name prevents. 🎯

If you try to reassign a final variable after it has been given a value, the code will not compile — Java catches the mistake before the program ever runs. This is exactly why constants are so useful: they replace unexplained 'magic numbers' scattered through your code with a single, clearly named, protected value. If that value ever needs to change, you update it in exactly one place, and a name like MAX_PLAYERS makes the code's intent obvious to anyone reading it.

final int MAX_LIVES = 3;
MAX_LIVES = 5; // Compile-time error: cannot assign a value to final variable MAX_LIVES
The compiler stops you from ever changing a final variable's value.
Fill in the blank

The ____ keyword tells Java that a variable's value can never be changed after it is first assigned.

Quick check

What happens if you try to reassign a variable declared with final?

True or false

By convention, constant names in Java are written in UPPER_SNAKE_CASE, like MAX_SPEED.

Keep your streak going in Swipe Coding

Swipe through every level of Java on your iPhone — with XP, stars, streaks, a personal advisor and the full track beyond these free levels.

Get the Swipe apps →