一、概述
Integer类是基本类型int所对应的包装类,该类提供了多个方法,能在int类型和String类型之间相互转换,还提供了处理int类型时非常有用的其他一些常量和方法
二、构造方法
- public Integer(int value):把int类型的数据封装成其对应对的Integer对象
- public Integer(String s):把字符串类型的整数封装成其对应的Integer对象
- 注意:这里传入的必须是纯数字类型的字符串
public class Test{
public static void main(String[] args) {
Integer i1 = 123;
System.out.println(i1);
System.out.println(new Integer(123));
Integer i2 = new Integer("123");
System.out.println(i2);
}
}
三、int类型和String类型的相互转换
-
int类型 -> String类型
-
方式一:直接在后边拼接""即可
public class Test{ public static void main(String[] args) { Integer i1 = 123; String s1 = i1+""; } }
-
方式二:通过String#valueOf()方法
public class Test{ public static void main(String[] args) { String s1 = String.valueOf(10); } }
-
-
String类型->int类型
-
方式一:通过String->Integer->int思路来实现
public class Test{ public static void main(String[] args) { // 1.先把String类型的对象转换成Integer类型的对象 String s1 = "10"; Integer i1 = new Integer(s1); // 2.把Integer类型的对象转成int类型 int num = i1.intValue(); System.out.println(num); } }
-
方式二:通过Integer#parseInt()方法来实现
public class Test{ public static void main(String[] args) { String s1 = "100"; int num = Integer.parseInt(s1); System.out.println(num); } }
-
四、自动拆装箱
-
解释
- 把基本类型的数据封装成其对应的包装类型,则才称之为自动装箱
- 把包装类型的对象拆解长城其对应的基本类型,则称之为自动拆箱
-
代码
public class Test { public static void main(String[] args) { // 1.自动装箱 Integer i = 100; // 2.自动拆箱 i = i + 100; } }