Java OCA OCP Practice Question 1758

Question

Which statements are true about the output from the following program?.

public class Main {
  public static void main(String[] args) {
    int i = 0;/*from   ww w . j av  a 2s .  c om*/
    int j = 0;

    boolean t = true;
    boolean r;

    r = (t &  0 < (i+=1));
    r = (t && 0 < (i+=2));
    r = (t |  0 < (j+=1));
    r = (t || 0 < (j+=2));
    System.out.println(i + " " + j);
  }
}

Select the two correct answers.

  • (a) The first digit printed is 1.
  • (b) The first digit printed is 2.
  • (c) The first digit printed is 3.
  • (d) The second digit printed is 1.
  • (e) The second digit printed is 2.
  • (f) The second digit printed is 3.


(c) and (d)

Note

Unlike the & and | operators, the && and || operators short-circuit the evaluation of their operands if the result of the operation can be determined from the value of the first operand.

The second operand of the || operator in the program is never evaluated because of short-circuiting.

All the operands of the other operators are evaluated.

Variable i ends up with the value 3, which is the first digit printed, and j ends up with the value 1, which is the second digit printed.




PreviousNext

Related