一道Morgan IT笔试题,关于生产了几个对象的
public class Test
{
static void print(String s1,String s2)
{
if(s1 == s2)
System.out.println("Ooops~");
else
System.out.println("Wows~");
if(s1.equals(s2))
System.out.println("Wows~");
else
System.out.println("Ooops~");
}
static public void main(String args[])
{
String s1 = new String ("hello world");
String s2 = new String ("hello world");
print(s1,s2);//s1,s2是2个不同的对象
s1 = "hello world";
s2 = "hello world";
print(s1,s2);//s1,s2是指向同一对象
s1 = s1 + "!";
s2 = s2 + "!";
print(s1,s2);//s1,s2不同对象
s1 = "hello" + "world";
s2 = "hello" + "world";
print(s1,s2);//s1,s2是指向同一对象
}
}
注意:String的==与equals方法区别:
==判断2个String对象是不是指向同一对象,equals 判断2个String对象的值是不是一样
输出结果为:
Wows~
Wows~
Ooops~
Wows~
Wows~
Wows~
Ooops~
Wows~
关于String的详细分析,可见<<Java面试解惑之二>>