In Java, final is the access modifier which can be used with a filed, class and a method.
Once you declare a final variable, it is a must to initialize it. You can initialize the final instance variable −
public final String name = "Raju"; public final int age = 20;
{ this.name = "Raju"; this.age = 20; }
public final String name; public final int age; public Student(){ this.name = "Raju"; this.age = 20; }
Note − If you try to initialize the final instance variable elsewhere, a compile-time error will be generated.
In the following Java program, the class Student contains two final variables − name, age and, we are initializing them at the time of declaration −
public class Student { public final String name = "Raju"; public final int age = 20; 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(); } }
Name of the Student: Raju Age of the Student: 20
In the following Java program, the class Student contains two final variables− name, age and, we are initializing them within an instance block −
public class Student { public final String name; public final int age; { this.name = "Raju"; this.age = 20; } 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(); } }
Name of the Student: Raju Age of the Student: 20
In the following Java program, the class Student contains two final variables − name, age and, we are initializing them within a default constructor −
public class Student { public final String name; public final int age; public Student(){ this.name = "Raju"; this.age = 20; } 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(); } }
Name of the Student: Raju Age of the Student: 20