Java中『equals』和『 == 』的不同之处是什么?
在使用IF语句进行条件分支时,如果不了解『equals』和『 == 』,而使用『 == 』,很有可能会出现许多故障(bug)。
如果执行以下处理,您能够知道在控制台上输出了什么吗?
程序
public class Test {
public static void main(String[] args) {
String test1 = new String("100");
String test2 = new String("100");
if (test1 == test2) {
System.out.println("同じです");
} else {
System.out.println("違います");
}
if (test1.equals(test2)) {
System.out.println("同じです");
} else {
System.out.println("違います");
}
}
}
控制台输出
違います
同じです