Java OCA OCP Practice Question 444

Question

What will be the result of attempting to compile and run the following class?

public class Main{ 
   public static void main (String args [] ){ 
      int i, j, k; 
      i = j = k = 9; 
      System.out.println (i); 
    } 
} 

Select 2 options

  • A. The code will not compile because unlike in c++, operator '=' cannot be chained i.e. a = b = c = d is invalid.
  • B. The code will not compile as 'j ' is being used before getting initialized.
  • C. The code will compile correctly and will display '9' when run.
  • D. The code will not compile as 'j ' and 'i' are being used before getting initialized.
  • E. All the variables will get a value of 9.


Correct Options are  : C E

Note

Every expression has a value, in this case the value of the expression is the value that is assigned to the Right Hand Side of the equation.

k has a value of 9 which is assigned to j and then to i.

Another implication of this is :

boolean b = false; 
if ( b = true)  { 
      System.out.println ("TRUE");
} 

The above code is valid and will print TRUE.

Because b = true has a boolean value, which is what an if statement expects.

if ( i = 5) { ... } is not valid because the value of the expression i = 5 is an int (5) and not a boolean.




PreviousNext

Related