Question 14
Back to Exercise
What is the output of the following Java program?
public class Main {
public static void main(String[] args) {
int a = 5, b = -2;
String r = "start";
if (a > 0)
if (b > 0)
r = "both positive";
else
r = "a positive, b not"; // indented like the first if, but belongs to the second
System.out.println(r);
a = -1;
r = "start";
if (a > 0)
if (b > 0)
r = "both positive";
else
r = "a positive, b not";
System.out.println(r);
}
}
- A a positive, b not start Correct
- B start a positive, b not
- C a positive, b not a positive, b not
- D both positive start
Correct Answer: Option A
The else belongs to if (b > 0). When a is negative, the outer if is false and nothing runs – the indentation lied.
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!