6

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Prashantha
  • 155
  • 1
  • 6

3 Answers3

14

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.

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
  • This could be a silly question. We are calling someNum to be final. Still it is not assuming different values for each object. If its final, how does it have different values? – Vishnu Dahatonde Aug 16 '19 at 07:03
  • 1
    @VDevD `someNum` will only ever hold one value. However if you construct three different instances of the class, each instance can have a different value for `someNum` – GBlodgett Aug 18 '19 at 20:36
5

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
3

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.

Hulk
  • 6,399
  • 1
  • 30
  • 52