包装类

  作用:使用基本数据类型声明的变量,如: int num = 10; 这里的num只是一个变量,而不是对象; 在某些必须操作对象的场合,这样的变量就不能使用了;

     需要用包装类将基本数据类型当作对象进行操作; 在java.lang包中,对于每个基本数据类型都有一个相应的包装类

                                        包装类对应表

基本数据类型

包装类

byte(字节型)

Byte

boolean(布尔型)

Boolean

short(短整型)

Short

char(字符型)

Character

int(整型)

Integer

long(长整型)

Long

float(浮点型)

Float

double(双精度浮点型)

Double

  方法每个包装类都有一个静态的valueOf方法,用于将字符串转换成相应包装类的对象

     除了Boolean类和Character类以外,其它的包装类都有静态的parse X方法(X指代具体的数据类型),用于将字符串转换成相对应的基本数据类型值

  拆装箱:JDK5.0以后提供了自动封解箱的操作

     例如:int x = 1;   Integer y = x;

        y++; //装箱  int z = y; //拆箱

      简单理解:基本数据类型和对应的包装类型会自动转换

代码示例

 

 1 package summary2;
 2 
 3 //包装类
 4 public class PackClass
 5 {
 6     public static void main(String[] args)
 7     {
 8         String str1 = "110";
 9         //如果转换失败,将会引发NumberFormatException异常
10         Byte objByte = Byte.valueOf(str1);
11         Short objShort = Short.valueOf(str1);
12         Integer objInt = Integer.valueOf(str1);
13         Long objLong = Long.valueOf(str1);
14         System.out.println(objByte);
15         System.out.println(objShort);
16         System.out.println(objInt);
17         System.out.println(objLong);
18         
19         String str2 = "120";
20         //分别调用各个包装类的paseXxx方法对字符串进行转换,如果转换失败,将报异常
21         int i = Integer.parseInt(str2);
22         short s = Short.parseShort(str2);
23         byte b = Byte.parseByte(str2);
24         long l = Long.parseLong(str2);
25         float f = Float.parseFloat(str2);
26         double d = Double.parseDouble(str2);
27         System.out.println(i);
28         System.out.println(s);
29         System.out.println(b);
30         System.out.println(l);
31         System.out.println(f);
32         System.out.println(d);
33         
34         int x = 1;
35         Integer y = x;
36         y++;        //装箱
37         int z = y;    //拆箱
38         System.out.println(x);
39         System.out.println(z);
40     }
41 }