Menu
Coddy logo textTech

Constants

Part of the Fundamentals section of Coddy's Java journey — lesson 10 of 73.

A constant is a special type of variable that cannot be changed once it is initialized.

To declare a constant use the keyword final followed by the variable type:

final int MAX_VALUE = 100;

In the above example, a constant named MAX_VALUE is initialized with the value 100.

If we try to change a constant value:

final int MAX_VALUE = 100;
MAX_VALUE = 200; // This will cause an error

It will result in an error because constant values cannot be changed.

challenge icon

Challenge

Beginner

Create a constant named PI and initialize it with the value 3.14159.

Cheat sheet

A constant is a variable that cannot be changed once initialized. Use the final keyword to declare constants:

final int MAX_VALUE = 100;

Constants cannot be reassigned after initialization - attempting to do so will cause an error.

Try it yourself

public class Main {
    public static void main(String[] args) {
        // Type your code below


        // Don't change the line below
        System.out.println("PI = " + PI);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals