加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么我可以在没有显式转换的情况下为一个char变量赋值

发布时间:2020-12-15 00:55:34 所属栏目:Java 来源:网络整理
导读:我想知道为什么这个片段有效. char ch1;ch1 = 'a' + 1;System.out.println(ch1); 在第2行中,不是将右侧提升为int然后将int赋值给char,我们是否需要显式转换? 同样,我理解当你执行ch1 = 65时会发生什么.但是由于Java不允许自动向下类型转换,我们不需要从int
我想知道为什么这个片段有效.
char ch1;
ch1 = 'a' + 1;
System.out.println(ch1);

在第2行中,不是将右侧提升为int然后将int赋值给char,我们是否需要显式转换?

同样,我理解当你执行ch1 = 65时会发生什么.但是由于Java不允许自动向下类型转换,我们不需要从int到char的显式转换吗?

解决方法

因为 Java Language Specification说:

In addition,if the expression is a constant expression (§15.28) of type byte,short,char or int :

A narrowing primitive conversion may be used if the type of the variable is byte,or char,and the value of the constant expression is representable in the type of the variable.

所以你是正确的,因为表达式被提升为int,但因为它是一个常量表达式,所以不需要强制转换.如果它涉及一个变量(或者它的值不适合char),那就不一样了.

对于这类问题,最好立即查看语言规范,因为它是权威的来源,对于规范来说非常易读.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读