目录
- 基本数据类型封装成对象,在对象中定义了属性和方法,可以方便的操作该数据(得到整型最大值,最小值,进制转换等等)
- 在java.lang包中,对于每个基本数据类型都有一个相应的包装类。
-
除了整型及字符型外,其他的包装器类型名字都是将基本数据类型首字母变大写即可
1、Integer类
主要用于基本数据类型和字符串之间的转换
静态方法
public class ParseTest {
public static void main(String[] args) {
String str="116";
int i=Integer.parseInt(str);
System.out.println(i);
short s=Short.parseShort(str);
System.out.println(s);
byte b=Byte.parseByte(str);
System.out.println(b);
long l=Long.parseLong(str);
System.out.println(l);
float f=Float.parseFloat(str);
System.out.println(f);
double d=Double.parseDouble(str);
System.out.println(d);
boolean l1= Boolean.parseBoolean(str);
System.out.println(l1);
Integer x=new Integer("43");
Integer y=20;
}
}
Run:
116
116
116
116
116.0
116.0
false
2、Character类
都是静态方法,可以直接通过类名调用,返回值均为布尔类型
public class CharacterTest {
public static void main(String[] args) {
char[] charArray = {'*', '7', 'b', ' ', 'A'};
for (int i = 0; i < charArray.length; i++) {
if (Character.**isDigit**(charArray[i])) {
System.out.println(charArray[i] + "是一个数字。");
}
if (Character.**isLetter**(charArray[i])) {
System.out.println(charArray[i] + "是一个字母。");
}
if (Character.**isWhitespace**(charArray[i])) {
System.out.println(charArray[i] + "是一个空格。");
}
if (Character.**isLowerCase**(charArray[i])) {
System.out.println(charArray[i] + "是小写形式。");
}
if (Character.**isUpperCase**(charArray[i])) {
System.out.println(charArray[i] + "是大写形式。");
}
}
}
}
3、装箱和拆箱
- 常量池就是方法区的一部分,是内存的逻辑分区。
- 装箱:基本数据类型转换为包装器类型,称为装箱(boxing)int型转换为Integer类型
- 拆箱:包装器类型转换为基本数据类型称为拆箱(unboxing)Integer类型转换为int类型
- 在自动装箱拆箱过程中,只有数值是byte范围内的时候,才使用到常量池,否则都是分配新的内存空间
public class Wapper {
public static void main(String[] args) {
//包装类型 赋值方法
Integer ai = new Integer(10);
Integer bi = 10;
//手动装箱和拆箱
Integer aoi = new Integer(20);
//拆
int i1 = aoi.intValue();
//装
Integer aoi1 = new Integer(i1);
//自动拆装
Integer aoi3 = 123;
int i3 = aoi3;
Integer aoi4 = i3;
Integer aoi5 = i3 + 80;
}
}