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
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);
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);
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 ____ keyword tells Java that a variable's value can never be changed after it is first assigned.
What happens if you try to reassign a variable declared with final?
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 →