Java OCA OCP Practice Question 1728

Question

What will be the result of compiling and running the following program?.

public class Main {
  public static void main(String[] args) {
    int a, b, c;
    b = 10;
    a = b = c = 20;
    System.out.println(a);
  }
}

Select the one correct answer.

  • (a) The program will fail to compile since the compiler will report that the variable c in the multiple assignment statement a = b = c = 20; has not been initialized.
  • (b) The program will fail to compile, because the multiple assignment statement a = b = c = 20; is illegal.
  • (c) The code will compile and print 10, when run.
  • (d) The code will compile and print 20, when run.


(d)

Note

An assignment statement is an expression statement.

The value of the expression statement is the value of the expression on the right-hand side.

Since the assignment operator is right associative, the statement a = b = c = 20 is evaluated as follows: (a = (b = (c = 20))).

This results in the value 20 being assigned to c, then the same value being assigned to b and finally to a.

The program will compile, and print 20, when run.




PreviousNext

Related