World's most popular travel blog for travel bloggers.

Explain use(s) of following keywords of Java with the help of program/example: final

, , No Comments

 Java final keyword

In Java, the final keyword is used to denote constants. It can be used with variables, methods, and classes.

Once any entity (variable, method or class) is declared final, it can be assigned only once. That is,

  • the final variable cannot be reinitialized with another value
  • the final method cannot be overridden
  • the final class cannot be extended

1. Java final Variable

In Java, we cannot change the value of a final variable. For example,

class Main {
  public static void main(String[] args) {

    // create a final variable
    final int AGE = 32;

    // try to change the final variable
    AGE = 45;
    System.out.println("Age: " + AGE);
  }
}

In the above program, we have created a final variable named age. And we have tried to change the value of the final variable.

When we run the program, we will get a compilation error with the following message.

cannot assign a value to final variable AGE
    AGE = 45;
    ^

0 comments:

Post a Comment

Let us know your responses and feedback