包装类
1.1 java中有“一切都是对象”的思想,但是八种基本数据
类型不是对象,所以把八种数据类型包装成类;;
下面是包装类:
基本数据类型--->包装类
int --> Integer
char-->Character
short-->Short
long-->Long
float-->Float
double-->Double
boolean-->Boolean
byte-->Byte
1.2 这八种包装类所继承的父类不全都相同。
public final class Boolean
extends Object
implements Serializable, Comparable<Boolean>
public final class Character
extends Object
implements Serializable, Comparable<Character>
public final class Byte
extends Number
implements Comparable<Byte>
1.3
Integer,Byte,Float,Double,Short,Long都属于Number
类的子类,Number类本身提供了一系列的返回以上六种基本
数据类型的操作。
Character,Boolean属于Object的直接子类。
public abstract class Number
extends Object
implements Serializable
Number类的操作方法:
byte byteValue()
Returns the value of the specified number
as a byte.
abstract double doubleValue()
Returns the value of the specified number
as a double.
abstract float floatValue()
Returns the value of the specified number
as a float.
abstract int intValue()
Returns the value of the specified number
as an int.
abstract long longValue()
Returns the value of the specified number
as a long.
short shortValue()
Returns the value of the specified number
as a short.
1.4
装箱:将基本数据类型变为包装类成为装箱
拆箱:将包装类的类型变为基本数据类型成为拆箱
public class test05
{
public static void main(String args[]){
int x = 30;
Integer i = new Integer(x);//装箱
int temp = i.intValue();//拆箱
}
}
那么在JDK1.5之前对于程序本身来说包装类是不能直接进行
“+,- *,/,++,--”是不可以的,因为是一个类。
但是在JDK1.5之后,对程序的包装类的功能进行了改变,增
加了自动装箱和自动拆箱的功能,而且可以直接使用包装类
进行数字运算。
public class test05
{
public static void main(String args[]){
Integer i = 30;
Float f = 56.3f;
int x = i;
float d = f;
}
}
1.5 在包装类中还存在着一个很大的特点,就是可以将字符
串变为制定的数据类型。
【public static int parseInt(String s)
throws NumberFormatException
】
【public static float parseFloat(String s)
throws NumberFormatException
】
public class test05
{
public static void main(String args[]){
String s1 = "30";
String s2 = "50.3f";
int x = Integer.parseInt(s1);
float f = Float.parseFloat(s2);
System.out.println(x*x);
System.out.println(f*f);
}
}