This article is participating in the Java Topic Month – Java Debug Notes event. See the event link for details

Debug Note < How does the “final” keyword in Java work? >

Ask questions

In Java, we use the final variable keyword to specify that its value is not changed.

But I see that you can change the value in the constructor/method of the class. Again, if the variable is static, it’s a compilation error. Here’s 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); }}Copy the code

The above code works fine without errors.

Now change the variable to static:

private static final List foo;

This is now a compilation error. How does the final really work?

Answer a

You are always allowed to initialize a final variable. The compiler ensures that you can only execute once.

Note that calling methods on objects stored in final variables is semantically independent of final.

In other words: Final is only about the reference itself, not the contents of the reference object.

Java has no concept of object invariance. This is achieved by carefully designing objects, which is a hard job.

Answer two

This is a favorite interview question. With this in mind, try to find out how well you understand object constructs, methods, class variables (static variables), and instance variables.

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 void setFoo(List foo) {
       //this.foo = foo; Results in compile time error.}}Copy the code

In the above case, we define a constructor for “Test” and specify the “setFoo” method for it.

About the constructor: The constructor can be called only once using the new keyword at the creation time of each object. You cannot call the constructor more than once, because that is not the purpose of the constructor.

About methods: A method can be called as many times as needed (or never), and the compiler knows about the method.

The article translated from Stack Overflow: stackoverflow.com/questions/1…