資料類型轉換是 Java 程式設計中最基礎也最頻繁的操作之一。從基本類型之間的擴大/縮小轉換,到包裝類的拆箱裝箱,再到 String、Date 與數值類型的複雜互轉,掌握完整的轉換體系對於撰寫健壯、高效的代碼至關重要。本文將系統梳理 Java 類型轉換的核心規則、API 與最佳實踐。
Java 將基本類型按「容量」分級:
(byte, short, char) → int → long → float → double
int i = 100; long l = i; // 自動double d = 3.14; int i = (int) d; // i=3,精度遺失特殊規則:char 可視為無號整數參與運算,但轉 byte/short 需強制轉型;boolean 不參與任何數值轉換。
每種基本類型對應一個包裝類:Byte, Short, Integer, Long, Float, Double, Character, Boolean。它們是不可變類別,提供豐富的工具方法。
Integer i = Integer.valueOf(100);(推薦,利用快取)int val = i.intValue();valueOf()/xxxValue()。Integer i = 100; int val = i;效能提示:Integer.valueOf() 預設快取 -128~127 範圍內的實例,頻繁創建大整數物件時考慮使用 new Integer() 或基本類型陣列。
所有數值包裝類繼承自 Number,提供統一的 xxxValue() 方法:
Double d = 3.14;
int i = d.intValue(); // 3
long l = d.longValue(); // 3
float f = d.floatValue(); // 3.14f
解析靜態方法(拋出 NumberFormatException):
Integer.parseInt("123") → intInteger.valueOf("123") → IntegerDouble.parseDouble("3.14"), Boolean.parseBoolean("true") 等進制轉換:Integer.parseInt("FF", 16) (十六進位) → 255。
String.valueOf(123) / String.valueOf(true)(通用、null 安全)Integer.toString(123) / Double.toString(3.14)Integer.toBinaryString(10) → "1010", toHexString(255) → "ff", toOctalString(8) → "10"obj.toString()(需確保物件非 null)str.charAt(index) → 單一 charstr.toCharArray() → char[]new String(charArray) / String.valueOf(charArray) → String關鍵區別:
'1' → (int)'1' = 49 (ASCII/Unicode 碼點)Character.getNumericValue('1') = 1,支援 Unicode 數字字元(如羅馬數字、中文數字)。注意:現代開發強烈建議使用 java.time 套件。以下為舊版 API 快速參考:
new Date(year-1900, month-1, day) (@Deprecated)new Date(year-1900, month-1, day, hrs, min, sec) (@Deprecated)new Date(System.currentTimeMillis()) 或 new Date(long ms)new Date(String)(格式依賴實現,極不推薦)getTime() → long 毫秒時間戳 (核心)getYear()+1900, getMonth(), getDate(), getHours()... (@Deprecated)toString() → "Dow Mon DD HH:MM:SS ZZZ YYYY"// 當前時間
Instant now = Instant.now(); // 時間戳
LocalDateTime ldt = LocalDateTime.now(); // 本地日期時間
ZonedDateTime zdt = ZonedDateTime.now(); // 帶時區
// 互轉
long ms = now.toEpochMilli(); // → long
Instant ins = Instant.ofEpochMilli(ms); // long → Instant
// 格式化/解析
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String str = ldt.format(fmt);
LocalDateTime parsed = LocalDateTime.parse(str, fmt);
NumberFormatException,並考慮輸入驗證。float/double,改用 BigDecimal。java.time,棄用 java.util.Date、Calendar、SimpleDateFormat(非執行緒安全)。Integer.toXxxString 系列方法,清晰可讀。