Final Keyword in JAVA – Method , Variable and Classes

Final Keyword in JAVA – Method, Variable, and Classes:-

In this post, I am going to tell you about one of the fundamental keywords in Java. We need a clear understanding of Final keyword not only to write efficient and good programs but also to clear technical interviews.Final in java can be used in three different ways:-

What will be the output of the following code? Are we gonna get any runtime errors as we know final variables cant be changed? Read the Post to find out the answer if you don’t know.

We know basics of final in Java. Let’s Cover some basic points and then we go into more details to find out the answer of above code snippet.

Final Variable:-

Java

1

2

3

4

5

6

7

8

9

<span style="font-family: 'book antiqua', palatino, serif;">classTest

{

finalinti=10;

voidShow()

{

i=20;

}

}</span>

Java

1

Output:-Compilation Error

We get Compilation Error because, if final variables are once initialized you can’t ever reassign the variable with some different value.

Final Methods:-

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<span style="font-family: 'book antiqua', palatino, serif;">classBase

{

finalvoidShow()

{

}

}

classDeriveextendsBase

{

@Override

voidShow()

{

//We Can't Override Method as the method is final

}

}</span>

Java

1

Output:-Compilation Error

A finalmethod in a superclass cannot be overridden in a subclass. Methods that are declared privateare implicitly final because it’s not possible to override them in a subclass. Methods that are declared are static also implicitly final. A final method’s declaration can never change, so all subclasses use the same method implementation, and calls to methods arefinal resolved at compile time and this is known as static binding.

If we use Final in any class we can’t extend or inherit the class, this is the reason above code is throwing the compilation error.A classed declared as final can’t be subclassed.

Now if you go and try to answer the code:-

Java

1

2

3

finalList<String>stringlist=newArrayList<String>();

stringlist.add("Frugalis");

stringlist.add("minds");

Do you know what happens exactly here?

So we are trying to change the state of the object to which a final reference variable is pointing. The important point to understand here is that Once you declare it as final, it is not immutable or read-only.

For references to objects, final ensures that the reference will never change, meaning that it will always refer to the same object. It makes no guarantees whatsoever about the values inside the object being referred to staying the same.

As such, final List<Whatever> stringlist; ensures that stringlist always refers to the same list, but the contents of said list may change over time. Please Comment and Share my articles. If you don’t like it comment we will improve.