Java char is also an int?(Java char 也是 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?
推荐答案
Java 语言规范 状态
当带有 Expression 的 return 语句出现在方法中时声明,Expression 必须 可分配(第 5.2 节) 到声明的方法的返回类型,或发生编译时错误.
When a return statement with an
Expressionappears in a method declaration, theExpressionmust 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:
char到int、long、float或 `double
chartoint,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.
这篇关于Java char 也是 int 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java char 也是 int 吗?
基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
