In Java, final and static are two modifiers that can be applied to variables, each serving a distinct purpose. Let’s explore how these modifiers function and their typical use cases.

Final Variables

A variable declared as final cannot have its value changed once it has been assigned. This immutability is useful for defining constants or ensuring that a value remains unchanged throughout the program.

public class Example {
    final int constantValue = 10;

    public void changeValue() {
        // Compilation error: cannot assign a value to a final variable
        // constantValue = 20;
    }
}

In the example above, constantValue is declared as final, making it immutable after its initial assignment.

Static Variables

A static variable is associated with the class rather than any instance of the class. This means there is only one copy of a static variable, no matter how many objects of the class are created. static variables are ideal for storing class-wide information or data shared among all instances.

public class Example {
    static int staticVariable = 5;

    public static void main(String[] args) {
        // Accessing a static variable
        System.out.println(Example.staticVariable);

        // Modifying a static variable
        Example.staticVariable = 10;
    }
}

In this case, staticVariable belongs to the class Example and can be accessed and modified without needing an object of the class.

Combining final and static

When a variable is both final and static, it becomes a constant associated with the class that cannot be changed. This is often used for defining constants.

public class Example {
    static final int CONSTANT_VALUE = 42;

    public static void main(String[] args) {
        // Accessing a final static variable
        System.out.println(Example.CONSTANT_VALUE);

        // Compilation error: cannot assign a value to a final variable
        // Example.CONSTANT_VALUE = 10;
    }
}

In the above example, CONSTANT_VALUE is a class-wide constant whose value is immutable.

Summary

  • A final variable’s value cannot be changed once assigned.
  • A static variable is shared among all instances of the class.
  • final and static can be combined to create constants that are shared across the class and immutable.

These modifiers can be used independently or together, depending on the needs of your program.

# Written by Elliyas Ahmed