nerdexam
Oracle

1Z0-808 · Question #27

Given: ``java public class Triangle { static double area; int b = 2, h = 3; public static void main(String[] args) { //line n1 double p, b, h; if (area == 0) { b = 3; h = 4; p = 0.5; } area = p b h…

The correct answer is D. Compilation fails at line n2. Option D is correct because Java requires local variables to be definitely assigned before use, and the compiler cannot guarantee that p is initialized before line n2. Since p is only assigned inside the if block, the compiler conservatively rejects the code - even though at…

Java Basics

Question

Given:
public class Triangle {
 static double area;
 int b = 2, h = 3;
 public static void main(String[] args) { //line n1
 double p, b, h;
 if (area == 0) {
 b = 3;
 h = 4;
 p = 0.5;
 }
 area = p * b * h; //line n2
 System.out.println("Area is " + area);
 }
}
What is the result?

Options

  • AArea is 6.0
  • BArea is 3.0
  • CCompilation fails at line n1
  • DCompilation fails at line n2

How the community answered

(41 responses)
  • A
    5% (2)
  • B
    10% (4)
  • C
    17% (7)
  • D
    68% (28)

Explanation

Option D is correct because Java requires local variables to be definitely assigned before use, and the compiler cannot guarantee that p is initialized before line n2. Since p is only assigned inside the if block, the compiler conservatively rejects the code - even though at runtime area always starts at 0.0, making the branch always execute.

Why A is wrong: If the code compiled and ran, p * b * h would use the local variables b=3, h=4, p=0.5, yielding 6.0 - but it never gets that far.

Why B is wrong: 3.0 would result from 0.5 * 2 * 3 using the instance fields, but local variables b and h shadow the instance fields inside main, and again, compilation fails before runtime anyway.

Why C is wrong: Line n1 is a perfectly valid main method signature - public static void main(String[] args) is exactly what the JVM expects.

Memory tip: Think of the Java compiler as a pessimist - it only trusts initialization that happens on every possible path to a variable's use. If a variable is assigned only inside an if (with no else), the compiler assumes the branch might be skipped and will refuse to compile any subsequent read of that variable.

Topics

#Variable Scope#Definite Assignment#Local Variables#Compilation Error

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice