基本类型、包装类与String类间的转换

包装类

java提供了8种基本数据类型对应的包装类,使得基本数据类型的变量具有类的特征

在这里插入图片描述

基本类型、包装类与String类间的转换

掌握的:基本数据类型、包装类、String三者之间的相互转换

在这里插入图片描述

基本数据类型 —>包装类:调用包装类的构造器

	@Test
	public void test1() {	
		int num1 = 10;
//		System.out.println(num1.toString());
		Integer in1 = new Integer(num1);
		System.out.println(in1.toString());		
		Integer in2 = new Integer("123");
		System.out.println(in2.toString());
		
		Float f1 = new Float(12.3f);
		Float f2 = new Float("12.3");
		System.out.println(f1);
		System.out.println(f2);
		
		//报异常
//		Integer in3 = new Integer("123abc");
//		System.out.println(in3.toString());
		
		Boolean b1 = new Boolean(true);
		//boolean类型的比较特殊return ((s != null) && s.equalsIgnoreCase("true"));
		Boolean b2 = new Boolean("TrUe");
		Boolean b3 = new Boolean("true123");
		System.out.println(b2);//true
		System.out.println(b3);//false
	}

包装类—>基本数据类型:调用包装类Xxx的xxxValue()

	@Test
	public void test2(){
		Integer in1 = new Integer(12);		
		int i1 = in1.intValue();
		System.out.println(i1 + 1);
		
		Float f1 = new Float(12.3);//形参double		
//		public Float(double value) {
//        	this.value = (float)value;
//    	}
		float f2 = f1.floatValue();
		System.out.println(f2 + 1);
	}

JDK 5.0 新特性:自动装箱 与自动拆箱

	@Test
	public void test3(){
//		int num1 = 10;
//		//基本数据类型-->包装类的对象
//		method(num1);
		
		//自动装箱:基本数据类型 --->包装类
		int num2 = 10;
		Integer in1 = num2;//自动装箱
		boolean b1 = true;
		Boolean b2 = b1;//自动装箱
		
		//自动拆箱:包装类--->基本数据类型
		//打印对象最后实际上还是调用了toString(),只不过包装类中重写了toString()方法
		System.out.println(in1.toString());//System.out.println(in1);
		int num3 = in1;//自动拆箱
	}
	
	public void method(Object obj){
		System.out.println(obj);
	}
	@Test
	public void test6() {
		Object obj = 3;//自动装箱+多态
		int i = (int) obj;//强转+自动拆箱
		System.out.println(i);//3
	}

基本数据类型、包装类—>String类型:调用String重载的valueOf(Xxx xxx)

	@Test
	public void test4(){	
		int num1 = 10;
		//方式1:连接运算
		String str1 = num1 + "";
		//方式2:调用String的valueOf(Xxx xxx)
		float f1 = 12.3f;
		String str2 = String.valueOf(f1);//"12.3"	
		Double d1 = new Double(12.4);
		//String.valueOf(Object obj)
		//return (obj == null) ? "null" : obj.toString();
		String str3 = String.valueOf(d1);
		System.out.println(str2);
		System.out.println(str3);//"12.4"
	}

String类型 —>基本数据类型、包装类:调用包装类的parseXxx(String s)

	@Test
	public void test5(){
		String str1 = "123";
		//错误的情况:
//		int num1 = (int)str1;
//		Integer in1 = (Integer)str1;//强转的前提必须有子父类关系
		//可能会报NumberFormatException
		int num2 = Integer.parseInt(str1);
		System.out.println(num2 + 1);
		
		String str2 = "true1";
		boolean b1 = Boolean.parseBoolean(str2);
		System.out.println(b1);//falses
	}
发布了25 篇原创文章 · 获赞 0 · 访问量 626

猜你喜欢

转载自blog.csdn.net/CGB1804Great/article/details/104072664