Java中的8个基本类型都对应一个包装类 byte → Byte short → Short int → Integer long → Long float → Float double → Double char → Character boolean→ Boolean 每个包装类中都有一个静态的方法来将java的基本数据类型转换为包装类,这个静态方法接受一个对应的基本类型参数然后返回一个包装类的引用: Java 1.5版本之后 增加了自动装箱、拆箱机制,提供基本数据类型和包装类型的相互转换操作。 自动装箱即自动将基本数据类型转换成包装类型: public class TestUtil { public static void main(String[] args){ //JDK1.5之前 不可以自动装箱 Integer i1 = new Integer(100); Integer i2 = Integer.valueOf(100); //1.5之后 可以自动装箱 Integer i3 = 100; 自动拆箱即自动将包装类型转换成基本数据类型,与自动装箱相反: public class TestUtil { public static void main(String[] args){ //JDK1.5之前 不可以自动装箱 Integer i1 = new Integer(100); Integer i2 = Integer.valueOf(100); //1.5之后 可以自动装箱 Integer i3 = 100; //自动拆箱 int i4 = i1; //自动拆箱的原理 调用intValue int i5 = i1.intValue(); System.out.println(i4); System.out.println(i5); } } 输出结果 100 100 public class TestUtil { public static void main(String[] args){ //将数字字符串转换为int类型数字 //将String直接转换为int类型 int value1 = Integer.parseInt("123"); //先将String构成一个Integer对象,然后拆分 int value2 = new Integer("123"); System.out.println(value1); System.out.println(value2); } } 输出结果: 123 123 笔试题 public class TestUtil { public static void main(String[] args){ //将数字字符串转换为int类型数字 Integer i1 = 10;//10自动包装成Integer对象 不是常量区的10,而是存放在静态元素区的10 Integer i2 = 10;//与i1同时指向静态元素区的10 Integer i3 = new Integer(10);// 新new 的一个对象 10 Integer i4 = new Integer(10);//再new一个 System.out.println(i1 == i2);//== 比较变量里的内容(地址) System.out.println(i1 == i3); System.out.println(i3 == i4); System.out.println(i1.equals(i2));//重写了 比值, 不是Object里的equals , System.out.println(i1.equals(i3)); System.out.println(i2.equals(i4)); } } 输出结果: true false false true true true 1.==与equals()区别 来源:https://www./content-1-316151.html |
|