java switch const_java – switch case中不接受的最终常量

我想知道方法add()中的2个声明之间的区别,如下所示.

final int c;

c = 20;

final int c = 20;

我认为两者都是最终变量,我无法重新分配任何新值.以下是以不同方式处理上述声明的方法.

void add() {

final int a = 30;

final int b = 10;

final int c;

c = 20;

switch (a) {

case b + c:

System.out.println("In case b+c");

break;

default:

break;

}

}

抱怨,上面的方法根本没有编译

constant expression required case b+c

如果变量c在一行中声明并初始化,如final int c = 30;.有用.

解决方法:

JLS #4.12.4将常量变量定义为(强调我的):

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression, is called a constant variable.

在你的情况下,最终int c = 20;是一个常量变量但是最终的int c; c = 20;不是.

标签:java,final,switch-statement,java-7

来源: https://codeday.me/bug/20190722/1506905.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值