包装类
为了对基本数据类型进行更多的操作,更方便的操作,java就针对每一种基本数据类型提供了对应的数值包装类类型。
基本类型和包装类的对应
基本类型 | 对应的包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
因为所有的包装类的用法都很相似,所以以Integer类来举例说明。
常量
每一个数值包装类都有常量MAX_VALUE和MIN_VALUE。MAX_VALUE代表对应的基本数据类型的最大值,MIN_VALUE代表的是对应的基本数据的最小值。对Float和Double类而言,MIN_VALUE表示该类型的最小正值。
例如,可以使用MAX_VALUE和MIN_VALUE来判断一个数是否是在int范围内。
public class InterDemo {
public static void main(String[] args) {
//获取int的最大值和最小值
int minValue = Integer.MIN_VALUE;
int maxValue = Integer.MAX_VALUE;
Scanner input = new Scanner(System.in);
int n = input.nextInt();
if(n>=minValue&&n<=maxValue){
System.out.println("是一个int范围内的数");
}
}
构造方法
public Integer(int value) 将基本类型int转换成包装类
public Integer(String s)将int型字符串转换为包装类型。
public class InterDemo {
public static void main(String[] args) {
Integer integer = new Integer(100);
Integer integer1 = new Integer("100");//传一个是数字的字符串
System.out.println(integer);
System.out.println(integer1);
}
}
自动装箱与拆箱
自动装箱是指把基本类型转换为包装类类型。
自动拆箱是指把包装类类型转换为基本类型。
public class IntegerDemo {
//JDK.5之后 有自动拆装箱
//自动装箱:将基本数据类型,直接转换成对应的包装类型
//自动拆箱:将包装类型,自动转成对应的基本类型
public static void main(String[] args) {
int num = 100;
Integer a = num;//自动装箱 相当于Integer a= new Inerger(num)
System.out.println("-------------------");
Integer b = 100;//自动装箱
b = b + 20;//自动拆箱和自动装箱 相当于 b = new Integer(b.intValue()+20);
System.out.println("-----------------------------------");
Integer integer = Integer.valueOf(100);//手动装箱
int i = integer.intValue();//手动拆箱
int c=10;
int r= integer+c;//自动拆箱
}
}
与基本类型的转换
1.从int 转换到String的方法
a:和""进行拼接
b:public static String valueOf(int i)
c:int – Integer – String
d:public static String toString(int i)
2.从String 转换到int的方法
a:String – Integer – intValue();
b:public static int parseInt(String s)//将数值字符串转换为一个Int值。
public class InterDemo {
public static void main(String[] args) {
// int --String
int num=100;
String s=num+"";
String s1 = String.valueOf(num);//推荐使用
String s2 = new Integer(num).toString();
System.out.println(s2);
//String--int
String str="100";
Integer integer2 = new Integer(str);
int i = integer2.intValue();
System.out.println(i);
//Integer中的一个静态方法,将一个字符串的数字转成数字
int i1 = Integer.parseInt(str);//推荐使用
// NumberFormatException 数字格式化异常
System.out.println(i1);
}
}