1 Integer类(应用)
Integer类概述
包装一个对象中的原始类型 int 的值
Integer类构造方法
示例代码
public class IntegerDemo { public static void main(String[] args) { //public Integer(int value):根据 int 值创建 Integer 对象(过时) Integer i1 = new Integer(100); System.out.println(i1); //public Integer(String s):根据 String 值创建 Integer 对象(过时) Integer i2 = new Integer("100"); // Integer i2 = new Integer("abc"); //NumberFormatException System.out.println(i2); System.out.println("--------"); //public static Integer valueOf(int i):返回表示指定的 int 值的 Integer 实 例 Integer i3 = Integer.valueOf(100); System.out.println(i3); //public static Integer valueOf(String s):返回一个保存指定值的Integer对象 String Integer i4 = Integer.valueOf("100"); System.out.println(i4); } }
2 Integer a= 127 与 Integer b = 127 相等吗
对于对象引用类型:==比较的是对象的内存地址。
对于基本数据类型:==比较的是值。
如果整型字面量的值在-128 到 127 之间,那么自动装箱时不会 new 新的 Integer 对象,而
是直接引用常量池中的 Integer 对象,超过范围 a1==b1 的结果是 false
3 int和String类型的相互转换(记忆)
int转换为String
转换方式
方式一:直接在数字后加一个空字符串
方式二:通过String类静态方法valueOf()
示例代码
public class IntegerDemo { public static void main(String[] args) { //int --- String int number = 100; //方式1 String s1 = number + ""; System.out.println(s1); //方式2 //public static String valueOf(int i) String s2 = String.valueOf(number); System.out.println(s2); System.out.println("--------"); } }
4 String转换为int
转换方式
方式一:先将字符串数字转成Integer,再调用valueOf()方法
方式二:通过Integer静态方法parseInt()进行转换
示例代码
public class IntegerDemo { public static void main(String[] args) { //String --- int String s = "100"; //方式1:String --- Integer --- int Integer i = Integer.valueOf(s); //public int intValue() int x = i.intValue(); System.out.println(x); //方式2 //public static int parseInt(String s) int y = Integer.parseInt(s); System.out.println(y); } }
5 包装类用途
1. 作为和基本数据类型对应的类型存在,方便涉及到对象的操作,如Object[]、集合等的操作。
2. 包含每种基本数据类型的相关属性如最大值、最小值等,以及相关的操作方法(这些操作方法的作用是在基本数据类型、包装类对象、字符串之间提供相互之间的转化!)。
包装类的使用
public class Test { /** 测试Integer的用法,其他包装类与Integer类似 */ void testInteger() { // 基本类型转化成Integer对象 Integer int1 = new Integer(10); Integer int2 = Integer.valueOf(20); // 官方推荐这种写法 // Integer对象转化成int int a = int1.intValue(); // 字符串转化成Integer对象 Integer int3 = Integer.parseInt("334"); Integer int4 = new Integer("999"); // Integer对象转化成字符串 String str1 = int3.toString(); // 一些常见int类型相关的常量 System.out.println("int能表示的最大整数:" + Integer.MAX_VALUE); } public static void main(String[] args) { Test test = new Test(); test.testInteger(); } }
运行效果:




