基本型別(byte, short, int, long, float, double)非物件。Java 為每種提供包裝類(Byte, Short, Integer, Long, Float, Double),皆繼承抽象類 Number。

JDK 1.5+ 編譯器自動在基本型別與包裝類間轉換:
Integer x = 5; // 裝箱:Integer.valueOf(5)
x = x + 10; // 拆箱:x.intValue() + 10 → 裝箱:Integer.valueOf(15)
System.out.println(x); // 15(toString)
頻繁裝箱拆箱有效能開銷,熱點迴圈建議用基本型別。
| 方法 | 說明 |
|---|---|
xxxValue() | 轉為對應基本型別(如 intValue()、doubleValue()) |
compareTo(Number) | 數值比較 |
equals(Object) | 值相等判斷 |
toString() | 字串表示 |
| 方法 | 說明 | 範例 |
|---|---|---|
valueOf(String) / valueOf(int) | 建立包裝物件(-128~127 快取) | Integer.valueOf("123") |
parseInt(String) / parseInt(String, radix) | 解析字串為基本型別 | parseInt("FF",16)=255 |
toString(int) / toString(int, radix) | 數值轉字串 | toString(255,16)="ff" |
compare(a, b) | 比較兩基本型別值 | Integer.compare(5,3)=1 |
min/max(a, b) | 最小/最大值 | |
sum(a, b) | 求和(JDK 1.8+) | |
bitCount / highestOneBit / numberOfLeadingZeros | 位運算工具 |
java.lang.Math 提供大量 static 方法:
| 分類 | 方法範例 |
|---|---|
| 絕對值/極值 | abs, max, min |
| 捨入 | ceil, floor, round, rint |
| 指數/對數 | exp, log, log10, pow, sqrt |
| 三角函數 | sin, cos, tan, asin, acos, atan, atan2 |
| 角度/弧度轉換 | toDegrees, toRadians |
| 隨機數 | random() 返回 [0,1) double |
| 精確運算 (JDK 1.8+) | addExact, multiplyExact, toIntExact 溢位拋異常 |
Math.max(10, 20); // 20
Math.sqrt(16); // 4.0
Math.pow(2, 10); // 1024.0
Math.round(3.14); // 3 (long)
Math.random(); // 0.0 ~ 1.0
Math.toRadians(180); // π
Math.addExact(100, 200); // 300,溢位拋 ArithmeticException
MathContext 控制精度與捨入模式。BigDecimal a = new BigDecimal("0.1");
BigDecimal b = new BigDecimal("0.2");
System.out.println(a.add(b)); // 0.3(精確)
// double: 0.1+0.2=0.30000000000000004
equals() 或 compareTo(),禁用 ==(快取範圍外會失效)。parseXxx 而非 valueOf(後者多一次裝箱)。BigDecimal,建構子用 String 參數避免二進制誤差。ThreadLocalRandom,安全需求用 SecureRandom。