1Z0-819 · Question #117
What will be the output of this code? var i = 1234; if (i == "1234") { System.out.println("Alpha"); } else if (i == 1234) { System.out.println("Beta"); } else { System.out.println("Gamma"); }
The correct answer is A. Does not compile. Option A is correct because Java is a strictly-typed language - comparing an int (which is what var i = 1234 infers) to a String literal using == is a compile-time type error; the compiler rejects incompatible types before the program ever runs. Options B, C, D, and E are all…
Question
Options
- ADoes not compile
- BPrints "Alpha" only
- CPrints "Alpha" followed by "Beta"
- DPrints "Beta" only
- EPrints "Gamma"
- FThrows an Exception
How the community answered
(25 responses)- A84% (21)
- B4% (1)
- C8% (2)
- E4% (1)
Explanation
Option A is correct because Java is a strictly-typed language - comparing an int (which is what var i = 1234 infers) to a String literal using == is a compile-time type error; the compiler rejects incompatible types before the program ever runs. Options B, C, D, and E are all wrong because they assume the program reaches runtime, which it never does. Options B and C further assume Java performs implicit type coercion like JavaScript (turning 1234 into "1234" for comparison), but Java never coerces primitives to String silently. Option E would only be reachable if both prior conditions were false, which is moot since compilation fails first. Option F (throws an exception) is wrong because type mismatches in Java surface at compile time, not as runtime exceptions.
Memory tip: Java = "type mismatch = won't compile." When you see == comparing two operands of unrelated types (like int vs String), stop - the compiler stops there too. If you'd need a cast or .equals() to make the comparison valid, the raw == won't pass the compiler.
Topics
Community Discussion
No community discussion yet for this question.