Given the code fragment:

String[] cartoons = {"tom", "jerry", "micky", "tom"};
int counter = 0;
if ("tom".equals(cartoons[0])) {
    counter++;
} else if ("tom".equals(cartoons[1])) {
    counter++;
} else if ("tom".equals(cartoons[2])) {
    counter++;
} else if ("tom".equals(cartoons[3])) {
    counter++;
}
System.out.print(counter);

What is the result?

A.

1

B.

2

C.

4

D.

0

題解

cartoons[0] 所參考到的字串物件是「tom」,所以第一個 if 的條件式會成立,將 counter 變數的值加 1。由於之後其它條件判斷都是使用 else if,因此當前面有一個條件式成立之後,就不會再繼續判斷下去了,所以最後輸出「1」。