java基础——包装类

包装类的定义,自动装箱拆箱

包装类,基本类型,string类之间的相互转化

package wrapper;

import org.junit.Test;

/*
 * 包装类的使用:
 *     1.八种基本数据类型对应八种包装类
 *     2.基本数据类型,包转类,string的转化
 * 
 * 
 * */

public class WrapperTest {

    Integer in = null;
    /*
     * 基本数据类型 -> 包装类:调用包装类的构造器
     * */
    @Test
    public void test1() {
        int num1 = 10;
        Integer in1 = new Integer(num1);
        Integer in2 = new Integer("123");
        System.out.println(in1.toString());
        System.out.println(in2.toString());
    
        System.out.println(in);
        
    }
    
    /*
     * 包装类->基本数据类型:调用包装类的xxxValue()方法
     * */
    @Test
    public void test2() {
        int num1 = 10;
        Integer in1 = new Integer(num1);
        Integer in2 = new Integer("123");
        System.out.println(in1.intValue());
        System.out.println(in2.intValue());
    }
    
    /*
     * JDK 5.0新特性:自动装箱与自动拆箱
     * 
     * */
    public void method(Object obj) {
        System.out.println(obj);
    }
    
    @Test
    public void test3() {
        int num = 10;
        method(num); 
        
        //自动装箱:
        int num1 = 10;
        Integer in1 = num1;
        
        //自动拆箱:
        int num2 = in1;
        
    }
    
    /*
     * 基本数据类型,包装类->Sting类型
     * 
     * */
    @Test
    public void test4() {
        int num1 = 10;
        //方法1
        String str1 = num1 + "";
        System.out.println(str1);
        //方法2
        String str2 = String.valueOf(num1);
        System.out.println(str2);
        //方法3
        Integer in = new Integer(num1);
        String str3 = String.valueOf(in);
        System.out.println(str3);
    }
    
    /*
     * String -> 基本数据类型,包装类
     * 调用包装类的parseXxx()
     * */
    @Test
    public void test5() {
        String str1 = "123";
        int num = Integer.parseInt(str1);
        System.out.println(num);
    }
    
    /*
     * 自动装箱的一些知识
     * Integer 有一个内部静态类IntegerCache,里面有一个数组static final Integer cache[];
     *         cache[i]对应的就是Integer(i)对象,自动装箱时就不用去new了,i的范围是[-128,127]
     * */
    @Test
    public void test6() {
        Integer m = 1;
        Integer n = 1;
        System.out.println(m == n);//true,因为没有new新对象
        
        Integer x = 128;
        Integer y = 128;
        System.out.println(x == y);//false,new了新对象
    }
}

猜你喜欢

转载自www.cnblogs.com/zsben991126/p/12148108.html