Given the code fragment:
StringBuilder sb = new StringBuilder() ;
sb.append("world");
Which code fragment prints Hello world?
A.
sb.insert(0,"Hello ");
System.out.println(sb);
B.
sb.append(0,"Hello ");
System.out.println(sb);
C.
sb.add(0,"Hello ");
System.out.println(sb);
D.
sb.set(0,"Hello ");
System.out.println(sb);
题解
sb 变量所参考的 StringBuilder 对象一开始的字符串内容是「world」,如果要输出「Hello world」,就必须要将「Hello 」字符串插入至「world」之前。
选项 A,使用 StringBuilder 对象的「insert」方法来插入「Hello 」字符串至开头的位置,这是正确的。
选项 B,StringBuilder 对象的「append」方法不能这样用。
选项 C,StringBuilder 对象没有「add」方法。
选项 D,StringBuilder 对象没有「set」方法。
