在Java中,我们有时会使用final对变量进行修饰,被修饰的变量只能够被赋值一次。如果final变量是引用类型,则它将永远持有相同的对象的引用;如果是简单类型,则它会拥有着不变的值。
那么,final变量就是我们所说的常量吗?事实上不是的,因为一个被final修饰的变量,虽然只能被赋值一次,但是如果它为引用类型的变量,那么它所指向的对象则可能改变,所以称其为'可变变量'更好,而常量的范围相对可变变量来说,更加狭窄。在Java语言规范(§4.12.4)中,对于常量有着明确的定义:A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28). Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9), and definite assignment (§16 (Definite Assignment)).
这说明,常量(或者说是常量变量)仅可能为简单类型或者String类型,是被一个常量表达式初始化,并且必须为final的,而常量表达式的定义在Java语言规范(§15.28)中有着定义: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 (§3.10.1, §3.10.2, §3.10.3, §3.10.4, §3.10.5)
Casts to primitive types and casts to type String (§15.16)
The unary operators +, -, ~, and ! (but not ++ or --) (§15.15.3, §15.15.4, §15.15.5, §15.15.6)
The multiplicative operators *, /, and % (§15.17)
The additive operators + and - (§15.18)
The shift operators <>, and >>> (§15.19)
The relational operators , and >= (but not instanceof) (§15.20)
The equality operators == and != (§15.21)
The bitwise and logical operators &, ^, and | (§15.22)
The conditional-and operator && and the conditional-or operator || (§15.23, §15.24)
The ternary conditional operator ? : (§15.25)
Parenthesized expressions (§15.8.5) whose contained expression is a constant expression.
Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
Qualified names (§6.5.6.2) of the form TypeName . Identifier that refer to constant variables (§4.12.4).
...