包装类
1.作为和基本数据类型对应的类型存在,方便涉及到对象的操作。
2.包含每种基本数据类型的相关属性如最大值、最小值等,以及相关的操作方法(这些操作方法的作用是在基本数据类型、包装类对象、字符串之间提供相互之间的转化!)。
包装类的使用
public static void main(String[] args) {
/*基本数据类型转换成包装类对象*/
Integer a=new Integer(30);
Integer b=Integer.valueOf(30);
/*把包装类转换层基本类型*/
int c=b.intValue();
double d=b.doubleValue(); //double包装类转换为double类型
/*把字符串转成包装类对象*/
Integer e=new Integer("1234");
Integer f=Integer.parseInt("123");
/*把包装类转成字符串*/
String str=f.toString();
/*常见的常量*/
System.out.println("int类型最大的整数:"+Integer.MAX_VALUE);
}
}
> 编译:int类型最大的整数:2147483647
自动装箱,拆箱
1.自动装箱和拆箱就是将基本数据类型和包装类之间进行自动的互相转换。
2. 基本类型的数据处于需要对象的环境中时,会自动转为“对象”。
Integer a=123; //自动装箱:Integer a=Integer.valueOf(123);
- 每当需要一个值时,对象会自动转成基本数据类型。
int b=a; //自动拆箱:编译器自动修改为int b=a.intValue();
缓存
1.整型、char类型所对应的包装类,在自动装箱时,对于-128~127之间的值会进行缓存处理,其目的是提高效率。
2. 包装类在自动装箱时为了提高效率,对于-128~127之间的值会进行缓存处理。超过范围后,对象之间不能再使用==进行数值的比较,而是使用equals方法。
Integer in1 = -128;
Integer in2 = -128;
System.out.println(in1 == in2); //true 因为123在缓存范围内
System.out.println(in1.equals(in2)); //true
Integer in3 = 1234;
Integer in4 = 1234;
System.out.println(in3 == in4); //false 因为1234不在缓存范围内(不是同一个对象)
System.out.println(in3.equals(in4)); //true
}
*缓存[-128,127]之间的数字,实际就是系统初始的时候,创建了[-128,127]之间的一个缓存数组。
* 当我们调用ValueOf()的时候,首先检查s是否在[-128,127]之间,如果在这个范围,直接从缓存数组中拿出已经建好的对象
*如果不在这个范围,则创建新的Integer对象 */
String类
1.String 类对象代表不可变的Unicode字符序列,因此可以称为不可变对象(指的是对象内部的成员变量的值无法再改变)
/*private final char value[];是String的核心*/
String str="abcd"; //不能修改
- 在遇到字符串常量之间的拼接时,编译器会做出优化,即在编译期间就会完成字符串的拼接
//编译器做了优化,直接在编译的时候将字符串进行拼接
String str1 = "hello" + " java"; //相当于str1 = "hello java";
String str2 = "hello java";
System.out.println(str1 == str2); //true
String str3 = "hello";
String str4 = " java";
//编译的时候不知道变量中存储的是什么,所以没办法在编译的时候优化
String str5 = str3 + str4;
System.out.println(str2 == str5); //false
System.out.println(str2.equals(str5)); //做字符串比较使用equals,不要使用==
StringBuilder
1.这个字符数组没有用final修饰,随时可以修改,称之为“可变字符序列”。
StringBuilder a=new StringBuilder("abcdefg");
System.out.println(a.hashCode());
System.out.println(a);
a.setCharAt(2, 'O'); //修改下标2的字符
System.out.println(a.hashCode());
System.out.println(a);
> 编译:366712642
abcdefg
366712642
abOdefg