The final Keyword

Learn how to use the final keyword in Java.

We'll cover the following

Sometimes, we require a variable to not actually be a variable in Java programs. This means that the value of the variable should not change during the execution of the program. For example, if you’re using a double type variable, pi, to store the value of π\pi, which is a mathematical constant, you wouldn’t want to accidentally update it. Thus, for situations like these, we have the keyword: final.

The final keyword

To declare an unchangeable variable, just add final before the type and name of the variable as shown here:

final type name;

You can either initialize the variable straight away by using the assignment operator. For example:

final double pi = 3.14; 

Or you can declare it first and initialize it later, as shown here:

final double pi;
pi = 3.14;

However, remember that any attempt to update the value of this variable would result in an error!

Example

Let’s say we want to write a program that calculates the circumference of the circle using the value of radius. According to the formula:

Circumference=2πradiusCircumference = 2 * \pi * radius

Here, π\pi is a mathematical constant with a value of 3.141592653593.141592653593.143.14.

Let’s start the coding!

Get hands-on with 1400+ tech skills courses.