1Z0-803 · Question #162
Given: public class VarScope { public static void main (Stirng[] args) { String color = "red"; int qty = 10; if (color.equals("red")) { // line n1 int amount = qty 10; } else if (color.equals("green")
The correct answer is D. line n4. The variable amount is declared exclusively within the block-scoped if-else if statements, making it inaccessible when System.out.print(amount) is called outside those blocks at line n4.
Question
Given:
public class VarScope { public static void main (Stirng[] args) { String color = "red"; int qty = 10; if (color.equals("red")) { // line n1 int amount = qty * 10; } else if (color.equals("green")) { int amount = qty * 15; // line n2 } else if (color.equals("blue")) { int amount = qty * 5; // line n3 } System.out.print(amount); // line n4 } } Which line causes a compilation error?
Options
- Aline n1
- Bline n2
- Cline n3
- Dline n4
How the community answered
(57 responses)- A14% (8)
- B11% (6)
- C4% (2)
- D72% (41)
Why each option
The variable `amount` is declared exclusively within the block-scoped `if-else if` statements, making it inaccessible when `System.out.print(amount)` is called outside those blocks at `line n4`.
`line n1` correctly declares and initializes the `amount` variable within its block.
`line n2` correctly declares and initializes the `amount` variable within its block.
`line n3` correctly declares and initializes the `amount` variable within its block.
The variable `amount` is declared inside the scope of the `if` and `else if` blocks (lines n1, n2, n3). Due to block scoping rules in Java, `amount` is not visible or accessible outside these blocks. Consequently, attempting to print `amount` at `line n4` will result in a "cannot find symbol" compilation error.
Concept tested: Java variable scope and visibility
Source: https://docs.oracle.com/javase/specs/jls/se11/html/jls-6.html#jls-6.3
Topics
Community Discussion
No community discussion yet for this question.