Compile-time and Runtime Constants
Please learn from the following code first
1 | package individual.cy.learn.mess; |
Its outputs is as follows:
1 | shanxi |
compile-time constant
Compile-time Constant: A variable use final
modifier, its type is primitive type
or String
, and its value is a constant expression
.
What is constant expression?
Constant Expressions in Oracle
e.g. Constant expressions:
1 | true |
A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the
following:
-
Literals of primitive type and literals of type String
-
Casts to primitive types and casts to type String
-
The unary operators +, -, ~, and ! (but not
++
or--
) -
The multiplicative operators *, /, and %
-
The additive operators + and -
-
The shift operators <<, >>, and >>>
-
The relational operators <, <=, >, and >= (but not
instanceof
) -
The equality operators == and !=
-
The bitwise and logical operators &, ^, and |
-
The conditional-and operator && and the conditional-or operator ||
-
The ternary conditional operator ? :
-
Parenthesized expressions whose contained expression is a constant expression.
-
Simple names that refer to constant variables.
-
Qualified names of the form TypeName . Identifier that refer to constant variables.
Constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.
A constant expression is always treated as FP-strict, even if it occurs in a context where a non-constant expression would not be considered to be
FP-strict.
All in all, except for instanceof
, ++
, --
runtime constant
Runtime constant: A variable use static
modifier, except for compile-time constant.
Class file
Compile-time constants' reference will be replaced with the actual value, like as follows.
1 | package individual.cy.learn.mess; |
1 | package individual.cy.learn.mess; |