The final Keyword and Variables in Java Tutorial

In this section, we will learn what the final keyword is and how to use it in Java.

What is final keyword in Java?

The Java final keyword is used to limit what users can do in certain areas!

These areas are variables, methods, parameters, and classes.

For example, by default when you create a variable in Java, you’re able to store a value in it and, in later times, replace that value with a new one.

But if you apply the final keyword on a variable, you become limited to just apply a value in that variable only once! After that, if you try to replace the old value with a new one, you’ll get a compile time error.

In case of variables, sometime we need to make sure that the value of a variable will never change after its initialization. That’s why using the final keyword on such a variable can be useful.

Where we can use the final keyword in Java?

As mentioned before, there are four areas in which we can apply the `final` keyword.

1) Java final variable (field)

When a variable is turned into final, we can only initialize it once and after that there’s no way to reassign a new value to it.

This is useful when we have a value in a program and we know it won’t change throughout the life cycle of a program. So then we can create a final variable and store that value there and be assured that the value won’t change.

Java final Variable Syntax:

final Datatype variable_name;

The keyword `final` comes before the datatype of a variable.

Example: Java final variable

public class Simple {

    public static void main(String[] args){
        final int age;
        age = 100;
        System.out.println(age);
    }
}

Output: 100

As you can see, here the variable `age` is declared as final and the value 100 is assigned to it. After this initialization, you can’t change the value of this variable anymore.

If you attempt to change the value of a final variable, you’ll get a compile time error.

Example: changing the value of a final variable in Java

public class Simple {

    public static void main(String[] args){
        final int age;
        age = 100;
        age = 200;
        System.out.println(age);
    }
}

Output:

Error: variable age might already have been assigned

As you can see, because we tried to reassign the variable `age` we’ve got the compile time error.

When to use a final variable:

We should use final variables when we want to store a value in a program and want to make sure the content of that variable won’t change accidentally or intentionally throughout the life of a program.

More to Read:

Java final methods

Java final class

 

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies