Java 資料型別分為布林、字元、數值(整數/浮點數)三大類,對應八種基本型別。實務開發中頻繁面臨型別轉換需求,本文系統整理六大轉換場景與最佳實踐。
型別階層:byte, short, char → int → long → float → double
int i = b; // byte b(byte)i,可能溢位或精度損失,非必要不建議使用。六大包裝類:Boolean, Character, Integer, Long, Float, Double
new Integer(10) 或靜態工廠 Integer.valueOf(10)(推薦,支援快取)。xxxValue() 方法,如 intValue()、doubleValue()。亦可跨型別取值,如 Double 物件取 intValue()。new Integer("123") 或靜態 parseXxx("123")(推薦,不建立物件)。new Date(String) 或 SimpleDateFormat 解析(生產環境強烈建議後者)。toCharArray()、charAt(index)、new String(char[])。toString();整數尚有 toBinaryString()、toHexString()、toOctalString();日期建議用 SimpleDateFormat 格式化。'1' 字元轉數值 1(非 ASCII 49),使用 Character.getNumericValue('1') 返回 1。
new Date(long ms) 與 getTime(),毫秒數基準為 GMT 1970-01-01 00:00:00。getYear()、getMonth() 等(注意:月份 0-11,年份為 1900 起算,建議改用 Calendar)。toString() 或 SimpleDateFormat。valueOf() 利用快取減少物件建立。parseXxx() 避免多餘物件。