包装类
- 基本数据类型所对应的引用数据类型
- Object可统一所有数组,包装类的默认值为null
为什么会有包装类
基本数据类型不是面向对象,java提供了与基本数据类型对应的引用数据类型
byte | short | int | long | float | double | boolean | char |
---|---|---|---|---|---|---|---|
Byte | Short | Integer | Long | Float | Double | Boolean | Charater |
包装类型体系
Number[数字类型]
Byte Short Integer Long Float Double
byte | byteValue() 返回指定号码作为值 byte ,这可能涉及舍入或截断。 |
---|---|
abstract double | doubleValue() 返回指定数字的值为 double ,可能涉及四舍五入。 |
abstract float | floatValue() 返回指定数字的值为 float ,可能涉及四舍五入。 |
abstract int | longValue() 返回指定数字的值为 long ,可能涉及四舍五入或截断。 |
short | shortValue() 返回指定号码作为值 short ,这可能涉及舍入或截断。 |
拆箱、装箱
把基本数据类型转换成引用数据类型的过程。
//装箱
int n = 90;
Integer age = new Integer(n);
//拆箱
int m = age.intValue();
System.out.println(m);
JDK1.5 自动装箱拆箱
Integer nb = 666; // 装箱
int sb= nb+100; // 拆箱
System.out.println(sb);
让使用包装类型更简单,基本数据类型和引用数据类型可以实现相互赋值。
类型转换
- 字符串转 数值类型
String price = "1234";
int pp = Integer.parseInt(price); //返回 int 基本类型
System.out.println(pp*0.5);
Integer pp2= Integer.valueOf(price);// 返回Integer 包装类型
System.out.println( pp2*0.5 );
确保字符串格式一定符合待转类型格式: 否则 java.lang.NumberFormatException
- 数值类型 转字符串
int abc = 123;
String strabc= abc+"";
System.out.println(abc);
String xx= String.valueOf(abc);
System.out.println(xx+1);
整形缓冲区
java 默认缓存了256个整数包装类对象也就是Byte范围内的对象,以便复用。
Integer a=127;
Integer b=127;
System.out.println(a==b); // true
Integer a=128;
Integer b=128;
System.out.println(a==b); // false