Java final variable

In Java, a final variable is a variable whose value cannot be changed once it has been initialized. Once a final variable is assigned a value, it cannot be reassigned to a new value. A final variable can be declared with the final keyword.

Here's an example of using a final variable in Java:

refer to:‮itfigi‬dea.com
class MyClass {
    private final int x;
    
    public MyClass(int x) {
        this.x = x;
    }
    
    public void printX() {
        System.out.println(x);
    }
}

In the example above, x is declared as a final variable. The x variable is assigned a value in the constructor and cannot be reassigned to a new value. The printX method can read the value of x but cannot change its value.

There are a few benefits of using final variables:

  • final variables can improve code readability by making it clear that the variable will not change after initialization.
  • final variables can improve code safety by preventing accidental changes to the value of a variable.
  • final variables can improve code performance by allowing the compiler to make certain optimizations.

It's important to note that a final variable must be initialized when it is declared or in the constructor. If the final variable is not initialized when it is declared or in the constructor, it will generate a compile-time error. Additionally, a final variable can only be assigned once. If you attempt to assign a value to a final variable more than once, it will generate a compile-time error.