nerdexam
Oracle

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.

Using Operators and Decision Constructs

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)
  • A
    14% (8)
  • B
    11% (6)
  • C
    4% (2)
  • D
    72% (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`.

Aline n1

`line n1` correctly declares and initializes the `amount` variable within its block.

Bline n2

`line n2` correctly declares and initializes the `amount` variable within its block.

Cline n3

`line n3` correctly declares and initializes the `amount` variable within its block.

Dline n4Correct

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

#variable scope#if-else#compilation error#local variables

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice