一、八大数据类型所对应的包装类
二、手动装箱与手动拆箱
在JDK1.5之前,只有手动装箱和手动拆箱
1.手动装箱
有两种方式
public class Wrapper {
public static void main(String[] args) {
int n1=100;
//方式1
Integer i = new Integer(n1);
//方式2
Integer i1 = Integer.valueOf(n1);
}
}
2.手动拆箱
public class Wrapper {
public static void main(String[] args) {
int n1 = 100;
//方式1
Integer i = new Integer(n1);
//方式2
Integer i1 = Integer.valueOf(n1);
//手动拆箱
int i2 = i1.intValue();
}
}
三、自动装箱与自动拆箱
在JDK1.5及1.5以后,就有自动装箱和自动拆箱
由于几个包装类方法都基本一样,所以本文选用int的包装类Integer作为展示:
1.自动装箱:将int转为Integer
public static void main(String[] args) {
// 自动装箱
Integer a = 45;
}
底层还是调用了 Integer.valueOf( )方法
2.自动拆箱:将Integer转为int
public static void main(String[] args) {
// 自动装箱
Integer a = 45;
// 自动拆箱
int b = a;
}
底层还是调用***.intValue( )方法
四、将包装类转为基本数据类型(手动拆箱)
***Value()方法
public static void main(String[] args) {
Integer a = 45;
int a1 = a.intValue();
Boolean b=true;
boolean b1 = b.booleanValue();
System.out.println(a1);
System.out.println(b1);
}
五、将基本数据类型转为字符串
//将包装类转换为String类型
public class Wrapper {
public static void main(String[] args) {
Integer n1 = 100;
//方式一
String string1 = n1 + "";
//方式二
String string2 = n1.toString();
//方法三
String string3 = String.valueOf(n1);
}
}
六、将字符串类型转为基本数据类型
包装类.parse***()方法
方式一:
public static void main(String[] args) {
int i = Integer.parseInt("45454");
System.out.println(i);
}
方式二:
public class Wrapper {
public static void main(String[] args) {
String str = "123456";
int i = new Integer(str);
}
}
七、Interger和Character类的常用方法
*附加知识
很有意思的是,今天学到个新知识,要把三元运算符看作一个整体;
例如:
public class Wrapper {
public static void main(String[] args) {
Object obj=true?new Integer(1):new Double(2.0);
System.out.println(obj);
}
}
它的输出结果是1.0,而不是1;因为要看成整体,后面是2.0,Double类型,精度需要提升;
对于像这样的问题:
到底输出true还是false呢?
我们可以看见,如果是在-128~127之间,是从数组直接返回,不创建新的对象,这个数组是在类加载时候就自动创建好的。
所以,上面的题目,答案是true