Easy Tutorial
For Competitive Exams

Java Programming Final Keyword

What is final variable?

Final keyword is a modifier used to restrict the user from doing unwanted code or preventing from the code or value from being changed.

Final can be applied to

  • Variable(prevent value change)
  • Method(prevent overridding)
  • Class(prevent inheritance)

How to use final variable in Java?

when final variable is used with a variable, it is specifically for restricting the user from changing the value anywhere else in the code.

A final variable, once initialized, its value cannot be changed.

Any change in the value of final variable more than once will result in compilation error.

Example

class FinalVariableExample {
    final int count = 0;
    public FinalVariableExample() {           
         count++; 
	}
      public static void main(String args[]){
      FinalVariableExample s1=new FinalVariableExample();
 }
}
Try it Yourself

How to use final method in Java?

when final variable is used with method, it restricts the inheriting class from overriding the method definition.

Example

public class Parent {
     final void testCode(){
           System.out.println("This is a final method");
    }
}

class Child extends Parent{
      void testCode(){
           System.out.println("This is overriding method");
	}
public static void main(String args[]){
    Child  c1=new Child ();
     c1.testCode();

    }
}
Try it Yourself

How to use final class in Java?

when final variable is used for a class as a modifier, it restricts the class from being extended or inherited by any other class.

Example

public final class Parent {
       final void testCode1(){
	   System.out.println("This is a final method");
	}
}

class Child extends Parent{
        void testCode(){
	    System.out.println("This is overriding method");
	}
public static void main(String args[]){
    Child  c1=new Child ();
     c1.testCode();
   }
}
Try it Yourself

Solve this!!

14260.What is the output of this program?
class Test {
 public static void main(String args[]){
    final int i;
    i = 20;
    i = 30;
    System.out.println(i);
 }
}
10
20
30
Error
Explanation:
i is assigned a value twice. Final variables can be assigned values only one.
14261.What is the output of this program?
class Base {
  public final void show() {
       System.out.println("Base::show() called");
    }
}
class Derived extends Base {
    public void show() {  
       System.out.println("Derived::show() called");
    }
}
public class Main {
    public static void main(String[] args) {
        Base b = new Derived();;
        b.show();
    }
}
Error
Base::show() called
Derived::show() called
None of the above
Explanation:
compiler error: show() in Derived cannot override show() in Base
Share with Friends