Java 資料型別分布林型、字元型、數值型(整數/浮點數),對應變數型別:boolean、char、byte/short/int/long、float/double,另常用 String、Date。本文系統整理六大類轉換場景。
低階向高階隱式轉換:byte → short/char → int → long → float → double。高階向低階需強制型別轉換:byte b = (byte)i;,可能溢位或失精度,不建議濫用。
六大包裝類:Boolean, Character, Integer, Long, Float, Double 對應基本型別。String、Date 本身即類別。
new Integer(123)。xxxValue(),如 intValue()、doubleValue(),亦可跨數值型別轉換。new Integer("123")、new Boolean("true");Date 亦有 new Date(String)。charAt()、toCharArray()。toString() 輸出字串。整數另提供 toBinaryString()、toHexString()、toOctalString()。Character.getNumericValue('1') 回傳數值 1(而非 ASCII 49),區別於直接字元→整數轉換。
new Date(long) / getTime()。getYear()、getMonth() 等。toString()。掌握上述轉換,應付實務開發綽綽有餘。