java常量final是什么_Java杂谈:final与常量

在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).

...

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值