Please note, this is a STATIC archive of website www.w3schools.com from 05 May 2020, cach3.com does not collect or store any user information, there is no "phishing" involved.
THE WORLD'S LARGEST WEB DEVELOPER SITE

Java final Keyword

❮ Java Keywords


Example

Set a variable to final, to prevent it from being overridden/modified:

public class MyClass {
  final int x = 10;

  public static void main(String[] args) {
    MyClass myObj = new MyClass();
    myObj.x = 25; // will generate an error: cannot assign a value to a final variable
    System.out.println(myObj.x);
  }
}

Run example »


Definition and Usage

The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override).

The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...).

The final keyword is called a "modifier". You will learn more about these in the Java Modifiers Chapter.


Related Pages

Read more about attributes our Java Class Attributes Tutorial.


❮ Java Keywords