Why final variable doesn't require initialization in main method in java?


In Java final is the access modifier which can be used with a filed class and a method.

  • When a method if final it cannot be overridden.
  • When a variable is final its value cannot be modified further.
  • When a class is final it cannot be extended.

Declaring final variable without initialization

If you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don’t, a compile-time error is generated.

Example

 Live Demo

public class Student {
   public final String name;
   public final int age;
   public void display(){
      System.out.println("Name of the Student: "+this.name);
      System.out.println("Age of the Student: "+this.age);
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Compile time error

On compiling, this program generates the following error.

Student.java:3: error: variable name not initialized in the default constructor      
private final String name;
                     ^
Student.java:4: error: variable age not initialized in the default constructor
private final int age;
                  ^
2 errors

Declaring a final variable without initialization

Generally, once you declare a local variable you need to initialize it before using it for the first time. If you try to use it without initialization then, you will get an error.

But, it is fine to declare a local variable final without initialization until you use it.

Example1

In the following Java program, we are declaring a local variable as final. Since we are not using it this gets compiled without errors.

public class Student {
   public static void main(String args[]) {
      final String name;
   }
}

But, if you try to use it then, it will generate an error −

Example2

In the following Java program, we are declaring a local variable as final and using it

 Live Demo

public class Student {
   public static void main(String args[]) {
      final String name;
      System.out.println(name);
   }
}

Compile time error

On compiling, the above program generates the following error −

Student.java:4: error: variable name might not have been initialized System.out.println(name);
                                                                                        ^
1 error

Updated on: 29-Jun-2020

502 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements