public class Test1 {
public static void main(String args[])
{
String x="a";
String y="a";
System.out.println(x==y); //This is true?Why?
String A="hello";
String B=" world";
String C="hello world";
String D="hello world";
A+=B;
System.out.println(A==C);//This is false?Why?
System.out.println(C==D);//This is true?Why?
String H=new String("hello");
String J=new String("hello");
System.out.println(H==J);//This is false?Why?
}
}
public static void main(String args[])
{
String x="a";
String y="a";
System.out.println(x==y); //This is true?Why?
String A="hello";
String B=" world";
String C="hello world";
String D="hello world";
A+=B;
System.out.println(A==C);//This is false?Why?
System.out.println(C==D);//This is true?Why?
String H=new String("hello");
String J=new String("hello");
System.out.println(H==J);//This is false?Why?
}
}
String H=new String("hello");
String J=new String("hello");
H和J虽然内容相同但是都使用了new分配了地址,所以用==返回的是false
String x="a";
String y="a";
System.out.println(x==y); //This is true?Why?
这儿为什么会是输出的true?
stamp80(峰) ( ) 信誉:105 ,谢谢!不好意思,能不能说得详细些?
String y="a"; 那么这个你也可以理解啦,也是两个对象,y也指向a ,
所以x==y比较他们所指向的地址时是相同的。String H=new String("hello");
String J=new String("hello");
这两个前面加拉个new 就是新开辟一块内存,H指的hello的地址,和J指的hello地址是不同的
所以 H==J 是False
所以H,J的值是两个指针,分别指向的是两个各自创建的堆中的"abc",注意:是2个各自新建的"abc",就是说不是同一个字符串。而如果用equals方法比值(比较指向字符串的值)是相等的。
而String s="abc";是创建一个字符串指针,指向常量池中的"abc",所以无论创建几个String,它们的值都是常量池中"abc"的地址,也就是相等的。
public static void main(String args[]){
String x="a";//"a"分配内存r x引用r
String y="a";//y引用r
System.out.println(x==y); //This is true?Why?地址相同
String A="hello";//"hello"分配内存rm1 A引用rm1
String B=" world";//" world"分配内存rm2 B引用rm2
String C="hello world";//"hello world"分配内存rm3
String D="hello world";
A+=B;//A+B 分配内存rm4 A引用rm4
System.out.println(A==C);//This is false?Why?地址不同
System.out.println(C==D);//This is true?Why?地址相同
String H=new String("hello");//分配内存r1
String J=new String("hello");//分配内存r2
System.out.println(H==J);//This is false?Why?地址不同
}
}
比较接受aaa2003gf() ( ) 信誉:100
虽然sky_boxer(饿鱼骨头) ( ) 信誉:100 的能解释得通,但我记得在java中不像c/c++,它是不存在指针(好像它全部是在变量存储在堆中,不太记得这个)总之,感谢大家!!