java常用类-----包装类及自动装箱和拆箱

一、包装类基本使用
package cn.zxg.PackgeUse;

/**
* 测试包装类
*/

public class TestWrappedClass {
public static void main(String[] args) {
//基本数据类型转换成包装类
Integer a=new Integer(3);
Integer b=Integer.valueOf(3);
//把包装类转换成基本数据类型
int c=b.intValue();
double d=b.doubleValue();
//把字符串转换成包装类对象
Integer e=new Integer("9999");
Integer f=Integer.parseInt("99988");
//包装类转换成字符串
String str=f.toString();
System.out.println("int类型最大整数"+Integer.MAX_VALUE);
}
}

二、包装类自动拆箱和装箱
package cn.zxg.PackgeUse;

/**
* 测试自动装箱和拆箱
*/

public class TestAutoBox {
public static void main(String[] args) {
Integer a=234;//自动装箱。Integer a=Integer.valueOf(234)

int b=a;//自动拆箱,编译器自动修改成:int b=a.intValue()

Integer c=null;
if(c!=null){
int d=c;
}

//缓存[-128,127]之间的数字,实际就是系统初始的时候,创建了[-128,127]之间的一个缓存数组
//当我们调用valueOf()的时候,首先检查是否在[-128,127]之间,如果在这个范围之间从缓存数组中拿。
//如果不在这个范围,则创建新Integer对象

Integer in1=-128;
Integer in2=-128;
System.out.println(in1==in2);//返回true
System.out.println(in1.equals(in2));//返回true

System.out.println("***************");
Integer in3=-1288;
Integer in4=-1288;
System.out.println(in3==in4);//返回false
System.out.println(in3.equals(in4));//返回true


}
}

猜你喜欢

转载自www.cnblogs.com/zzzao/p/10902724.html