Java final variable not initialized

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

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.

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

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

Источник

Can we declare final variables without initialization 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 final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values.

Therefore, it is mandatory to initialize final variables once you declare them.

Still, if you try to declare final variables without initialization that will generate a compilation error saying «variable variable_name not initialized in the default constructor»

Example

In the following Java program, the class Student contains two final variables name and age and they have not been initialized.

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.

Output

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

To resolve this, you need to initialize the declared final variables as −

Example

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(); >>

Output

Name of the Student: Raju Age of the Student: 20

Источник

Final Keyword In Java – Final variable, Method and Class

In this tutorial we will learn the usage of final keyword. The final keyword can be used for variables, methods and classes. We will cover following topics in detail.

1) final variable
2) final method
3) final class

1) final variable

final variables are nothing but constants. We cannot change the value of a final variable once it is initialized. Lets have a look at the below code:

class Demo < final int MAX_VALUE=99; void myMethod()< MAX_VALUE=101; >public static void main(String args[]) < Demo obj=new Demo(); obj.myMethod(); >>
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field Demo.MAX_VALUE cannot be assigned at beginnersbook.com.Demo.myMethod(Details.java:6) at beginnersbook.com.Demo.main(Details.java:10)

We got a compilation error in the above program because we tried to change the value of a final variable “MAX_VALUE”.

Note: It is considered as a good practice to have constant names in UPPER CASE(CAPS).

Blank final variable

A final variable that is not initialized at the time of declaration is known as blank final variable. We must initialize the blank final variable in constructor of the class otherwise it will throw a compilation error (Error: variable MAX_VALUE might not have been initialized).

This is how a blank final variable is used in a class:

class Demo < //Blank final variable final int MAX_VALUE; Demo()< //It must be initialized in constructor MAX_VALUE=100; >void myMethod() < System.out.println(MAX_VALUE); >public static void main(String args[]) < Demo obj=new Demo(); obj.myMethod(); >>

Whats the use of blank final variable?
Lets say we have a Student class which is having a field called Roll No. Since Roll No should not be changed once the student is registered, we can declare it as a final variable in a class but we cannot initialize roll no in advance for all the students(otherwise all students would be having same roll no). In such case we can declare roll no variable as blank final and we initialize this value during object creation like this:

class StudentData < //Blank final variable final int ROLL_NO; StudentData(int rnum)< //It must be initialized in constructor ROLL_NO=rnum; >void myMethod() < System.out.println("Roll no is:"+ROLL_NO); >public static void main(String args[]) < StudentData obj=new StudentData(1234); obj.myMethod(); >>

More about blank final variable at StackOverflow and Wiki.

Uninitialized static final variable

A static final variable that is not initialized during declaration can only be initialized in static block. Example:

class Example < //static blank final variable static final int ROLL_NO; static< ROLL_NO=1230; >public static void main(String args[]) < System.out.println(Example.ROLL_NO); >>

2) final method

A final method cannot be overridden. Which means even though a sub class can call the final method of parent class without any issues but it cannot override it.

class XYZ < final void demo()< System.out.println("XYZ Class Method"); >> class ABC extends XYZ < void demo()< System.out.println("ABC Class Method"); >public static void main(String args[]) < ABC obj= new ABC(); obj.demo(); >>

The above program would throw a compilation error, however we can use the parent class final method in sub class without any issues. Lets have a look at this code: This program would run fine as we are not overriding the final method. That shows that final methods are inherited but they are not eligible for overriding.

class XYZ < final void demo()< System.out.println("XYZ Class Method"); >> class ABC extends XYZ < public static void main(String args[])< ABC obj= new ABC(); obj.demo(); >>

3) final class

We cannot extend a final class. Consider the following example:

final class XYZ < >class ABC extends XYZ < void demo()< System.out.println("My Method"); >public static void main(String args[]) < ABC obj= new ABC(); obj.demo(); >>
The type ABC cannot subclass the final class XYZ

Points to Remember:
1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.
5) A final method cannot be overridden.
6) A final class not be inherited.
7) If method parameters are declared final then the value of these parameters cannot be changed.
8) It is a good practice to name final variable in all CAPS.
9) final, finally and finalize are three different terms. finally is used in exception handling and finalize is a method that is called by JVM during garbage collection.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

Is there a difference in declaring a class final or marking the class and methods final. I think that making the class final makes the methods as well but I’m not sure for any extra information that i have missed in your post.

Dude, if you want only one of the methods of a super class to be not overridden by subclass, you need to mark the method as abstract instead of marking the class as final (which makes it not inheritable). And if you want all the methods in a super class to be not overridden but be available for sub class to access), u need to use abstract keywords for all abstract methods.

i like your website because every topic is simply represent with an good and useful example, that why everything gonna be easier to understand…. please carry on.

final int MAX_VALUE=99;
void myMethod() MAX_VALUE=101;
> instance variables and local variables are different , MAX_VALUE=101; should be intialized, and prints output 101 , as there is no relation in MAX_VALUE=99; and MAX_VALUE=101;

Источник

Оцените статью