CORE JAVA

ProwessApps Learning Portal

Final keyword in Java


In java programming final can be :

  1. Variable
  2. Method
  3. Class
1. Java final variable (Constant)

In Java, to make constant we use final keyword.

If you make any variable as final, you cannot change the value of that variable.

Naming convention for final variable (class constants) is, write in upper case..

Test.java Copy Code
public class Test
{
  final int x =20;
  void calculate()
   {
     x = 30;
   }
}    
OUTPUT :
Test.java:6: error: cannot assign a value to final variable x
     x = 30;
     ^
1 error
Rules for final variables in Java:
  1. Initialization: A final variable must be initialized exactly once. It can be initialized either at the time of declaration or in a constructor for instance variables, or in a static initializer block for static variables.

    FinalVariableInitializationExample.java Copy Code
    public class FinalVariableInitializationExample {
        // Final instance variable initialized at the time of declaration
        final int x = 10;
    
        // Blank final instance variable
        final int y;
    
        // Constructor to initialize the blank final variable
        public FinalVariableInitializationExample() {
            y = 20;
        }
    
        public static void main(String[] args) {
            FinalVariableInitializationExample obj = new FinalVariableInitializationExample();
            System.out.println("x: " + obj.x); // Output: 10
            System.out.println("y: " + obj.y); // Output: 20
        }
    }
    

  2. No reassignment: Once initialized, the value of a final variable cannot be changed. Any attempt to reassign a value to a final variable will result in a compilation error.

    FinalVariableReassignmentExample.java Copy Code
    public class FinalVariableReassignmentExample {
        final int x = 10;
    
        public void modifyFinalVariable() {
            // Compilation error: Cannot assign a value to final variable 'x'
            // x = 20;
        }
    
        public static void main(String[] args) {
            FinalVariableReassignmentExample obj = new FinalVariableReassignmentExample();
            System.out.println("x: " + obj.x); // Output: 10
        }
    }
    
    

  3. Final parameters: Method parameters can be declared as final. This means that the value of the parameter cannot be changed within the method.

    FinalParameterExample.java Copy Code
    public class FinalParameterExample {
        public void printValue(final int x) {
            // Compilation error: Cannot assign a value to final variable 'x'
            // x = 20;
            System.out.println("Value of x: " + x);
        }
    
        public static void main(String[] args) {
            FinalParameterExample obj = new FinalParameterExample();
            obj.printValue(10); // Output: Value of x: 10
        }
    }
    

  4. Final class members: In Java, final variables can be used to declare constant values. These variables are typically declared as static and final, and their values are conventionally written in uppercase letters.

    ConstantsExample.java Copy Code
    public class ConstantsExample {
        public static final double PI = 3.14159;
    
        public static void main(String[] args) {
            System.out.println("Value of PI: " + ConstantsExample.PI); // Output: 3.14159
        }
    }
    

  5. Final instance variables in anonymous classes: When a final instance variable is accessed within an anonymous class, it must be effectively final, meaning that its value cannot change after initialization. This restriction ensures that the variable can be safely accessed from within the anonymous class.

    AnonymousClassExample.java Copy Code
    public class AnonymousClassExample {
        public void printValue() {
            final int x = 10; // Final local variable
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    // x = 20; // Compilation error: Cannot assign a value to final variable 'x'
                    System.out.println("Value of x: " + x);
                }
            };
            r.run();
        }
    
        public static void main(String[] args) {
            AnonymousClassExample obj = new AnonymousClassExample();
            obj.printValue(); // Output: Value of x: 10
        }
    }
    
2. Java final method

If you make any method as final, you cannot override it.

Main.java Copy Code
class Parent
{
  final void calculate()
   {
     //definition
   }
}

class Child extends Parent
{
 void calculate()
 {
   //definition
 }
}
public class Main{
    public static void main(String [] args){
    
    }
}
OUTPUT :
Main.java:11: error: calculate() in Child cannot override calculate() in Parent
 void calculate()
      ^
  overridden method is final
1 error

Note :Final methods can be inherited by subclasses, but they cannot be overridden.

3. Java final class

If you make any class as final, you cannot extend it.

Main.java Copy Code
final class FinalClass
{
  void calculate()
   {
     //definition
   }
}
// Compilation error: Cannot inherit from final FinalClass
class SubClass extends Parent
{
 void show()
 {
   //definition
 }
}
public class Main{
    public static void main(String [] args){
    
    }
}
OUTPUT :
Main.java:9: error: cannot inherit from final FinalClass
class SubClass extends FinalClass
                    ^
1 errorR


Is final method inherited?

Yes,final method is inherited but you cannot override it.


What is the blank or uninitialized final variable?

A final variable that is not initialized at the time of declaration is known as blank final variable.


Can we initialize blank final variable?

Yes, but only in constructor.

class Test
{
  final int x;
  Test()
   {
     x = 10;
   }
}           

What is the static blank final variable ?

Answer :

A static final variable that is not initialized at the time of declaration.

It can be initialized only in static block.

class Test
{
  static final int X;
  static
   {
     X = 10;
   }
} 




advertisement