1. 程式人生 > 實用技巧 >Java 基本資料型別

Java 基本資料型別

八大基本資料型別

資料型別 記憶體 取值範圍 包裝類 預設值
byte 1位元組8位 -128~127 Byte 0
short 2位元組16位 -32768~32767 Short 0
int 4位元組32位 -231~231-1 Integer 0
long 8位元組64位 -263~263-1 Long 0L
float 4位元組32位 3.4e45~1.4e38 Float 0.0f
double 8位元組64位 4.9e324~1.8e308 Double 0.0d
boolean 1位元組8位 true與false Boolean false
char 2位元組16位,儲存Unicode碼 2^16 -1 Character \u0000

注意:JVM 在編譯時期會把 boolean 型別的資料轉換為 int,使用1表示 true,0表示 false

包裝型別

基本型別都有對應的包裝型別,基本型別與對應包裝型別之間的賦值使用自動裝箱和拆箱完成
由基本型別向對應的包裝型別轉換稱為裝箱
由包裝類相對應的基本資料型別轉換稱為拆箱
基本型別的效率 優於 裝箱型別

Integer x = 2;     // 裝箱 呼叫了 Integer.valueOf(2)
int y = x;         // 拆箱 呼叫了 X.intValue()

快取池

int a = 128, b = 128;
System.out.println(a == b);                        //true
        
Integer a1 = 127, b1 = 127;
System.out.println(a1 == b1);                      //true
        
Integer a2 = 128, b2 = 128;
System.out.println(a2 == b2);                      //false
System.out.println(a2.equals(b2));                 //true
System.out.println(a2.intValue() == b2.intValue());//true
Integer x = 127; //自動裝箱,如果在-128到127之間,則值存在常量池 IntegerCache 中。等同於 Integer x = Integer.valueOf(127);
Integer y = new Integer(127); //普通的堆中的物件

對於裝箱型別,正確的比較寫法應該是 a2.equals(b2) 或者 a2.intValue() == b2.intValue()
Integer 內部使用了 IntegerCache,
預設情況下,對於在(-128 <= i <=  127)範圍的值,裝箱賦值時,直接取的快取,是同一個物件,引用相同,所以 == 運算返回 true


基本型別對應的緩衝池如下:
    * boolean values true and false
    * all byte values
    * short values between -128 and 127
    * int values between -128 and 127
    * char in the range \u0000 to \u007F

調整快取池大小:
    JVM引數設定 -XX:AutoBoxCacheMax=<size> 來指定這個緩衝池的大小