(Java) 返回类型是int,但我可以返回一个char。为什么?

huangapple go评论138阅读模式
英文:

(Java) The return type is int, but I can return a char.Why?

问题

返回类型是int,但我可以返回一个char。为什么?

 public class Test{
      public int returnInt(){
        return 'a';
    }
}
英文:

The return type is int, but I can return a char. Why?

 public class Test{
      public int returnInt(){
        return 'a';
    }
}

答案1

得分: 1

这将返回字符的ASCII值。从char到int之间存在隐式类型转换。
https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.2

英文:

It will return the ascii value of the character. There is implicit type casting from char to int.
https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.2

答案2

得分: 0

在Java中,char(以及其他原始类型)类似于int类型。因此,您可以将char视为int,如示例所示:

char ch = 'a';
ch++;
ch = ch + 'r';

因此,您的函数将返回所返回char的对应ASCII值。

英文:

char (and other primitive types) in Java are like int's.
so you can use the char as an int see the example

char ch = 'a';
ch++;
ch = ch + 'r';

so your function will return the corresponding ASCII for that returned char.

huangapple
  • 本文由 发表于 2020年3月16日 17:20:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/60703228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定