如何在 Java 9 中的 JShell 中实现整数类型转换?

javaobject oriented programmingprogramming更新于 2025/10/22 9:16:17

JShell  是 Java 9 版本中引入的命令行交互工具,允许程序员执行简单的语句、表达式、变量、方法、类、接口等,而无需声明 ma​​in() 方法。

在 JShell 中,编译器会通过抛出错误来警告程序员有关类型转换 问题。但是,如果程序员意识到这一点,则需要显式转换。如果我们需要将较小的数据值存储到较大的类型转换中,则需要隐式转换。

有两种整数类型转换:

  • 文字到变量的赋值:例如,短型s1 = 123456,数据超出范围。它在编译时已知,并且编译器会标记错误。
  • 变量到变量的赋值:例如,s1 = i1。该阶段存储在 int 中的值:4567,完全在短型类型的范围内,并且编译器不会抛出任何错误。可以使用显式强制转换 s1 = (short) i1 来抢占它。

在下面的代码片段中,我们可以实现隐式和显式类型转换。

C:\Users\User>jshell
|   Welcome to JShell -- Version 9.0.4
|   For an introduction type: /help intro

jshell> byte b = 128;
|   Error:
|   incompatible types: possible lossy conversion from int to byte
|   byte b = 128;
|            ^-^

jshell> short s = 123456;
|   Error:
|   incompatible types: possible lossy conversion from int to short
|   short s = 123456;
|             ^----^

jshell> short s1 = 3456
s1 ==> 3456

jshell> int i1 = 4567;
i1 ==> 4567

jshell> s1 = i1;
|   Error:
|   incompatible types: possible lossy conversion from int to short
|   s1 = i1;
|        ^^

jshell> s1 = (short) i1;
s1 ==> 4567

jshell> int num = s1;
num ==> 4567

相关文章


有用资源