Java 语言 设计的时候提倡一种思想,一切皆对象。我们了解到 Java 语言中的 数据类型 有基本数据类型和引用数据类型。
这个和我们提倡的思想矛盾了,所以就有了包装类,将基本数据类型变成引用数据类型。基本类与对应的包装类对应关系如下:
序号 | 基本数据类型 | 包装类 |
---|---|---|
1 | Int | Integer |
2 | char | Character |
3 | short | Short |
4 | long | Long |
5 | float | Float |
6 | double | Double |
7 | boolean | Boolean |
8 | byte | Byte |
将一个基本数据转换为包装类,就叫做装箱,将一个包装类转换成基本数据类型就叫作拆箱。
package com.haicoder.net.wrapper;
public class WrapperDemo {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
int intNum = 100;
Integer integerNum = new Integer(intNum); //装箱
int integer = integerNum.intValue(); //拆箱
float f = 100.2f;
Float floatNum = new Float(f); //装箱
float f1 = floatNum.floatValue(); //拆箱
char c = 'c';
Character charWrapper = new Character(c); //装箱
char charNoWrapper = charWrapper.charValue(); //拆箱
short s = 4;
Short shortWrapper = new Short(s); //装箱
short shortNotWrapper = shortWrapper.shortValue(); //拆箱
long l = 200l;
Long longWrapper = new Long(l); //装箱
long longNoWrapper = longWrapper.longValue(); //拆箱
double d = 100.2d;
Double doubleWrapper = new Double(d); //装箱
double doubleNoWrapper = doubleWrapper.doubleValue(); //拆箱
boolean b = false;
Boolean booleanWrapper = new Boolean(b);
boolean booleanNoWrapper = booleanWrapper.booleanValue();
byte by = 3;
Byte byteWrapper = new Byte(by);
byte byteNoWrapper = byteWrapper.byteValue();
Integer integer1 = 100; //自动装箱
int x = integer1; //自动拆箱
System.out.println("结束");
}
}
运行结果如下:
我们将所有的基本类型的装箱和拆箱方法都列举了出来,其实观察一下,都差不多,而且也将自动拆箱和子装装箱的例子也举了出来。
包装类主要是对于基本数据类型而言的,让基本数据类型也有对应的引用类型,也能够有对象。