更新時間:2022-11-15 10:33:43 來源:動力節(jié)點 瀏覽1407次
Integer 類在對象中包裝了一個基本類型 int 的值。Integer 類對象包含一個 int 類型的字段。此外,該類提供了多個方法,能在 int 類型和 String 類型之間互相轉(zhuǎn)換,還提供了處理 int 類型時非常有用的其他一些常量和方法。
Integer 類中的構(gòu)造方法有以下兩個:
Integer(int value):構(gòu)造一個新分配的 Integer 對象,它表示指定的 int 值。
Integer(String s):構(gòu)造一個新分配的 Integer 對象,它表示 String 參數(shù)所指示的 int 值。
例如,以下代碼分別使用以上兩個構(gòu)造方法來獲取 Integer 對象:
Integer integer1 = new Integer(100); // 以 int 型變量作為參數(shù)創(chuàng)建 Integer 對象
Integer integer2 = new Integer("100"); // 以 String 型變量作為參數(shù)創(chuàng)建 Integer 對象
在 Integer 類內(nèi)部包含一些和 int 類型操作有關(guān)的方法,表 1 列出了這些常用的方法。
方法 | 返回值 | 功能 |
---|---|---|
byteValue() | byte | 以 byte 類型返回該 Integer 的值 |
shortValue() | short | 以 short 類型返回該 Integer 的值 |
intValue() | int | 以 int 類型返回該 Integer 的值 |
toString() | String | 返回一個表示該 Integer 值的 String 對象 |
equals(Object obj) | boolean | 比較此對象與指定對象是否相等 |
compareTo(Integer anotherlnteger) |
int | 在數(shù)字上比較兩個 Integer 對象,如相等,則返回 0; 如調(diào)用對象的數(shù)值小于 anotherlnteger 的數(shù)值,則返回負值; 如調(diào)用對象的數(shù)值大于 anotherlnteger 的數(shù)值,則返回正值 |
valueOf(String s) | Integer | 返回保存指定的 String 值的 Integer 對象 |
parseInt(String s) | int | 將數(shù)字字符串轉(zhuǎn)換為 int 數(shù)值 |
在實際的編程過程中,經(jīng)常將字符串轉(zhuǎn)換為 int 類型的數(shù)值,或者將 int 類型的數(shù)值轉(zhuǎn)換為對應(yīng)的字符串。以下代碼演示如何實現(xiàn)這兩種功能:
String str = "456";
int num = Integer.parseInt(str); // 將字符串轉(zhuǎn)換為int類型的數(shù)值
int i = 789;
String s = Integer.toString(i); // 將int類型的數(shù)值轉(zhuǎn)換為字符串
注意:在實現(xiàn)將字符串轉(zhuǎn)換為 int 類型數(shù)值的過程中,如果字符串中包含非數(shù)值類型的字符,則程序執(zhí)行將出現(xiàn)異常。
例 1
編寫一個程序,在程序中創(chuàng)建一個 String 類型變量,然后將它轉(zhuǎn)換為二進制、八進制、十進制和十六進制輸出。
public class Test03 {
public static void main(String[] args) {
int num = 40;
String str = Integer.toString(num); // 將數(shù)字轉(zhuǎn)換成字符串
String str1 = Integer.toBinaryString(num); // 將數(shù)字轉(zhuǎn)換成二進制
String str2 = Integer.toHexString(num); // 將數(shù)字轉(zhuǎn)換成八進制
String str3 = Integer.toOctalString(num); // 將數(shù)字轉(zhuǎn)換成十六進制
System.out.println(str + "的二進制數(shù)是:" + str1);
System.out.println(str + "的八進制數(shù)是:" + str3);
System.out.println(str + "的十進制數(shù)是:" + str);
System.out.println(str + "的十六進制數(shù)是:" + str2);
}
}
運行后的輸出結(jié)果如下:
40的二進制數(shù)是:101000
40的八進制數(shù)是:50
40的十進制數(shù)是:40
40的十六進制數(shù)是:28
Integer 類包含以下 4 個常量。
MAX_VALUE:值為 231-1 的常量,它表示 int 類型能夠表示的最大值。
MIN_VALUE:值為 -231 的常量,它表示 int 類型能夠表示的最小值。
SIZE:用來以二進制補碼形式表示 int 值的比特位數(shù)。
TYPE:表示基本類型 int 的 Class 實例。
下面的代碼演示了 Integer 類中常量的使用。
int max_value = Integer.MAX_VALUE; // 獲取 int 類型可取的最大值
int min_value = Integer.MIN_VALUE; // 獲取 int 類型可取的最小值
int size = Integer.SIZE; // 獲取 int 類型的二進制位
Class c = Integer.TYPE; // 獲取基本類型 int 的 Class 實例
相關(guān)閱讀