假设在比较 str 和 “hehe"两个字符串是否相等我们可以采用以下两种方式:
(1)
String str = null;
if ("hehe".equals(str)) {
System.out.println("相等");
} else {
System.out.println("不相等");
}
(2)
String str = null;
if (str.equals("hehe")) {
System.out.println("相等");
} else {
System.out.println("不相等");
}
我们的结论是采用第一种方式比较合理高效,原因很简单,如果 str 是空字符,那么就不能使用 . 操作,否则就会出现以下出错状况: