为什么我可以分配一个int到一个字符变量没有显式转换? [英] Why can I assign an int to a char variable without an explicit cast?

查看:162
本文介绍了为什么我可以分配一个int到一个字符变量没有显式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么此代码段工作。

  char ch1; 
ch1 ='a'+ 1;
System.out.println(ch1);

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



同样,我理解当你做 ch1 = 65 时会发生什么。但是由于Java不允许自动向下类型转换,我们不需要从 int char ? / p>

解决方案

因为 Java语言规范说:


此外,如果表达式是常量表达式如果变量的类型是byte,short或char,则可以使用缩小的原语转换,并且可以使用类型为byte,short,char或int的类型:


$ b可以在变量类型中表示常量表达式的值。


所以你是对的,表达式被提升为 int ,但因为它是一个常量表达式,所以不需要转换。如果它涉及一个变量(或其值不适合 char ),则会有所不同。



对于这种问题,最好立即查看语言规范,因为它是权威的来源,并且对于规范是可读的。


I wanted to know why this snippet works.

char ch1;
ch1 = 'a' + 1;
System.out.println(ch1);

In line 2, isn't the right hand side promoted to an int and then for assigning int to char, won't we need an explicit cast?

Similarly, I understand what happens when you do ch1 = 65. But since Java does not allow automatic down type conversion, don't we need explicit cast from int to char?

解决方案

Because the Java Language Specification says:

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, short, or char, and the value of the constant expression is representable in the type of the variable.

So you're right in that the expression is promoted to int, but because it's a constant expression, the cast is not necessary. If it involved a variable (or its value did not fit into a char), it would be different.

For this kind of question it's best to look at the language specification right away, as it's the authoritative source and quite readable for a specification.

这篇关于为什么我可以分配一个int到一个字符变量没有显式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆