如何在Java 9的JShell中實現整數型別轉換?
JShell 是Java 9版本中引入的一個命令列互動式工具,允許程式設計師執行簡單的語句、表示式、變數、方法、類、介面等,無需宣告main()方法。
在JShell中,編譯器會透過丟擲錯誤來警告程式設計師關於型別轉換問題。但是,如果程式設計師知道這一點,則需要進行顯式轉換。如果需要將較小的資料值儲存到較大的型別中,則需要隱式轉換。
有兩種整數型別轉換
- 字面量到變數賦值:例如,short 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
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP