Question 12
Back to Exercise
What is the output of the following Java program?
public class Main {
static int weight(Object o) {
return switch (o) {
case Integer i when i < 0 -> 0;
case Integer i -> i;
case String s when s.length() > 3 -> 10;
case String s -> 1;
case int[] arr -> arr.length;
default -> -1;
};
}
public static void main(String[] args) {
Object[] data = {5, -3, "Java", "Go", new int[]{1, 2, 3}, 2.5};
int sum = 0;
for (Object o : data) sum += weight(o);
System.out.println(sum);
}
}
- A 18 Correct
- B 19
- C 15
- D 16
Correct Answer: Option A
5 + 0 + 10 + 1 + 3 + (-1) = 18. Guarded cases are listed before the unguarded case of the same type.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!