gpt4 book ai didi

Java char 也是 int 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:50:29 26 4
gpt4 key购买 nike

我试图为类完成一些代码:

public int getValue(char value) {
if (value == 'y') return this.y;
else if (value == 'x') return this.x;

由于我可能最终无法返回任何东西,它告诉我最后这样做:

return value;

这让我感到惊讶,因为该方法的返回类型是 int 类型。然而,它告诉我返回一个 char!我正在使用 Eclipse,并且习惯了无穷无尽的警告和其他东西,这是一个很大的惊喜。

那么,char 真的是 int 吗?为什么会这样?

最佳答案

Java Language Specification

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.

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

Assignment contexts allow the use of one of the following:

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

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

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 的返回类型。

关于Java char 也是 int 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30717898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com