标题翻译
(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.
专注分享java语言的经验与见解,让所有开发者获益!
评论