Java數值類型包裝器
Byte, Short, Integer, Long, Float 和 Double 類類是數字包裝類。
它們都繼承自Number抽象類。但是不能創建Number類的對象。 但是,我們可以聲明Number類的引用變量。可以將六個數值包裝類中的任何一個的對象引用分配給Number類的引用。Number類包含六個方法。 它們被命名爲xxxValue(),其中xxx是六種基本數據類型之一(byte,short,int,long,float和double)。這些方法的返回類型與xxx相同。
示例
以下代碼顯示如何從數字包裝器對象檢索不同的原始數據類型值:
public class Main {
public static void main(String[] args) {
Integer intObj = Integer.valueOf(100);
// Gets byte from Integer
byte b = intObj.byteValue();
// Gets double from Integer
double dd = intObj.doubleValue();
System.out.println("intObj = " + intObj);
System.out.println("byte from intObj = " + b);
System.out.println("double from intObj = " + dd);
// Creates a Double object
Double doubleObj = Double.valueOf("123.45");
// Gets different types of primitive values from Double
double d = doubleObj.doubleValue();
float f = doubleObj.floatValue();
int i = doubleObj.intValue();
long l = doubleObj.longValue();
System.out.println("doubleObj = " + doubleObj);
System.out.println("double from doubleObj = " + d);
System.out.println("float from doubleObj = " + f);
System.out.println("int from doubleObj = " + i);
System.out.println("long from doubleObj = " + l);
}
}
上面的代碼生成以下結果。
intObj = 100
byte from intObj = 100
double from intObj = 100.0
doubleObj = 123.45
double from doubleObj = 123.45
float from doubleObj = 123.45
int from doubleObj = 123
long from doubleObj = 123
方法
在Java8在一些數值包裝類(如Integer,Long,Float和Double)中添加了一些方法,如:sum(),max()和min()。
例如,Integer.sum(10,20)簡單地返回10 + 20的求值結果。
它們的引用使用集合lambda表達式。包裝器類處理包含原始值的字符串。
- 使用
valueOf()方法將字符串轉換成包裝器對象。 - 使用
parseXxx()方法將字符串轉換爲原始值。
Byte, Short, Integer, Long, Float 和 Double 類分別包含parseByte(),parseShort(),parseInt(),parseLong(),parseFloat()和parseDouble()方法將字符串解析爲原始值。
以下代碼是將包含二進制格式的整數的字符串轉換爲Integer對象和int值:
public class Main {
public static void main(String[] args) {
String str = "01111111";
int radix = 2;
// Creates an Integer object from the string
Integer intObject = Integer.valueOf(str, radix);
// Extracts the int value from the string
int intValue = Integer.parseInt(str, 2);
System.out.println("str = " + str);
System.out.println("intObject = " + intObject);
System.out.println("intValue = " + intValue);
}
}
執行上面的示例代碼,得到如下結果 -
str = 01111111
intObject = 127
intValue = 127
值
所有數值包裝類都包含幾個有用的常量。它們的MIN_VALUE和MAX_VALUE個常數表示最小值和最大值。它們還有SIZE常數,其表示對應原始類型的變量佔據的位的大小。
以下代碼嘗試將兩個字符串解析爲雙精度(double)值。
第一個字符串包含有效的double值,第二個字符串包含無效的double值。 當調用parseDouble()方法來解析第二個字符串時,就會拋出NumberFormatException。
public class Main {
public static void main(String[] args) {
String str1 = "123.45";
try {
double value1 = Double.parseDouble(str1);
System.out.println("value1 = " + value1);
} catch (NumberFormatException e) {
System.out.println("Error in parsing " + str1);
}
String str2 = "8B.99"; // An invalid double
try {
double value2 = Double.parseDouble(str2);
System.out.println("value2 = " + value2);
} catch (NumberFormatException e) {
System.out.println("Error in parsing " + str2);
}
}
}
執行上面的示例代碼,得到如下結果 -
value1 = 123.45
Error in parsing 8B.99