Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

final

Example

Declare a variable as final to prohibit its override or modification.

public class Main {
 
final int x = 10;

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

Definition and Usage

The final keyword, as a non-access modifier, applies to classes, attributes, and methods, rendering them immutable and uninheritable or unoverridable.

The final keyword is beneficial when you require a variable to consistently retain a specific value, such as PI (3.14159…).

The final keyword is categorized as a “modifier,” a concept you’ll delve deeper into in the Java Modifiers Chapter.