Java面向对象编程

Wrapper

  • Java提供了8种基本数据类型的包装类,使得基本数据类型变量具有了类的特征
  • 基本数据类型、包装类和String的相互转换;
    总结下来parseXxx和String的xxxValue静态方法就可以最简单高效的实现三者之间的转换
    Java面向对象编程_第1张图片
package com.xyl.contacts;

import org.junit.Test;
/**
 * 
 * @Descryption 包装测试类
 * @author xyl Email:[email protected]
 * @version v1.0
 * @date 2021年3月6日下午10:27:23
 *
 */
public class WrapperTest {
     
	@Test
	/**
	 * 
	 * @Descryption 基本数据类型转包装类
	 * @author xyl 
	 * @date 2021年3月6日下午10:28:13
	 */
	public void test1() {
     
		int i=56;
		Integer I1=new Integer(i);
		Integer I2=new Integer("89");//写"89"就相当于写89
		System.out.println(I1.toString());//56
		System.out.println(I2.toString());//89
		
		Float F1=new Float(12.3f);
		Float F2=new Float("45.6");//45.6
		System.out.println(F1);//12.3
		System.out.println(F2);//45.6
		
		Boolean B1=new Boolean(true);
		Boolean B2=new Boolean("TRue");//构造方法进行了改进
		/*
		 * public Boolean(String s) {
        this(parseBoolean(s));
    }
    		
    		public static boolean parseBoolean(String s) {
        return ((s != null) && s.equalsIgnoreCase("true"));
    }
		 */
		Boolean B3=new Boolean("true123");
		System.out.println(B1);//true
		System.out.println(B2);//true
		System.out.println(B3);//false
		
		Order order=new Order();
		System.out.println(order.b);//false
		System.out.println(order.B);//null,对象的默认值是null
	}
	
	@Test
	/**
	 * 
	 * @Descryption 包装类转基本数据类型
	 * @author xyl 
	 * @date 2021年3月6日下午10:36:00
	 */
	public void test2() {
     
		Integer I3=new Integer(45);
		int i3=I3.intValue();
		System.out.println(i3);//45
		
		Float F3=new Float(87.6f);
		float f3=F3.floatValue();
		System.out.println(f3);//87.6
	}
	
	@Test
	/**
	 * 
	 * @Descryption JDK5.0后新特性:自动装箱和拆箱
	 * @author xyl 
	 * @date 2021年3月6日下午10:44:53
	 */
	public void test3() {
     
		int i1=1;
		method(i1);//自动装箱
		Integer I=i1;//自动装箱
		int i2=I;//自动拆箱
		//System.out.println(i2.);此时i2是基本数据类型,不可以调用方法
	}
	public void method(Object O) {
     
		
	}
	
	@Test
	/**
	 * 
	 * @Descryption 基本数据类型、包装类-->String
	 * @author xyl 
	 * @date 2021年3月6日下午11:14:08
	 */
	public void test4() {
     
		int i=1;
		String s1=1+"";//方式1:连接运算
		System.out.println(s1);//1
		
		Integer II=i;
		String ss=i+"";//包装类自动拆箱再连接运算
		System.out.println(ss);//1
		
		String s2=String.valueOf(12.3f);//String类的valueOf静态方法
		System.out.println(s2);//12.3
	}
	@Test
	/**
	 * 
	 * @Descryption String-->基本数据类型、包装类
	 * @author xyl 
	 * @date 2021年3月6日下午11:27:52
	 */
	public void test5() {
     
		//强制类型转换需要都是基本数据类型,向上转型、向下转型必须有父子继承关系的引用数据类型,基本数据类型不能和引用数据类型互转
		String str1="123";
		//String str="123abc";
		int I=Integer.parseInt(str1);
		//int I2=Integer.parseInt(str);NumberFormatException,123abc不是数值
		System.out.println(I+1);//124
		
		String str2="truE";
		boolean b=Boolean.parseBoolean(str2);
		System.out.println(b);//true
		
		String str3="truE123";
		boolean b2=Boolean.parseBoolean(str3);
		System.out.println(b2);//false
	}
}

class Order{
     
	boolean b;
	Boolean B;
}

你可能感兴趣的:(JavaSE,java)