将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据
基本数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
在JDK帮助文档中可以发现Integer类里面有两个常量
//public static fina int MIN_VALUE
//public static fina int MAX_VALUE
这两个代表的是int的取值范围
因为是static修饰的,而且Integer是java.lang包下的我们不用导包,所以我们可以直接通过类名访问。
//public static fina int MIN_VALUE
System.out.println(Integer.MIN_VALUE);
//public static fina int MAX_VALUE
System.out.println(Integer.MAX_VALUE);
在JDK帮助文档中可以发现Integer类里面有两个方法
public static Integer valueOf (int i): 返回指定的int值的 Integer 实例
public static Integer valueOf (String s): 返回一个保存指定值的 Integer 对象 String
代码示例:
System.out.println("返回的String类型:"+Integer.valueOf(100));
System.out.println("返回的Integer类型:"+Integer.valueOf("100"));
输出结果:
基本类型包装类的最常见的操作就是:用于基本类型和字符串之间的相互转换
int -----> String
//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);
String -----> int
//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);