Integer.parseInt() 是 Java 中將字符串轉為整數的核心方法,看似簡單,實則藏著進制轉換、異常處理、性能優化等實戰細節。本文系統梳理其語法重載、進制參數原理、常見異常與最佳實踐。
// 基礎版:默認十進制
public static int parseInt(String s) throws NumberFormatException
// 進制版:指定基數 (2-36)
public static int parseInt(String s, int radix) throws NumberFormatException
"-123"),不允許空格、下劃線、小數點。Character.MIN_RADIX (2) 到 Character.MAX_RADIX (36)。超出範圍拋出 NumberFormatException。radix 決定了字符串字符的「權重」。以 "12" 為例:
| radix | 解析邏輯 | 十進制結果 |
|---|---|---|
| 10 (默認) | 1×10¹ + 2×10⁰ | 12 |
| 8 (八進制) | 1×8¹ + 2×8⁰ | 10 |
| 16 (十六進制) | 1×16¹ + 2×16⁰ | 18 |
| 2 (二進制) | 字符必須為 0/1,"12" 非法 | 拋異常 |
實戰案例:Integer.parseInt("444", 16) → 4×16² + 4×16¹ + 4×16⁰ = 1092。
public class ParseIntDemo {
public static void main(String[] args) {
int x = Integer.parseInt("9"); // 十進制 9
double c = Double.parseDouble("5"); // 5.0 (Double 同理)
int b = Integer.parseInt("444", 16); // 十六進制 444 -> 1092
System.out.println(x); // 9
System.out.println(c); // 5.0
System.out.println(b); // 1092
}
}
parseInt("12a")parseInt("")、parseInt(null)int 範圍(-2³¹ ~ 2³¹-1):parseInt("2147483648")parseInt("9", 8)(八進制無數字 9)parseInt 返回基本類型 int,無裝箱開銷。但若誤用 new Integer(str) 或 Integer.valueOf(str) 會創建對象,高併發下增加 GC 壓力。
"0x" 或 "#" 不被識別,需手動去除:parseInt(hexStr.replace("0x", ""), 16)。parseInt("-FF", 16) → -255。| 類型 | 方法 | 示例 |
|---|---|---|
| long | Long.parseLong(s, radix) | 大數值場景 |
| double | Double.parseDouble(s) | 無 radix 重載 |
| float | Float.parseFloat(s) | 科學計數法支援 |
| byte/short | Byte.parseByte / Short.parseShort | 範圍更小,溢出更易發生 |
try-catch NumberFormatException。str.trim() 去除空白,移除已知前綴(0x、0b)。parseXxx 而非 valueOf,避免不必要的裝箱。convertBase(str, fromRadix, toRadix) 方法,復用邏輯。