Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
6 views
in Java by (10.2k points)

In Java we use the final keyword with variables to specify its values are not to be changed. But I see that you can change the value in the constructor/methods of the class. Again, if the variable is static then it is a compilation error.

Here is the code:

import java.util.ArrayList;

import java.util.List;

class Test {

  private final List foo;

  public Test()

  {

      foo = new ArrayList();

      foo.add("foo"); // Modification-1

  }

  public static void main(String[] args) 

  {

      Test t = new Test();

      t.foo.add("bar"); // Modification-2

      System.out.println("print - " + t.foo);

  }

}

The above code works fine and no errors.

Now change the variable as static:

private static final List foo;

Now it is a compilation error. How does this final really work?

1 Answer

0 votes
by (46k points)

You are perpetually authorized to initialize a final variable. The compiler makes it certain that you can perform it only once.

Perceive that calling methods on an object saved in a final variable has nothing to act with the semantics of the final. In other words: the final is simply about the citation itself, and not about the contents of the referenced object.

Java has no notion of object immutability; this is accomplished by deliberately creating the object, and is a far-from-trivial effort.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 16, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Jul 9, 2019 in Java by Nigam (4k points)

Browse Categories

...