JAVA Integer類詳解
阿新 • • 發佈:2021-07-19
Integer 類物件包含一個 int 型別的欄位。此外,該類提供了多個方法,能在 int 型別和 String 型別之間互相轉換,還提供了處理 int 型別時非常有用的其他一些常量和方法。
Integer 類的構造方法
- Integer(int value):構造一個新分配的 Integer 物件,它表示指定的 int 值。
- Integer(String s):構造一個新分配的 Integer 物件,它表示 String 引數所指示的 int 值。
- Integer integer1 = new Integer(100); // 以 int 型變數作為引數建立 Integer 物件
- Integer integer2 = new Integer("100"); // 以 String 型變數作為引數建立 Integer 物件
Integer 類的常用方法
在 Integer 類內部包含一些和 int 型別操作有關的方法,表 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 | 在數字上比較兩個 Integer 物件,如相等,則返回 0; 如呼叫物件的數值小於 anotherlnteger 的數值,則返回負值; 如呼叫物件的數值大於 anotherlnteger 的數值,則返回正值 |
valueOf(String s) | Integer | 返回儲存指定的 String 值的 Integer 物件 |
parseInt(String s) | int | 將數字字串轉換為 int 數值 |
- String str = "456";
- int num = Integer.parseInt(str); // 將字串轉換為int型別的數值
- int i = 789;
- String s = Integer.toString(i); // 將int型別的數值轉換為字串
注意:在實現將字串轉換為 int 型別數值的過程中,如果字串中包含非數值型別的字元,則程式執行將出現異常。
編寫一個程式,在程式中建立一個 String 型別變數,然後將它轉換為二進位制、八進位制、十進位制和十六進位制輸出。
- public class Test{
- public static void main(String[] args) {
- int num = 40;
- String str = Integer.toString(num); // 將數字轉換成字串
- String str1 = Integer.toBinaryString(num); // 將數字轉換成二進位制
- String str2 = Integer.toHexString(num); // 將數字轉換成八進位制
- String str3 = Integer.toOctalString(num); // 將數字轉換成十六進位制
- System.out.println(str + "的二進位制數是:" + str1);
- System.out.println(str + "的八進位制數是:" + str3);
- System.out.println(str + "的十進位制數是:" + str);
- System.out.println(str + "的十六進位制數是:" + str2);
- }
- }
40的二進位制數是:101000
40的八進位制數是:50
40的十進位制數是:40
40的十六進位制數是:28
Integer 類的常量
Integer 類包含以下 4 個常量。
- MAX_VALUE:值為 231-1 的常量,它表示 int 型別能夠表示的最大值。
- MIN_VALUE:值為 -231的常量,它表示 int 型別能夠表示的最小值。
- SIZE:用來以二進位制補碼形式表示 int 值的位元位數。
- TYPE:表示基本型別 int 的 Class 例項。
- 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 例項