问一道简单的题目

jacky_yp 2003-10-15 10:54:31
public class test {

public static void main(String args[]) {
String s1 = new String("amit");
System.out.println(s1.replace('m','r'));
System.out.println(s1);
String s3 = "arit";
String s4 = "arit";
String s2 = s1.replace('m','r');
System.out.println(s2 == s3);
System.out.println(s3 == s4);
}
}

输出为:arit
amit
false
true
为什么System.out.println(s2 == s3)输出会是false?s2也等于“arit”啊!
...全文
96 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
SwordsmanF 2003-10-16
  • 打赏
  • 举报
回复
MyClass m1=new MyClass();
MyClass m2=m1;
if(m1==m2){
System.out.println("yes");
}
jacky_yp 2003-10-15
  • 打赏
  • 举报
回复
即使把if(m1.equals(m2))换成 if (m1 == m2)还是输出"Both are not equal"啊!
jacky_yp 2003-10-15
  • 打赏
  • 举报
回复
明白!但这道题:
What will happen if you compile/run the following code?

class MyClass
{
int x;
MyClass(int i)
{
x = i;
}

public static void main(String args[])
{
MyClass m1 = new MyClass(100);
MyClass m2 = new MyClass(100);

if(m1.equals(m2))
{
System.out.println("Both are equal");
}
else
{
System.out.println("Both are not equal");
}
}

}
为什么输出的是("Both are not equal")啊?
happyegg 2003-10-15
  • 打赏
  • 举报
回复
String要用s2.equals(s3)来比较
SwordsmanF 2003-10-15
  • 打赏
  • 举报
回复
==判断的是是否引用了同一个对象
equal("")才是比较字符串

50,503

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧