【Java开源代码栏目提醒】:网学会员在Java开源代码频道为大家收集整理了TextAutoboxAndUnbox.java提供大家参考,希望对大家有所帮助!
package com.zf.s11; //创建一个包
public class TextAutoboxAndUnbox { //操作自动装箱与拆箱的类
private static void testEqual() { //测试对象型是否相等
Integer i1 = 256;
Integer i2 = 256;
if (i1 == i2)
System.out.println("相等!");
else
System.out.println("不相等!");
}
private static void autoBoxToInt() { // 自动装箱拆箱
int i = 0;
Integer integer = i; //基本类型值,可以赋值给Integer型变量
int j = integer; // 原始类型的数,也能赋值基本类型
Integer counter = 1; // 装箱
int counter2 = counter; // 拆箱
while (counter < 3) {
System.out.println("计数 " + counter++); // 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);
}
}
private static void testWhile() { //测试自动装箱与拆箱在循环中的影响
Boolean bool = true;
Integer number = 0;
int captcity = 3;
while (number < captcity) {
if (bool) {
System.out.println("Welcome you "+number);
number++; //等价于number=number+1
}
else
number--; //等价于number=number-1
}
}
public static void main(String []args){ //java程序主入口处
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(); //调用方法
}
}