基本类型包装类概述
为什么会有基本类型包装类?
为了对基本数据类型进行更多的操作,更方便的操作,java就针对每一种基本数据类型提供了对应的类类型。
常用的操作之一:用于基本数据类型与字符串之间的转换。
基本类型和包装类的对应:
基本类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
char | Character |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
Integer类的概述和构造方法
Integer 类在对象中包装了一个基本类型 int 的值。Integer 类型的对象包含一个 int 类型的字段。
该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,还提供了处理 int 类型时非常有用的其他一些常量和方法。
构造方法:
Integer类重载构造方法,但是没有空参构造。
public Integer(int value); 对于该构造方法可以传递一个int类型的值即可。
public Integer(String s); 对于该构造方法,需要传递一个字面值看起来是数字的字符串。
String和int类型的相互转换
int到String:
- 和""进行拼接
public class Demo3 {
public static void main(String[] args) {
int a=100;
String s=a+"";
System.out.println(s);
}
}
- public static String valueOf(int i)
public class Demo3 {
public static void main(String[] args) {
int a = 100;
String s = String.valueOf(a);
System.out.println(s);
}
}
- int到Integer再到String
public class Demo3 {
public static void main(String[] args) {
int a = 120;
Integer integer = new Integer(a);
String s = integer.toString();
System.out.println(s);
}
}
- public static String toString(int i)
public class Demo3 {
public static void main(String[] args) {
int a = 120;
Integer integer = new Integer(a);
String s = integer.toString();
System.out.println(s);
}
}
String到int:
- String到Integer再使用intValue();
public class Demo3 {
public static void main(String[] args) {
String s="1903";
Integer integer = new Integer(s);
int num=integer.intValue();
System.out.println(num);
}
}
- public static int parseInt(String s)
public class Demo3 {
public static void main(String[] args) {
String s="1985";
int num = Integer.parseInt(s);
System.out.println(num);
}
}
自动装箱和拆箱
JDK5有了新特性:
- 自动装箱:把基本类型转换为包装类类型
public class Demo3 {
public static void main(String[] args) {
Integer integer=100;
System.out.println(integer);
}
}
- 自动拆箱:把包装类类型转换为基本类型
public class Demo3 {
public static void main(String[] args) {
int num=new Integer(185);
System.out.println(num);
}
}
但是,在使用时候,Integer x = null; 代码就会出现NullPointerException。所以最好先判断是否为null,然后再使用。