public class Test
{
public static void main(String[] args)
{
String str1 ="Too many cooks";
String str3 ="Too many cooks";

if(str1==str3)
{
System.out.println("ok");
}
}
}为什么结果是ok?
改成str1.equals(str3)还是ok.
小弟初学java,请各位大哥帮忙。

解决方案 »

  1.   

    equals是比较值,==是比较引用的对象
    因为你声明的时候没有new,值又相同,两个引用了一个对象。
      

  2.   

    系统做优化了啊,虽然你写了2个“Too many cooks”,但是系统只保存了一个,节省空间啊。
    如果这样写就不会OK了:
    String str1 = new String("Too many cooks");
    String str3 = new String("Too many cooks");
      

  3.   

    同意andycpp(幻瞳) 说法:)