Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 109
Question ID: UKOCP47829
Consider below code of Wall.java file:
- package com.udayankhattry.ocp;
- public class Wall {
- public static void main(String args[]) {
- double area = 5.7;
- String color;
- if (area < 7)
- color = "BLUE";
- System.out.println(color);
- }
- }
What will be the result of compiling and executing Wall class?
- A BLUE
- B null
- C An exception is thrown at runtime
- D Compilation error
Reveal correct answer
Correct answer: D
Explanation
UKOCP47829:
'color' is LOCAL variable and it must be initialized before it can be used.
As area is not compile time constant, java compiler doesn't have an idea of the value of variable area.
There is no else block available as well.
So compiler cannot be sure of whether variable color will be initialized or not. So System.out.println(color); causes compilation error.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
