常量池
第一个问题:运算符“==”比较的是什么?
答:①对于基本数据类型,比较的是值是否相等;
②对于包装器类型,比较的是其引用的对象的地址。
运行下面的程序:
public class Test {
public static void main(String[] args) {
//自动装箱功能,把128直接赋值给i1
Integer i1 = 128;
Integer i2 = 128;
System.out.println(i1 == i2);
int i3 = 128;
int i4 = 128;
System.out.println(i3 == i4);
}
}
运行结果:
false
true
第二个问题:整数常量池
运行下面的程序:
public class Test {
public static void main(String[] args){
//自动装箱功能,把100直接赋值给Integer对象i1、i2
Integer i1 = 100;
Integer i2 = 100;
System.out.println (i1 == i2);
Integer i3= new Integer (100);
System.out.println (i1 == i3);
}
}
运行结果:
true
false
整数常量池缓存了一个字节大小的整数,即-128~127。使用自动装箱功能把100直接赋值给i1、i2,事实上是建立了整数常量池中100的两个引用地址,这两个引用地址均指向常量池中的100。而i3是在常量池之外的堆内存中创建的一个新的Integer对象的引用地址。
第三个问题:字符串常量池和intern()方法
字符串常量池缓存的是你在程序中创建过的字符串。
public class Test {
public static void main(String[] args) {
String str1 = new String ("HelloWorld");
}
}
上面的代码在内存中创建了两个"HelloWorld":一个在堆内存中,一个在字符串常量池中。
字符串方法intern(): 取当前字符串在常量池中的引用地址。
运行下面的程序:
public class Test {
public static void main(String[] args) {
String str1 = new String ("HelloWorld");
String str2 = "HelloWorld";
System.out.println (str1.intern() == str2);
}
}
运行结果:
true