Java final Keyword: Difference between revisions
Jump to navigation
Jump to search
(One intermediate revision by the same user not shown) | |||
Line 9: | Line 9: | ||
An attempt to assign a final variable the second time is detected as compilation error. | An attempt to assign a final variable the second time is detected as compilation error. | ||
A ''blank final'' is a final variable that | A ''blank final'' is a final variable that does not have an initializer. | ||
A ''constant variable'' is a final variable of a primitive type or String initialized with a constant expression. | A ''constant variable'' is a final variable of a primitive type or String initialized with a constant expression. | ||
Line 16: | Line 16: | ||
* a field of an interface | * a field of an interface | ||
* a local variable declared as a resource of a [[Java_7_try-with-resources#Overview|try-with-resource]] statement. | * a local variable declared as a resource of a [[Java_7_try-with-resources#Overview|try-with-resource]] statement. | ||
* an exception parameter of a multi-catch clause. |
Latest revision as of 20:23, 27 September 2017
Internal
Overview
A final variable may only be assigned to once. The final variable may be defined unassigned and immediately assigned to ("definite assignment"). Once a final variable has been assigned, it always contains the same value. If the variable contain a reference of an object, the state of the referred object may change, but the variable will always refer to the same object.
An attempt to assign a final variable the second time is detected as compilation error.
A blank final is a final variable that does not have an initializer.
A constant variable is a final variable of a primitive type or String initialized with a constant expression.
Variables are implicitly final in the following cases:
- a field of an interface
- a local variable declared as a resource of a try-with-resource statement.
- an exception parameter of a multi-catch clause.