class lesson
{
public static void main(String args[])
{
String str1 = "abcd";
String str2 = "abcd";
String str3 = str1;
if (str1==str2)
System.out.println("ture");
if (str1==str3)
System.out.println("right");
}
}
-------------------------------------------------
打印出rure right
--------------------------------------------------
------------------------------------------------------
class lesson
{
public static void main(String args[])
{
String str1 =new String("abcd");
String str2 =new String("abcd");
String str3 = str1;
if (str1==str2)
System.out.println("ture");
if (str1==str3)
System.out.println("right");
}
}
-------------------------------------
只打印right
为什么???
字符串池为什么不起作用了?
{
public static void main(String args[])
{
String str1 = "abcd";
String str2 = "abcd";
String str3 = str1;
if (str1==str2)
System.out.println("ture");
if (str1==str3)
System.out.println("right");
}
}
-------------------------------------------------
打印出rure right
--------------------------------------------------
------------------------------------------------------
class lesson
{
public static void main(String args[])
{
String str1 =new String("abcd");
String str2 =new String("abcd");
String str3 = str1;
if (str1==str2)
System.out.println("ture");
if (str1==str3)
System.out.println("right");
}
}
-------------------------------------
只打印right
为什么???
字符串池为什么不起作用了?
{
public static void main(String args[])
{
String str1 =new String("abcd");
String str2 =new String("abcd");
String str3 = str1;
if (str1.equals(str2))
System.out.println("ture");
if (str1==str3)
System.out.println("right");
}
}
答案就一样了
String str2 = "abcd";
···················
String str1 =new String("abcd");
String str2 =new String("abcd");
一样在内存中分配的不是同一块内存地址,所以才会出现上面的结果,小弟拙见,不对请指出。谢谢
String str1 = "abcd";
String str2 = "abcd";
是同一块内存地址
String str1 =new String("abcd");
String str2 =new String("abcd");
就不同了
String str1 = "abcd";
String str2 = "abcd";此时str2没有创建新的对象,而是把地址指向了已经创建的"abcd",所以str1和str2所指向的地址一样
String str1 =new String("abcd");
String str2 =new String("abcd");
此时str1和str2都创建了新的对象,所以str1和str2指向的地址不一样,而此时str1.equals(str2)返回的却是true,因为其内容一样
return (this == obj);
}但是String类覆盖了Object中的eqauls()方法, 使得它的功能扩充为比较两个字符串是否一样(即使不是同一个对象). 具体实现大家自己去看, 我就不贴了.
== 地址
String str1 = "abcd";
String str2 = "abcd";
"abcd"是常量,被分配在静态内存区,str1和str2都指向这片静态内存区地质,所以==成立String str1 =new String("abcd");
String str2 =new String("abcd");
对象是用new创建出来,被分配在堆内存区,每个new出来的对象,分配的堆内存地址是不一样的,所以==不成立,但是两个对象的值是相等的,所以equals成立