Compare with two strings:

Loope 2001-12-14 12:49:51
Compare with two strings:
When I run the test program as the following using
javac Test testString

I got the following results:

test == testString
test1 != testString
test1 != test
test2 == test
test equal to testString
test1 equals to testString
test1 equals to test
test2 equals to test


So why test1 != testString and test1 != test ?

Thank you!

The following are my codes:

public static void main(String[] args) {
String test = "testString";
String test1 = args[2];
String test2 = test;

if (test == "testString") {
System.out.println("test == testString");
} else {
System.out.println("test != testString");
}

if (test1 == "testString") {
System.out.println("test1 == testString");
} else {
System.out.println("test1 != testString");
}

if (test1 == test) {
System.out.println("test1 == test");
} else {
System.out.println("test1 != test");
}

if (test2 == test) {
System.out.println("test2 == test");
} else {
System.out.println("test2 != test");
}

if (test .equals("testString")) {
System.out.println("test equal to testString");
} else {
System.out.println("test does not equal to testString");
}

if (test1 .equals("testString")) {
System.out.println("test1 equals to testString");
} else {
System.out.println("test1 does not equal to testString");
}

if (test1 .equals(test)) {
System.out.println("test1 equals to test");
} else {
System.out.println("test1 does not equal to test");
}

if (test2 .equals(test)) {
System.out.println("test2 equals to test");
} else {
System.out.println("test2 does not equal to test");
}
}
...全文
44 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhaofeiyu 2001-12-14
  • 打赏
  • 举报
回复
== -------->比较的是句柄 (refference)
equals -------->比较的是内容 (Object refferenced to)

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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