Oracle Certified Associate Java Se 8 Programmer · Free Practice Question Medium
Question 10
What will be the result of compiling and executing RoomColorTest class?
public class RoomColorTest {
public static void main(String[] args) {
double size = 5.7;
String paint;
if (size < 7)
paint = "blue";
System.out.println(paint);
}
}
-
A
blue
-
B
Compilation error
-
C
null
-
D
NullPointerException
Reveal correct answer
Correct answer: B
Explanation
The variable paint is local and must be initialized before use. The if condition is not known at compile time, and there's no else block. Thus, the compiler cannot guarantee that paint will be initialized before the System.out.println(paint); statement.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
