java基本数据类型与字符串之间的转换(基本数据类型、对象封装类、自动装箱、自动拆箱)

来源:互联网 发布:js innerhtml 段落 编辑:程序博客网 时间:2024/04/29 09:10

1  基本数据类型与对象包装类对应关系


基本数据类型对象包装类byteByteshortShortint   Integerlong  LongbooleanBooleanfloat Floatdouble  Doublechar  Character

2  基本数据类型与对象封装类之间的转换


封装类用来解决基本数据类型和String类型之间相互转换的关系而存在

//String → Integer → int

Integer a = new Integer("123");

int b = a;
System.out.println(b - 23);

输出:100
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//String → Integer → double
String a = "123";
Integer b = new Integer(a);

double c = b.doubleValue();//看看doubleValue()的作用,当然还有floatValue,byteValue,longValue()等,作用类似。
System.out.println(c - 23);

输出:100.0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// int Integer String 

int d = 123;
Integer e = new Integer(d);
String f = e.toString();//toString()方法,能将上面的对象包装类转换成String类型,注意:String f = d.toString();//错误,因为d是基本数据类型!
System.out.println(f - 23);

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

此时不能编译,因为 f 已经是字符串,不能进行四则运算。

2  自动拆箱和自动装箱


基本数据类型的自动装箱(autoboxing)、拆箱(unboxing)是自JDK5.0开始提供的功能。


自动装箱:


我们这样创建一个类的对象:

Student a = new Student();


当我们创建一个Integer对象时,却可以这样:

Integer b = 123;//注意:不是 int b = 123;


实际上,系统自己已经执行了:Integer b = new Integer(123); 

这就是自动装箱功能。



自动拆箱:

也就是将对象中的基本数据从对象中自动取出。如下可实现自动拆箱:

Integer b = 123;//装箱

int b = 123;//拆箱


0 0
原创粉丝点击