CodeBlanks Logo Icon CodeBlanks

final variables

Learn constant-value variables with final.

What is final?

The final keyword marks a variable as not reassignable. Once you give it a value, it cannot change. Such variables are called constants.

final double PI = 3.14;
PI = 3.15; // compile error

Constants are usually named in ALL_CAPS: MAX_SPEED, PI, URL. This signals to other developers that the value does not change.

Constants are ideal for values that stay the same across the program: math constants, configuration values, limits.

Practice Define a final constant and print it

Write a Main class with a main method. Assign 120 to final int MAX_SPEED. Print it with println.

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        final int MAX_SPEED = 120;
        System.out.println(MAX_SPEED);
    }
}

Expected output

120

When to use final?

When a value will not change throughout the program, using final is good practice. It prevents accidental changes and states the intent clearly.

Common examples:

  • Math constants: PI, EULER
  • Configuration: URL, PORT
  • Limits: MAX_USERS, TIMEOUT

Local variables can also be final; variables used in lambda expressions must be effectively final.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the final concepts

Term Meaning
final Constant
PI Constant example
MAX_SPEED ALL_CAPS
const Not Java

2 Complete the final constant

Question
final double PI = ____;
Answer
final double PI = 3.14;

Explanation: PI = 3.14 declares the math constant.

3 What can NOT be done to a final variable?

  • Reassign Correct answer
  • Print
  • Declare
  • Use

Explanation: A final variable cannot be reassigned.

All lessons in Beginner