| 類型 | 大小 | 位數 | 範圍 / 精度 | 預設值 |
|---|---|---|---|---|
| boolean | 1 bit (實作相關) | 1 | true / false | false |
| byte | 1 byte | 8 | -128 ~ 127 | 0 |
| short | 2 bytes | 16 | -32,768 ~ 32,767 | 0 |
| char | 2 bytes | 16 | \\u0000 ~ \\uFFFF (Unicode BMP) | \\u0000 |
| int | 4 bytes | 32 | -2,147,483,648 ~ 2,147,483,647 | 0 |
| float | 4 bytes | 32 | IEEE 754 單精度 (~7 位有效數字) | 0.0f |
| long | 8 bytes | 64 | -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 | 0L |
| double | 8 bytes | 64 | IEEE 754 雙精度 (~15-16 位有效數字) | 0.0d |
Java 所有整數類型皆為有號 (Two's Complement)。沒有 unsigned 關鍵字,範圍固定不隨硬體/OS 變化。
byte b = -1; // 0xFF
int unsigned = b & 0xFF; // 結果 255 (隱式轉為 int)
& 0xFF 保留低 8 位,高位補 0。結果自動提升為 int (32 位),因 byte 容不下 255。
short s = -1; // 0xFFFF
int unsigned = s & 0xFFFF; // 65535
int i = -1; // 0xFFFFFFFF
long unsigned = i & 0xFFFFFFFFL; // 4294967295L
// Byte/Short/Integer/Long 類別提供靜態方法
int uByte = Byte.toUnsignedInt((byte) 200); // 200
int uShort = Short.toUnsignedInt((short) 50000); // 50000
long uInt = Integer.toUnsignedLong(-1); // 4294967295L
long uLong = Long.toUnsignedLong(-1L); // 18446744073709551615 (溢位,僅邏輯)
// 反向
byte b = (byte) 200; // 編譯警告,執行時 -56
byte b2 = (byte) Integer.parseUnsignedInt("200"); // 同樣 -56
&、|、^、~、<<、>>、>>> 為單指令操作,比加減乘除更快,適合大量資料轉換。
| Java | Oracle 對應類型 | 備註 |
|---|---|---|
| byte | NUMBER(3) | 範圍 -128~127 |
| short | NUMBER(5) | 範圍 -32768~32767 |
| int | NUMBER(10) | 標準整數映射 |
| long | NUMBER(19) | 或 BIGINT (12c+) |
| float | BINARY_FLOAT | 單精度 |
| double | BINARY_DOUBLE | 雙精度,預設 NUMBER 精度更高 |
| String | VARCHAR2 / CLOB | char[] 映射 |
| BigDecimal | NUMBER | 精確金融計算 |
byte b = 200; 編譯錯誤 (超出範圍),需 byte b = (byte) 200; 存儲為 -56Integer.parseUnsignedInt("4000000000") (Java 8+)char 是無號 16 位整數,可直接參與算術:'A' + 1 = 66 ('B')雖然本文主題為 Java 基本類型,但理解「無符號處理」與「位元運算」對於處理 Oracle RAW、BLOB、網路協定解析、加密演算法等場景至關重要。Java 8+ 的 toUnsigned* 系列方法已大幅簡化此類操作。