Java char也是int吗? [英] Java char is also an int?

查看:127
本文介绍了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?

推荐答案

当方法中出现带有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:

  • a widening primitive conversion (§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.

简而言之,通过扩展基元转换,可以将char值作为return语句的表达式分配给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吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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