包装类的使用

文章目录

一、包装类是什么?

包装类实现了基本数据类型拥有类的特点,可以调用类中的方法

二、使用步骤

1.掌握基本数据类型相应的包装类

2.完成String类型、基本数据类型、包装类的相互转换

代码如下:

public class WrapperTest
{
	//String类型-->基本数据类型、包装类:调用包装类的parseXxx(String s)
	@Test
	public void Test5()
	{
		String str1="123";
		int num=Integer.parseInt(str1);
		System.out.println(num);//123
		
		String str2="true";
		boolean b1=Boolean.parseBoolean(str2);
		System.out.println(b1);//true
		
		String str3="true1";
		boolean b2=Boolean.parseBoolean(str3);
		System.out.println(b2);//false
		
		String str4="12";
	   Integer in1=Integer.parseInt(str4);
	   System.out.println(in1.toString());//12
	}
	
	//基本数据类型、包装类-->String类型:调用String重载的valueOf(Xxx xxx)
	@Test
	public void Test4()
	{
		//方法1:连接运算
		int num1=10;
		String str1=num1+" ";
	   System.out.println(str1);//10
		
		//方法2:调用String重载的valueOf(Xxx xxx)
	   float f1=12.3f;
	   String str2=String.valueOf(f1);
	   System.out.println(str2);//12.3
	   
	   Double d1 =new Double(12.4);//包装类
	   String str3=String.valueOf(d1);
	   System.out.println(str3);//12.4
	}
	/*
	 * JDK5.0后的新特性:自动装箱与自动拆箱
	 */
	@Test
	public void test3()
	{
	/*
	  int num1=10;
	  //基本数据类型-->包装类的对象
	   method(num1);
	*/
		
		//自动装箱:基本数据类型-->包装类
		int num2=12;
		Integer in1=num2;
		System.out.println(in1.toString());
		
		boolean b1=true;
		Boolean b2=b1;
		System.out.println(b2.toString());
		
		//自动拆箱:包装类-->基本数据类型
		boolean number=b2;
		System.out.println(number);
		
		
	}
	public void method(Object obj)
	{
		System.out.println(obj);
	}
	
	//包装类-->基本数据类型,调用包装类Xxx的XxxValue()
	@Test
	public void Test1()
	{
		Integer in1=new Integer(12);
		int i1=in1.intValue();
		System.out.println(i1+1);
		
		Float float1=new Float(12.3);
		float f1=float1;
		System.out.println(f1);
		
	}
      @Test
      public void test2()
     {
	
	//基本数据类型-->包装类,调用包装类的构造器
	int num1=10;
	Integer in1=new Integer(num1);
	System.out.println(in1.toString());//10   包装类重写了toString方法
	
	Integer in2=new Integer("123");
	System.out.println(in2.toString());//123
	
	//异常
//	Integer in3=new Integer("123abc"); //纯粹的
//	System.out.println(in3.toString());
	
	Boolean b1=new Boolean(true);
	System.out.println(b1.toString());//true
	
	Boolean b2=new Boolean("True");
	System.out.println(b2.toString());//true
	
	Boolean b3=new Boolean("true123");
	System.out.println(b3.toString());//false   经过优化
	
	Orde order=new Orde();
    System.out.println(order.isMale);//false
	System.out.println(order.isFemale);//null
	  }
}
class Orde
{
	boolean isMale;
	Boolean isFemale;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值