A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 无云 中级黑马   /  2015-8-30 01:23  /  380 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/**
*
* @author
* @function
* 自动装箱是把基本数据类型封装成类对象,拆箱是指把类对象拆成基本数据类型
*/
public class TextAutoboxAndUnbox {
    //测试对象类型是否相等,大家考虑一下如果在范围(-128-127)之间的数呢?
    public static void testEqual(){
        Integer i1 = 256;
        Integer i2 = 256;
        if(i1 == i2)
            System.out.println("相等");
        else
            System.out.println("不相等");
    }
    //自动拆箱和装箱
    public static void autoBoxToInt(){
        int i = 0;
        Integer integer = i;
        int j = integer;
        Integer counter =1;                     //装箱
        int counter2 = counter;                 //拆箱
        while(counter < 3){
            System.out.println("计数:" + counter++);  //对象类型的数能自动增加
        }
    }
    //字符类型的自动拆箱和装箱
    public static void autoBoxTochar(){
        char ch = 'A';
        Character character = 'B';              //装箱
        System.out.println("ch = " + ch + "; character = " + character);
        if(ch != character){
            ch = character;
            System.out.println("ch = " + ch + ";character = " + character);
        }
    }
    //布尔类型的自动拆箱与装箱
    public static void autoBoxToBoolean(){
        boolean b = false;
        Boolean bool = true;                    //装箱
        if(bool){                               //拆箱
            System.out.println("bool : " + true);
        }
        if(b || bool){
            b = bool;
            System.out.println("bool : " + bool + "; b :" + b);
        }
    }
    //测试自动装箱与拆箱在循环中的影响
    public static void testWhile(){
        Boolean bool = true;
        Integer number = 0;
        int captcity = 3;
        while(number < captcity){
            if (bool) {
                System.out.println("Welcome you " + number);
                number++;
            }
            else{
                number--;
            }
        }
    }
    public static void main(String[] args) {
        System.out.println("1.测试对象型是否相等");
        testEqual();
        System.out.println("2.测试整数类型自动装箱与拆箱");
        autoBoxToInt();
        System.out.println("3.测试字符类型自动装箱与拆箱");
        autoBoxTochar();
        System.out.println("4.测试布尔类型自动装箱与拆箱");
        autoBoxToBoolean();
        System.out.println("5.测试自动装箱与拆箱在循环中的影响");
        testWhile();
    }
}

4 个回复

倒序浏览
厉害啊!
回复 使用道具 举报
jdk1.5新特性
回复 使用道具 举报
赞一个!!!
回复 使用道具 举报
顶顶顶顶
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马