java 为什么方法返回类型中可以将 char 转为 Short

Tsv*_*gov 3 java methods casting short char

我在Java中有以下方法:

private static short charToShort_1() {
    return 's';
}

private static char shortToChar_1() {
    return ((short) 15);
}

private static short charToShort_2() {
    char ch = 's';
    return ch;
}

private static char shortToChar_2() {
    short number = 15;
    return number;
}
Run Code Online (Sandbox Code Playgroud)

为什么“charToShort_1”和“shortToChar_1”编译成功?
同时,最后两个方法“charToShort_2”和“shortToChar_2”无法编译(因为需要显式转换)。

dav*_*xxx 5

这里 :

\n\n
private static short charToShort_1() {\n    return \'s\';\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

\'s\'是一个常量表达式,该值可以用 表示short。\n因此编译器会进行隐式转换。

\n\n

JLS规定

\n\n
\n

此外,如果表达式是 byte、short、char 或 int 类型的常量表达式 (\xc2\xa715.28)\n:

\n\n
    \n
  • 如果变量的类型是 byte、short 或 char,并且常量表达式的值可以用变量的类型表示,则可以使用缩小基元转换。
  • \n
\n
\n\n

取值short范围为 -32,76832,767(含)。\n因此超出这些范围的
常量表达式将产生编译错误:char

\n\n
private static short charToShort_2() {\n   return \'\xe8\x80\x80\'; // 32768 numeric value       \n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

关于这个无法编译的方法:

\n\n
private static short charToShort_2() {\n    char ch = \'s\';\n    return ch;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

char ch = \'s\';不是常量表达式。
\n您可以重新分配一个无法表示的ch新值(例如用数值表示的值)。\n因此编译器希望您显式地将其转换为\n因为转换可能是缩小原始转换。\n将其更改为变量,您将看到它可以正常编译:charshort\'\xe8\x80\x80\'32768
short
final

\n\n
private static short charToShort_2() {\n    final char ch = \'s\';\n    return ch;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

short关于这个从to转换的方法char,编译错误原因与 for 完全相同charToShort_2()

\n\n

最后,关于shortToChar_1()

\n\n
private static char shortToChar_1() {\n    return ((short) 15);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

转换为短可能会给人这样的印象:与使用以下命令相比,您花费的内存更少int

\n\n
private static char shortToChar_1() {\n    return 15;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

事实上,它不会改变任何东西,因为在这两种情况下,编译器都会使用bipushJVM 指令将 abyte作为整数值压入堆栈。

\n


归档时间:

查看次数:

550 次

最近记录:

7 年,8 月 前