Java char 也是 int 吗?

2022-01-13 00:00:00 type-conversion java equivalence

我正在尝试为课程完成一些代码:

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?

推荐答案

Java 语言规范 状态

当带有 Expression 的 return 语句出现在方法中时声明,Expression 必须 可分配(第 5.2 节) 到声明的方法的返回类型,或发生编译时错误.

When a return statement with an 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.

控制一个值是否可分配给另一个值的规则定义为

where the rules governing whether one value is assignable to another is defined as

赋值上下文允许使用以下之一:

Assignment contexts allow the use of one of the following:

  • 扩大原语转换(§5.1.2)

原始类型的 19 种特定转换称为扩展原始转换:

19 specific conversions on primitive types are called the widening primitive conversions:

  • charintlongfloat 或 `double
  • char to int, long, float, or `double

最后

扩展原语转换不会丢失有关在下列情况下,数值的总大小,其中数值被完全保留:[...]

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: [...]

char 到整数类型 T 的扩展转换将零扩展char 值的表示以填充更宽的格式.

A widening conversion of a char to an integral type T zero-extends the representation of the char value to fill the wider format.

简而言之,作为 return 语句表达式的 char 值可通过扩展原语转换分配给 int 的返回类型.

In short, a char value as the expression of a return statement is assignable to a return type of int through widening primitive conversion.

相关文章