Java char也是int吗? [英] Java char is also an int?
问题描述
我正在尝试为班级做一些代码:
I was trying to get some code done for class:
public int getValue(char value) {
if (value == 'y') return this.y;
else if (value == 'x') return this.x;
由于最终我可能无法返回任何内容,因此它告诉我最终要执行以下操作:
Since I might not be able to return anything in the end, it told me to do this at the end:
return value;
这让我感到惊讶,因为该方法的返回类型是int
类型.但是,它告诉我返回char
!我正在使用Eclipse,并且习惯了无数的警告和提示,这是一个很大的惊喜.
This surprised me because the return type for the method was of type int
. Yet, it was telling me to return a char
! I'm using eclipse, and accustomed to the endless number of warnings and stuff, this was a major surprise.
那么,char
真的是int
吗?为什么会这样?
So, is a char
really an int
? Why is this happening?
推荐答案
当方法中出现带有 When a return statement with an 其中将一个值是否可分配给另一个值的规则定义为 where the rules governing whether one value is assignable to another is defined as 分配上下文允许使用以下之一: Assignment contexts allow the use of one of the following: 和 原始类型的19种特定转换称为扩展
原始转换: 19 specific conversions on primitive types are called the widening
primitive conversions: 最后 不断扩展的原始转换不会丢失有关
在以下情况下,数值的总体大小,其中
精确保留数值:[...] A widening primitive conversion does not lose information about the
overall magnitude of a numeric value in the following cases, where the
numeric value is preserved exactly: [...] A widening conversion of a 简而言之,通过扩展基元转换,可以将 In short, a 这篇关于Java char也是int吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!Expression
的return语句时
声明,Expression
必须 可分配给已声明的对象(第5.2节)
方法的返回类型,否则会发生编译时错误.
Expression
appears in a method
declaration, the Expression
must be assignable (§5.2) to the declared
return type of the method, or a compile-time error occurs.
char
到int
,long
,float
或`double
char
to int
, long
, float
, or `double
char
到整数类型T
的加宽转换将零扩展
char
值的表示形式以填充更宽的格式.char
to an integral type T
zero-extends the
representation of the char
value to fill the wider format.char
值作为return
语句的表达式分配给int
的返回类型.char
value as the expression of a return
statement is assignable to a return type of int
through widening primitive conversion.