Given the code fragment:

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder(5);
    String s = "";

    if (sb.equals(s)) {
        System.out.println("Match 1");
    } else if (sb.toString().equals(s.toString())) {
        System.out.println("Match 2");
    } else {
        System.out.println("No Match");
    }
}

What is the result?

A.

Match 1

B.

Match 2

C.

No Match

D. A NullPointerException is thrown at runtime.

题解

程序第 7 行,判断 StringBuilder 对象和字符串对象逻辑上是否相等。它们是不同类型的对象,永远不会相等。

程序第 9 行,判断 StringBuilder 对象转成字符串后和字符串对象逻辑上是否相等。它们都是空字符串,因此相等,输出「Match 2」。