1Z0-803 · Question #126
Given the code fragment: String[] cartoons = {"tom", "jerry", "micky", "tom"}; int counter = 0; And, if ("tom".equals(cartoons[0])) { counter++; } else if ("tom".equals(cartoons[1])) { counter++; } el
The correct answer is A. 1. The code initializes a string array and then uses an if-else if chain to check for the string 'tom' at various array indices, incrementing a counter upon the first match.
Question
Given the code fragment:
String[] cartoons = {"tom", "jerry", "micky", "tom"}; int counter = 0; And, 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?
Options
- A1
- B2
- C4
- D0
How the community answered
(29 responses)- A86% (25)
- B7% (2)
- C3% (1)
- D3% (1)
Why each option
The code initializes a string array and then uses an if-else if chain to check for the string 'tom' at various array indices, incrementing a counter upon the first match.
The condition "tom".equals(cartoons[0]) evaluates to true because cartoons[0] is "tom". The counter is then incremented to 1, and since it's an if-else if chain, subsequent else if conditions are not evaluated.
'2' is incorrect because only the first if condition evaluates to true, causing the counter to increment only once.
'4' is incorrect as the counter is only incremented when the first matching if condition is met, and the else if chain prevents multiple increments for subsequent matches.
'0' is incorrect because the string 'tom' is found at cartoons[0], which increments the counter to 1.
Concept tested: Java if-else if conditional logic
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Topics
Community Discussion
No community discussion yet for this question.