包装类与基本数据类型与String类型之间的相互转换
-
包装类与基本数据类型
-
基本数据类型---->包装类
-
通过构造器
Integer t = new Integer(11);
-
通过自动装箱
Integer t1 = 11;
-
通过 包装类的valueOf( 基本数据类型) 来转换
Integer i=Integer.valueOf(123); // 有缓存区
-
-
包装类—>基本数据类型
-
调用包装类的方法
Integer i = new Integer(11); int num3= i.intValue();//调用包装类的方法 //源码: Integer类中 public int intValue() { return value; }
-
自动拆箱
int num2 =i;//自动拆箱
-
-
-
包装类与字符串类型
-
字符串类型—>包装类
-
通过字符串参数
Integer i3=new Integer("456"); //调用字符串参数
-
使用包装类的 parseXxx(String str)静态方法 (间接的转换)
Integer i4=Integer.parseInt("1234556"); //该方法返回的是int型,后通过自动装箱成包装类 //源码: Integer类中 public static int parseInt(String s) throws NumberFormatException { return parseInt(s,10); }
-
-
包装类—>字符串类型
-
调用包装类 对象的toString(); 方法
String str2= i.toString();//(i是包装类对象) //调用包装类对象的toString方法 //底层代码 : Integer类中 public String toString() { return toString(value); }
-
调用包装 类的toString(形参); 方法
String str3=Integer.toString(i); //调用包装类的toString(形参)方法 //底层代码: Integer类中 public static String toString(int i){ int size = stringSize(i); if (COMPACT_STRINGS) { byte[] buf = new byte[size]; getChars(i, size, buf); return new String(buf, LATIN1); } else { byte[] buf = new byte[size * 2]; StringUTF16.getChars(i, size, buf); return new String(buf, UTF16); } }
-
-
-
字符串类型与基本数据类中
-
基本数据类型—>字符串
-
通过与空字符串连接
String str= 20+"";
-
通过String类中的valueOf() 方法将基本数据类型转换到字符串类型
String str=valueOf(123); // 通过String类中的valueOf() 方法将基本数据类型转换到字符串类型 //源码: String类中 public static String valueOf(int i) { return Integer.toString(i); }
-
-
字符串转—>基本数据类型
-
调用包装 类的parsseXxx()方法
int num4=Integer.parseInt("12345"); //调用包装类的parseXxx(String str)方法 //源码: Integer类中 public static int parseInt(String s) throws NumberFormatException { return parseInt(s,10); }
-
-