/**
*
* @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();
}
}
|
|