Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding of final variable [duplicate]

Tags:

java

oop

final

Suppose a class contains a final variable. Why is new space allocated for final variable every time an object of the class is created even though its value can't be changed? Why its memory allocation is not like a static variable?

like image 221
Prashantha Avatar asked Sep 20 '18 20:09

Prashantha


Video Answer


3 Answers

Consider this example:

public class Example {
    public final int someNum;
    // constructor
    public Example(int n) {
        someNum = n;
    }
}

Here in this example, every object of this class might have a different value for someNum, even though it is a final variable. Therefore new space must be allotted for every instance of the class.

like image 182
GBlodgett Avatar answered Oct 19 '22 03:10

GBlodgett


While you can't assign a new value to a final variable, each instance of the class can have a different value, so each instance needs to allocate its own memory for its own member.

like image 5
Mureinik Avatar answered Oct 19 '22 03:10

Mureinik


For final variables in Java, it is not necessary to assign a value when declared. A final variable can be assigned value later, but only once. As a different value can be assigned it needs different memory allocation.

like image 3
Tishat Ahasan Avatar answered Oct 19 '22 02:10

Tishat Ahasan