1Z0-803 · Question #118
Given: public class CheckIt { public static void main (String[] args) { if (doCheck()) { System.out.print("square "); } System.out.print("..."); } public static int doCheck() { return 0; } }
The correct answer is C. Compilation fails.. The 'if' statement condition requires a boolean expression, but the 'doCheck()' method returns an integer, which is a type mismatch, causing a compilation error.
Question
Given:
public class CheckIt { public static void main (String[] args) { if (doCheck()) { System.out.print("square "); } System.out.print("..."); } public static int doCheck() { return 0; } }
Options
- Asquare ...
- B...
- CCompilation fails.
- DAn exception is through at runtime.
How the community answered
(23 responses)- A4% (1)
- C91% (21)
- D4% (1)
Why each option
The 'if' statement condition requires a boolean expression, but the 'doCheck()' method returns an integer, which is a type mismatch, causing a compilation error.
A is incorrect because the code will not compile due to a type mismatch, preventing any runtime output.
B is incorrect for the same reason as A; the code will not compile, so no output is produced.
C is correct because Java's 'if' statement explicitly requires a boolean expression within its parentheses. The 'doCheck()' method returns an 'int' (specifically 0), which Java does not implicitly convert to a boolean value. This fundamental type mismatch is detected by the compiler, preventing the code from running.
D is incorrect because the error is a compile-time type mismatch, not an exception thrown during runtime execution.
Concept tested: Java if-statement boolean condition requirement
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Topics
Community Discussion
No community discussion yet for this question.