1.int和Integer之間的轉換:
1) int----->Integer
①自動裝箱
②Integer的構造方法
③調用Integer的靜態方法:static Integer valueOf(int i):返回一個指定int值的Integer對象
代碼如下:
int a = 10;
Integer i1 = a; //①
Integer i2 = new Integer(a); //②
Integer i3 = Integer.valueOf(a); //③
2) Integer------>int
①自動拆箱
②調用Integer的方法:int intValue():以int類型返回該Integer的值
示例代碼:
Integer a = new Integer(10);
int i1 = a; //①
int i2 = a.intValue(); //②
2.String和Integer之間的轉換:
1) Integer---->String
①調用Integer的方法:String toString():返回該Integer對象的字符串形式
②調用Integer的靜態方法:static String toString(int i):返回一個指定整數的String對象
③調用String的靜態方法:static String valueOf(Object obj):返回任意類型的字符串形式
示例代碼:
Integer a = new Integer(20);
String str1 = a.toString(); //①
String str2 = Integer.toString(a); //②
String str3 = String.valueOf(a); //③
2) String---->Integer
①調用Integer的靜態方法:static Integer valueOf(String s):返回指定的 String 的值的 Integer 對象。
注意:這里的參數s必須是可以解析成整數的字符串,否則會報異常:NumberFormatException
示例代碼:
String str = "123";
Integer i = Integer.valueOf(str); //①
3.int和String之間的轉換:
1) int------>String
①字符串拼接,使用+
②調用Integer的靜態方法:static String toString(int i):返回一個指定整數的String對象
③調用String的靜態方法:static String valueOf(int i):返回指定int值的字符串形式
示例代碼:
int a = 5;
String s1 = a +""; //①
String s3 = Integer.toString(a); //②
String s2 = String.valueOf(a); //③
2) String----->int
①調用Integer的靜態方法:static int parseInt(String s):將一個可以解析為整數的字符串解析為一個int值
②調用Integer的靜態方法:static Integer valueOf(String s):返回指定的 String 的值的 Integer 對象。【自動拆箱】
示例代碼:
String str = "123";
int m1 = Integer.parseInt(str); //①
int m2 = Integer.valueOf(str); //②--->自動拆箱
int m3 = Integer.valueOf(str).intValue(); //②--->手動拆箱