1.包裝類:
基本數(shù)據(jù)類型的數(shù)據(jù)使用起來非常方便,但是如果沒有對(duì)應(yīng)的方法來操作這些數(shù)據(jù),所以我們可以用一個(gè)類把基本數(shù)據(jù)類型的數(shù)據(jù)包裝起來,這個(gè)類叫做包裝類,在包裝類中可以定義一些放啊,來操作基本類型數(shù)據(jù)
| 基本數(shù)據(jù)類型 | 對(duì)應(yīng)包裝類(位于java.long) |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | float |
| double | Double |
| char | Character |
| boolean | Boolean |
裝箱與拆箱
裝箱就是把基本數(shù)據(jù)類型數(shù)據(jù)包裝到包裝類中(基本數(shù)據(jù)類型 ->包裝類)
- 構(gòu)造方法:
Integer(int value)
構(gòu)造一個(gè)新分配的 Integer對(duì)象,該對(duì)象表示指定的 int值。
Integer(String s)
構(gòu)造一個(gè)新分配 Integer對(duì)象,表示 int由指示值 String參數(shù)。
傳遞的字符串必須是基本數(shù)據(jù)據(jù)類型,否則拋出異常
-
靜態(tài)方法:
1.valueOf
public static Integer valueOf(String s)
throws NumberFormatException
返回一個(gè)Integer物體保持在指定的值String 。 該參數(shù)被解釋為表示一個(gè)有符號(hào)的十進(jìn)制整數(shù),就像參數(shù)給予parseInt(java.lang.String)方法一樣。 結(jié)果是一個(gè)Integer對(duì)象,表示由字符串指定的整數(shù)值。
換句話說,該方法返回一個(gè)Integer對(duì)象的值等于:
new Integer(Integer.parseInt(s))
參數(shù)
s - 要解析的字符串。
結(jié)果
一個(gè)保存由string參數(shù)表示的值的 Integer對(duì)象。
異常
NumberFormatException - 如果字符串不能被解析為整數(shù)。
valueOf
public static Integer valueOf(int i)
返回一個(gè)Integer指定的int值的Integer實(shí)例。 如果不需要新的Integer實(shí)例,則該方法通常優(yōu)先于構(gòu)造函數(shù)Integer(int)使用 ,因?yàn)樵摲椒赡芡ㄟ^緩存經(jīng)常請(qǐng)求的值而產(chǎn)生明顯更好的空間和時(shí)間性能。 此方法將始終緩存-128到127(含)范圍內(nèi)的值,并可能會(huì)超出此范圍之外的其他值。
參數(shù)
i - 一個(gè) int價(jià)值。
結(jié)果
一個(gè) Integer實(shí)例,代表 i 。
從以下版本開始:
1.5
拆箱:在包裝類中取出基本數(shù)據(jù)類型的數(shù)據(jù)(包裝類 ->基本數(shù)據(jù)類型)
成員方法: int intValue()以 int 類型返回Integer的值
代碼示例
public class demo01Integer {
public static void main(String[] args) {
//裝箱就是把基本數(shù)據(jù)類型數(shù)據(jù)包裝到包裝類中(基本數(shù)據(jù)類型 ->包裝類)
//構(gòu)造方法
Integer integer = new Integer(1); //方法上有一條紅線說明方法過時(shí)了
System.out.println(integer);
Integer integer1 = new Integer("1");
System.out.println(integer1);
//靜態(tài)方法
Integer integer2 = Integer.valueOf(1);
System.out.println(integer2);
Integer integer3 = Integer.valueOf("1");
// Integer integer3 = Integer.valueOf("a"); //java.lang.NumberFormatException: For input string: "a" 數(shù)字格式化異常
System.out.println(integer3);
//拆箱:在包裝類中取出基本數(shù)據(jù)類型的數(shù)據(jù)(包裝類 ->基本數(shù)據(jù)類型)
int i = integer1.intValue();
System.out.println(i);
}
}