在实际开发过程中,我们经常会遇到需要使用对象,而不是内置数据类型的情形。为了解决这个问题,Java语言为每一个内置数据类型提供了对应的包装类。
所有的包装类(Integer、Long、Byte、Double、Float、Short)都是抽象类Number的子类。
这种由编译器特别支持的包装称为装箱,所以当内置数据类型被当作对象使用的时候,编译器会把内置类型装箱为包装类。相似的,编译器也可以把一个对象拆箱为内置类型。Number类属于java.lang包。
下面是一个装箱与拆箱的例子:
public class Test{
public static void main(String args[]){
Integer x = 5; // boxes int to an Integer object
x = x + 10; // unboxes the Integer to a int
System.out.println(x);
}
}
运行结果如下:
15
当x被赋为整型值时,由于x是一个对象,所以编译器要对x进行装箱。然后,为了使x能进行加运算,所以要对x进行拆箱。
以下是Number类的源码, 除了byteValue()和shortValue之外,其他都是抽象方法
public abstract class Number implements java.io.Serializable {
/**
* Returns the value of the specified number as an {@code int},
* which may involve rounding or truncation.
*/
public abstract int intValue();
/**
* Returns the value of the specified number as a {@code long},
* which may involve rounding or truncation.
*/
public abstract long longValue();
/**
* Returns the value of the specified number as a {@code float},
* which may involve rounding.
*/
public abstract float floatValue();
/**
* Returns the value of the specified number as a {@code double},
* which may involve rounding.
*/
public abstract double doubleValue();
/**
* Returns the value of the specified number as a {@code byte},
* which may involve rounding or truncation.
*/
public byte byteValue() {
return (byte)intValue();
}
/**
* Returns the value of the specified number as a {@code short},
* which may involve rounding or truncation.
*/
public short shortValue() {
return (short)intValue();
}
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -8742448824652078965L;
}