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

WBOY
WBOY 转载
2023-09-13 17:09:03 767浏览

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

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

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

有两种各种整数类型转换

  • 文字到变量赋值: 例如,s1 = 123456,数据超出范围。它在编译时已知,并且编译器会标记错误。
  • 变量到变量赋值:例如,s1 = i1 。该阶段int存储的值为:4567,完全在short类型的范围之内,编译器不会抛出任何错误。可以通过显式转换 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

以上就是如何在Java 9的JShell中实现整数类型转换?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除