/* * 若尘 */package packing;
/** * 演示Integer类的使用 * @author ruochen * @version 1.0 */public class TestInteger { public static void main(String[] args) { // 使用Integer类中的构造方法来构造对象,该类没有无参构造方法 Integer it = new Integer(123); // 自动调用toString()方法, 得到字符串类型的十进制整数 System.out.println(it); Integer it2 = new Integer("234"); System.out.println(it2); System.out.println("----------------------"); // 实现int类型和Integer类型之间的相互转换 Integer it3 = Integer.valueOf(222); System.out.println(it3); // String 类型 int res = it3.intValue(); System.out.println(res); // int 类型
System.out.println("----------------------"); // 实现String类型向int类型的转换 int res2 = Integer.parseInt("33333"); System.out.println(res2); // java.lang.NumberFormatException // 要求字符串中每个字符都是十进制整数的字符,否则产生数字格式异常 // int res3 = Integer.parseInt("1234a"); // System.out.println(res3); System.out.println("----------------------"); // 自动装箱和自动拆箱的机制 Integer it4 = 100; // int -> Integer 发生自动装箱,自动调用ValueOf() res = it4; // Integer -> int 发生自动拆箱,自动调用intValue() System.out.println("----------------------"); Integer it5 = 128; Integer it6 = 128; Integer it7 = new Integer(128); Integer it8 = new Integer(128); System.out.println(it5.equals(it6)); // true 比较内容 System.out.println(it5 == it6); // false 比较地址 System.out.println(it7.equals(it8)); // true 比较内容 System.out.println(it7 == it8); // false 比较地址 System.out.println("----------------------"); // 源码993行 // 耗时 // -128~127 提前装箱完毕 // 此处127已经提前装箱,不需要重新创建对象,两个指向同一个对象 // 上面128不在范围内,需要创建对象 Integer it9 = 127; Integer it10 = 127; // 下面是自己手动new的两个对象,地址不同 Integer it11 = new Integer(128); Integer it12 = new Integer(128); System.out.println(it9.equals(it10)); // true 比较内容 System.out.println(it9 == it10); // false 比较地址 System.out.println(it11.equals(it12)); // true 比较内容 System.out.println(it11 == it12); // false 比较地址 }}
评论