JAVA編程思想(第四版)學習筆記----4.8 switch(知識點已更新)

來源:互聯網
上載者:User

標籤:with   ted   variable   break   character   spec   pes   case   jdk   

switch語句和if-else語句不同,switch語句可以有多個可能的執行路徑。在第四版java編程思想介紹switch語句的文法格式時寫到:

switch (integral-selector) {        case integral-value1:             statement;             break;        case integral-value12:            statement;             break;        default:            statement;        }

其中integral-selector(整數選擇因子)是一個能產生整數值的運算式。並且說明選擇因子必須是一個int或者char那樣的整數值,或者是一個enum枚舉類型。由於java編程思想第四版是在JDK1.5的基礎上進行編寫的,所以對現在來說當時的書中介紹的難免有過時之處。

在java官方手冊中找到switch語句的說明中,已經明確指出了 A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types , the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer。其中enum枚舉類型是JDK1.5中新增加的新特性,而switch對於String字串的支援則是在JDK7以後。

在使用JDK7版本的環境進行編程時,使用switch語句的選擇因子,如果不符合規範(比如float類型變數)會產生提示: Cannot switch on a value of type float. Only convertible int values, strings or enum variables are permitted 由於, byte,short,char 都可以隱含轉換為 int 所以int類型變數中也包含了byte,short,char類型變數。

總結:

可以用作switch選擇因子的資料類型有:

  • char,byte,short,int以及他們的封裝類Character,Byte,Short,Integer
  • enmu枚舉 (since jdk1.5)
  • String字串(since jdk1.7)

 

JAVA編程思想(第四版)學習筆記----4.8 switch(知識點已更新)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.