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」。
