switch分支語法如下:
switch (key) { case value: break; default: break; }
其中的key值就是變數,這個變數的型別可以為什么呢?
答:在JDK1.5之前,switch回圈只支持byte short char int四種資料型別.JDK1.5 在switch回圈中增加了列舉類與byte short char int的包裝類,對四個包裝類的支持是因為java編譯器在底層手動進行拆箱,而對列舉類的支持是因為列舉類有一個ordinal方法,該方法實際上是一個int型別的數值.jdk1.7開始支持String型別,但實際上String型別有一個hashCode演算法,結果也是int型別.而byte short char型別可以在不損失精度的情況下向上轉型成int型別.所以總的來說,可以認為switch中只支持int.
我們來看資料型別的大小 (從小到大):byte—> short, char—> int —> long—>float —> double
我們清楚資料型別小轉大是不需要強轉的所以int 以下包含int就是swich回圈中key值所包含的資料型別
下面有一個小例題:
public static void main(String[] args) { /*byte x = 1; short x = 1; String x = "1"; long x = 1; double x = 1; int x =1; char x =1; Integer x = new Integer("1");*/ switch (x) { case 1: System.out.println("One"); break; case 2: System.out.println("Two"); break; } }
總結:swich所支持的基本資料型別有:byte,short ,char,int,以及他們包裝型別 如:Integer Byte 等...
這是jdk7之前的自jdk7更新后,swich支持String型別 寫法如下
String x1 = "true"; switch (x1) { case "true": System.out.println("One"); break; case "flase": System.out.println("Two"); break; }
除此之外,還有列舉Enum 如下:
Status status = Status.PROCESSING; switch (status) { case OPEN: System.out.println("open"); break; case PROCESSING: System.out.println("processing"); break; case CLOSE: System.out.println("close"); break; default: System.out.println("default"); }
官網檔案:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
可以試著看看 個人學習,內容拙劣見諒
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/170366.html
標籤:Java
上一篇:【Java-jxl插件】【Excel檔案讀寫報錯】jxl.read.biff.BiffException: Unable to recognize OLE stream
下一篇:騰訊IM
