Home » Use of final Keyword in Java

Use of final Keyword in Java

by Online Tutorials Library

Use of final Keyword in Java

In Java, final is a keyword that guarantees only the immutability of primitive types. And also guarantees that a variable is assigned only once. If an object is mutable, we can change the content of it even it is defined as final. In this section, we will discuss the uses of the final keyword in detail.

Use of final Keyword in Java

The keyword final is a non-access modifier. If we want to use the final keyword, we must specify it before a variable, method, and class. It restricts us to access the variable, method, and class. Note that the final methods cannot be inherited and overridden. We must use the final keyword if we want to store the value that does not require to change throughout the execution of the program. Usually, it is used to assign constant values. For example, the value of PI=3.14, g=9.8.

Remember the following points while dealing with the final keyword:

  • Initialize a final variable when it is declared.
  • A blank final variable can be initialized inside an instance-initializer block or inside the constructor.
  • A blank final static variable can be initialized inside a static block.

Let’s discuss the use of the final keyword.

Use of final keyword with a Variable

A variable can be declared as final by using the final keyword. The value of a final variable (constant) cannot be changed once assigned. The final variable must be in uppercase. We can also use underscore to separate two words. For example:

When a final variable is a reference to an object, then this final variable is called the reference final variable. For example, final StringBuffer sb;

Note: In the case of the reference final variable, the internal state of the object pointed by that reference variable can be changed but it is not re-assigning of a reference variable. The mechanism is known as non-transitivity.

The mechanism can also be applied to an array as arrays are objects in Java. Arrays prefix with final is called final arrays.

Use of final keyword with a Method

A method prefix with the keyword final is known as the final method. Note that a final method cannot be overridden. For example, most of the methods of the Java Object class are final.

Use of final keyword with a Class

The class declared as final is called final class. Note that the final class cannot be inherited. There are two uses of the final class i.e. to prevent inheritance and to make classes immutable. For example, all wrapper classes are the final classes and the String class is an immutable class.

You may also like