nerdexam
Oracle

1Z0-808 · Question #100

Given the following Java code: public class CheckIt { public static void main (String[] args) { if (doCheck()) { System.out.print("square "); } System.out.print("..."); } public static int doCheck()…

The correct answer is C. An exception is thrown at runtime. The provided answer key appears to contain an error - the actual correct answer is B (Compilation fails). In Java, an if statement requires a strictly boolean expression; unlike C/C++, Java does not allow implicit conversion from int to boolean. Since doCheck() returns int, the…

Using Operators and Decision Constructs

Question

Given the following Java code: public class CheckIt { public static void main (String[] args) { if (doCheck()) { System.out.print("square "); } System.out.print("..."); } public static int doCheck() { return 0; } } What is the result?

Options

  • ASquare ...
  • BCompilation fails.
  • CAn exception is thrown at runtime.
  • D...

How the community answered

(42 responses)
  • A
    2% (1)
  • C
    93% (39)
  • D
    5% (2)

Explanation

The provided answer key appears to contain an error - the actual correct answer is B (Compilation fails).

In Java, an if statement requires a strictly boolean expression; unlike C/C++, Java does not allow implicit conversion from int to boolean. Since doCheck() returns int, the line if (doCheck()) produces a compile-time error: "incompatible types: int cannot be converted to boolean." No bytecode is ever generated, so a runtime exception (C) is impossible - the program never runs.

  • A is wrong because the code never compiles, let alone prints anything.
  • C is wrong because the error is caught by the compiler, not at runtime.
  • D is wrong for the same reason as A - no output is produced.

Memory tip: In Java, if is not C - remember "Java demands boolean, period." Any time you see a non-boolean type (int, Integer, Object) used directly in an if condition without an explicit comparison (== 0, != null, etc.), your first instinct should be compilation failure.

Topics

#type_mismatch#if_statement#boolean_expression#type_compatibility

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice