nerdexam
Oracle

1Z0-803 · Question #121

Given: class App { private boolean flag; public void displayResult() { int result = flag ? 5 : 10; System.out.print("Result = " + result++); } public static void main (String[] args) { new App().displ

The correct answer is D. Result = 10. The code will print 'Result = 10' because the boolean flag defaults to false, assigning 10 to result, and the post-increment operator uses the original value before incrementing.

Using Operators and Decision Constructs

Question

Given:

class App { private boolean flag; public void displayResult() { int result = flag ? 5 : 10; System.out.print("Result = " + result++); } public static void main (String[] args) { new App().displayResult(); } } What is the result?

Options

  • ACompilation fails.
  • BResult = 5
  • CResult = 6
  • DResult = 10
  • EResult = 11

How the community answered

(30 responses)
  • A
    3% (1)
  • B
    10% (3)
  • D
    83% (25)
  • E
    3% (1)

Why each option

The code will print 'Result = 10' because the `boolean flag` defaults to `false`, assigning `10` to `result`, and the post-increment operator uses the original value before incrementing.

ACompilation fails.

The code compiles successfully as there are no syntax errors or type mismatches.

BResult = 5

This would be correct if `flag` were `true`, leading to `result` being initialized to `5`.

CResult = 6

This would be correct if `flag` were `true` and the pre-increment operator `++result` was used, or if `result` was printed after the increment, which is not the case for post-increment.

DResult = 10Correct

When an instance variable `flag` of type `boolean` is not explicitly initialized, it defaults to `false`. The ternary operator `flag ? 5 : 10` then evaluates to `10`, assigning this value to `result`. The post-increment operator `result++` means the current value of `result` (which is `10`) is used for the print statement before `result` is incremented to `11`.

EResult = 11

This would be correct if the `result` was initialized to `10` and `++result` (pre-increment) was used, or if `result` was printed after the increment, but `result++` uses the value *before* incrementing for the expression.

Concept tested: Java default values, ternary operator, post-increment

Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html

Topics

#default values#ternary operator#post-increment operator#primitive data types

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice