This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

usefinalWhen a keyword modifies a variable, is the reference immutable or the referenced object immutable?

When the final keyword is used to modify a variable, it indicates that the variable cannot be changed and that the contents of the object to which the reference variable refers can be changed. For example, for the following statement:

final StringBuffer s = new StringBuffer("xcbeyond");
Copy the code

A compile-time error is reported by executing the following statement:

s = new StringBuffer("xcbeyond1");
Copy the code

However, the following statement can be compiled:

 a.append(" hello!"); 
Copy the code

When you define a method’s parameters, you might want to prevent the method from modifying the passed parameter object internally:

public void method(final  StringBuffer  param) {}Copy the code

In fact, this is incorrect, so final cannot decorate parameters ina method. If it can be modified, it violates the principle that final modified variables cannot be modified. Inside the method you can still add the following code to modify the parameter object: param.append(“a”);

Final review:

  1. The reference variable of a final modifier cannot be changed, but the reference variable pointing to the object can be changed. As described in this paper.

  2. Final modified classes can no longer be inherited.

  • Java strings are final classes and cannot be inherited! Math is also the final class

  • In real project development, final classes are not allowed in principle! Such as Spring,Hibernate, and Struts 2, these frameworks often use dynamic proxy (dynamic inheritance) techniques. The use of final classes can create working problems for these frameworks.

  1. finalDecorated methods can no longer be overridden.

In real project development, final methods are not allowed in principle!

  1. Final modified variables are not allowed to be modified after initialization.

  2. Final static, Java uses final static variables as a general requirement that variable names have uppercase letters.