基本類型包裝類概述
爲什麼會有基本類型包裝類?
爲了對基本數據類型進行更多的操作,更方便的操作,java就針對每一種基本數據類型提供了對應的類類型。
常用的操作之一:用於基本數據類型與字符串之間的轉換。
基本類型和包裝類的對應:
基本類型 | 包裝類 |
---|---|
byte | Byte |
short | Short |
int | Integer |
char | Character |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
Integer類的概述和構造方法
Integer 類在對象中包裝了一個基本類型 int 的值。Integer 類型的對象包含一個 int 類型的字段。
該類提供了多個方法,能在 int 類型和 String 類型之間互相轉換,還提供了處理 int 類型時非常有用的其他一些常量和方法。
構造方法:
Integer類重載構造方法,但是沒有空參構造。
public Integer(int value); 對於該構造方法可以傳遞一個int類型的值即可。
public Integer(String s); 對於該構造方法,需要傳遞一個字面值看起來是數字的字符串。
String和int類型的相互轉換
int到String:
- 和""進行拼接
public class Demo3 {
public static void main(String[] args) {
int a=100;
String s=a+"";
System.out.println(s);
}
}
- public static String valueOf(int i)
public class Demo3 {
public static void main(String[] args) {
int a = 100;
String s = String.valueOf(a);
System.out.println(s);
}
}
- int到Integer再到String
public class Demo3 {
public static void main(String[] args) {
int a = 120;
Integer integer = new Integer(a);
String s = integer.toString();
System.out.println(s);
}
}
- public static String toString(int i)
public class Demo3 {
public static void main(String[] args) {
int a = 120;
Integer integer = new Integer(a);
String s = integer.toString();
System.out.println(s);
}
}
String到int:
- String到Integer再使用intValue();
public class Demo3 {
public static void main(String[] args) {
String s="1903";
Integer integer = new Integer(s);
int num=integer.intValue();
System.out.println(num);
}
}
- public static int parseInt(String s)
public class Demo3 {
public static void main(String[] args) {
String s="1985";
int num = Integer.parseInt(s);
System.out.println(num);
}
}
自動裝箱和拆箱
JDK5有了新特性:
- 自動裝箱:把基本類型轉換爲包裝類類型
public class Demo3 {
public static void main(String[] args) {
Integer integer=100;
System.out.println(integer);
}
}
- 自動拆箱:把包裝類類型轉換爲基本類型
public class Demo3 {
public static void main(String[] args) {
int num=new Integer(185);
System.out.println(num);
}
}
但是,在使用時候,Integer x = null; 代碼就會出現NullPointerException。所以最好先判斷是否爲null,然後再使用。