how2examples.com
Home - Introduction to Java Programming

Java's final keyword

The final keyword can be applied to classes, methods and variables. The exact meaning depends on the context but the general rule is that something marked as final cannot be changed.

final variables

Once a variable marked as final has been assigned a value it cannot then be re-assigned to another value.

Example of trying to re-assign a value to a final variable.
Code snippet:
final int i = 1;
i = 2;
Result of trying to compile code snippet:
cannot assign a value to final variable i
i = 2;
^
1 error

You can change data owned by a reference marked as final.

Example of altering the state of a variable even though it is marked as final.
Code snippet:
final StringBuilder sb = new StringBuilder("qwerty");
sb.append("abcdef");
System.out.println(sb);
Output from running code snippet:
qwertyabcdef

A instance variable marked as final must be assigned a value when it is constructed.

Example of not assigning a value to final member variable.
Contents of Example.java:
public class Example {
   final int i;
}
Command to compile Example.java:
javac Example.java
Result of trying to compile Example.java:
Example.java:1: variable i might not have been initialized
public class Example {
       ^
1 error

Member variables marked as final can be assigned were they are declared or in a constructor.

Example of of correctly initilasing final member variables.
Contents of Example.java:
public class Example {
   public static void main(String[] args) {
      A a1 = new A(true);
      A a2 = new A(false);
      System.out.println(a1.i2+" "+a2.i2);
   }
}

class A {
   final int i1 = 1;
   final int i2;
   
   A(boolean b) {
      if (b) {
         i2 = 0;
      } else {
         i2 = 10;
      }
   }
}
Command to compile Example.java:
javac Example.java
Command to run Example:
java Example
Output from running Example:
0 10

final methods

A method can be marked as final to indicate that it can not be overriden by any subclasses.

Example of trying to overide a method marked as final.
Contents of Example.java:
public class Example extends A {
   @Override
   void x() {
   }
}

class A {
   final void x() {
   }
}
Command to compile Example.java:
javac Example.java
Result of trying to compile Example.java:
Example.java:3: x() in Example cannot override x() in A; overridden method is final
   void x() {
        ^
1 error

final classes

A class can be marked as final to indicate that it cannot be subclassed.

Example of trying to extend a class marked as final.
Contents of Example.java:
public class Example extends A {
}

final class A {
}
Command to compile Example.java:
javac Example.java
Result of trying to compile Example.java:
Example.java:1: cannot inherit from final A
public class Example extends A {
                             ^
1 error