初识equals和==
在Java中,String类用的比较广泛,可是你真的知道String吗?
看下面的代码:
public class StringTest {
public static void main(String[] args) {
String s1="hello";
String s2="hello";
System.out.println(s1.equals(s2));
System.out.println(s1==s2);
}
}
运行结果如下:
true
true
对于上面的代码,在JVM中存在着一个字符串池,其中保存着很多String对象,而且可以被共享使用,s1和s2引用的是同一个常量池中的对象,所以它们不仅值相等而且对象也相等。
再来看下面的代码:
public class StringTest {
public static void main(String[] args) {
String s1= new String ("hello");
String s2= new String ("hello");
System.out.println(s1.equals(s2));
System.out.println(s1==s2);
}
}
运行结果如下:
true
false
对于上面的代码,s1,s2都是通过new String(“hello”)创建出来的,虽然它们的值都是"hello",但它们分别是2个对象,它们在内存中的地址是不同的。所以它们虽然值相等但对象并不相等。
Java中的常量池
如果用String s="hello"语句,会首先在字符串常量池中查找是否存在相同值(采用equals比较方法)的对象,如果有就直接使用,如果没有那么就创建这个对象,再把它加入到字符串池中,并返回它的引用。
用代码表示如下:
//将s1放入字符串常量区
String s1 = "hello";
//s2引用常量区的对象,这时没有创建新的对象
String s2 = "hello";
//创建一个值为"hello"的字符串对象
String s3 = new String ("hello");
//重新创建一个值为"hello"的字符串对象
String s4 = new String ("hello");