<pre name="code" class="java"> //有这样一段代码,想想它的结果是什么呢?
public class StringTest {
public static void main(String[] args) {
String a=new String("hello lol");
String b=new String("hello lol");
System.out.println(a==b);//false
System.out.println(a.equals(b));//true
String c="hello league of legends";
String d="hello league of legends";
System.out.println(c==d);//true
System.out.println(c.equals(d));//true
}
}
答案已在注释中给出。为什么会是这种情况呢?
下面我们来分析一下:
“==”操作符专门用来比较两个变量是否相等。
equals用来比较两个独立对象的内容是否相等。
String a=new String("hello lol");
String b=new String("hello lol");
a,b两个变量分别指向两个不同的String对象,但他们的内容相同。
String c="hello league of legends";
String d="hello league of legends";
字符串直接用这种方式赋值,java会把"hello league of legends"放在同一个内存空间,即在数据缓冲局中c ,d变量所指向的是同一个String对象。
所以产生如上述注释中产生的输出。