JAVA包装类
java语言是面向对象的,但是8种基本数据类型不是对象
java是从C语言中演变过来的,沿用了这8个基本数据类型
基本数据类型:
优点:占用内存小,灵活方便。存在栈中
缺点:不具备对象的特点,在以后泛型,集合等API操作时,不支持
通过给基本数据类型包装成对象,就可以达到调用的目的。
1. 基本数据类型封装为包装类的过程叫 装箱
java1.5之前 必须手动装箱 Integer a=new Integer(10);
java1.5之后 自动装箱 和拆箱 Integer a=10;
注意:装箱时 基本数据类型匹配 Double d=1.5;
//Double d=1; 编译出错
但是用Double d=new Double(10) //其中10可以自动转换为double型的
栈里存放的是基本数据类型
堆里存放对象
方法区 类的一些属性 放一些常用的数字
2.包装类常量值 存在了缓冲区(在方法区里)
包装类 | 缓冲区范围 |
---|---|
Integer | -128 ~127 |
Byte,Short,Long | -128~127 |
Character | 0~127 |
Float,Double | 没有缓冲区 |
注意:如果在缓冲区内,不用创建对象,直接从方法区的常量池去拿。此时 比较的话是true
Integer a=120;
Integer b=120;
System.out.println(a==b);
->>结果为true;
如果不在缓冲区,需要创建对象,放在了堆里。
Integer a=128;
Integer b=128;
System.out.println(a==b);
->>结果为false;
3.基本数据类型和字符串之间的转换
(1)基本数据类型 转 字符串
方法1:字符串 和基本数据类型 用+拼接后 直接转换为字符串。
String s=10+“”;
System.out.println(s);
=>输出为字符串10
方法2:
使用方法String.valueOf(基本数据类型);
(2)字符串转基本数据类类型
基本包装类.parseXXX() 比如Integer.parseInt();
String s="123";
int i=Integer.parseInt(s);
System.out.println(i);
包装类里的数据不可变。如果改变,会重新建一个
字符串,常量池 每次 拼接 都是新建一个
因为他们的底层都是被final修饰的。
(3)包装类转换自身
将包装类转换成基本数据类型 xxxValue---------大转小
Short s=123;
byte b1=s.byteValue();
short s1=s.shortValue();
double d1=s.doubleValue();
System.out.println(b1);
System.out.println(s1);
System.out.println(d1);
将基本数据类型转换成包装类 包装类. valueOf(基本数据类型)------小转大
Short sh = 1; //==Short sh1 = Short.valueOf((short)1);装箱
short shh = sh;// short shh = Short.shortValue(sh); 拆箱。