- 1.基本数据类型有什么?
- 2.为什么有需要包装类
- 3.包装类的用途
- 4.包装类常用属性方法
- 5.装箱和拆箱(Auto-boxing/unboxing)
byte 、short、int、long、double、float、char、boolean、
2.为什么有需要包装类Java语言是一个面向对象的语言,但是Java中的基本数据类型却是不面向对象的,这在实际使用时存在很多的不便(例如做条件判断的时候),为了解决这个不足,在设 计类时为每个基本数据类型设计了一个对应的类进行代表,这样八个和 基本数据类型对应的类统称为包装类.
包装类(如:Integer,Double等)这些类封装了一个相应的基本数据 类型数值,并为其提供了一系列操作方法。
对于包装类来说,这些类的用途主要包含两种:
- 作为和基本数据类型对应的类类型存在。
- 包含每种基本数据类型的相关属性如最大值、最小值等,以及相关的操 作方法。
以下方法以java.lang.Integer为例
public static final int MAX_VALUE 最大的int型数(231-1)
public static final int MIN_VALUE 最小的int型数(-231)
构造方法
Integer(int a);
Integer(String a);
比较方法
static int compareTo(Integer a);
boolean equals(Object);
int max(int a,int b); i
nt min(int a,int b);
转换方法
static toBinaryString(int i);
static String toHexString(int i);
static String toOctalString(int i);
int intValue();
static int parseInt(String s);
String toString();
static String toString(int i) ;
static Integer valueOf(int i) ;
static Integer valueOf(String s);
//包装类常用属性方法
//以java.lang.Integer为例
public static void main(String[] args) {
//使用Integer包装一个整数,可以使用Integer类提供的方法
Integer m = new Integer(10);//Integer的构造方法
System.out.println(Integer.MAX_VALUE); //Integer的最大值
System.out.println(Integer.MIN_VALUE); //Integer的最小值
System.out.println(Integer.SIZE);//Integer的位数
System.out.println(Integer.BYTES);//Integer的字节数
Integer n = new Integer("12"); //Integer的构造方法,会自动转换为数值类型;
System.out.println(n.equals(m));//判断n和m是否相等
System.out.println(n.compareTo(m));//比较n与m的大小,n>m 输出 1 n
5.装箱和拆箱(Auto-boxing/unboxing)
装箱
- 自动将基本数据类型转换为包装器类型
- 装箱的时候自动调用的是Integer的valueOf(int)方法
拆箱
- 自动将包装器类型转换为基本数据类型
- 拆箱的时候自动调用的是Integer的intValue方法
public class IntegerDemo {
public static void main(String[] args) {
int a=12;
//装箱
Integer b=Integer.valueOf(a);
//拆箱
int c= b.intValue();
int n=10;
//装箱
Integer m=n;
//拆箱
int y=m;
Integer a=Integer.valueOf(127); //同一个地址在 -127-128之间 都为true
Integer b=127;
System.out.println(a==b); //true
Integer c=new Integer(128); //创建了两个新的地址 不管数值为多少都为false
Integer d=new Integer(128);
System.out.println(c==d); //false
}
}



