OCA Java SE 8 Mock Exam - OCA Mock Question 20








Question

What is the result of the following program?

     1: public class Rectangle { 
     2:   private String color; 
     3:   public Rectangle() { 
     4:     this("white"); 
     5:   } 
     6:   public Rectangle(String color) { 
     7:     color = color; 
     8:   } 
     9:   public static void main(String[] args) { 
     10:    Rectangle e = new Rectangle(); 
     11:    System.out.println("Color:" + e.color); 
     12:   } 
     13: } 
  1. Color:
  2. Color:null
  3. Color:White
  4. Compiler error on line 4.
  5. Compiler error on line 10.
  6. Compiler error on line 11.




Answer



B.

Note

Line 10 calls the constructor from line 3 to line 5.

That constructor calls the other constructor.

The constructor on lines 6?8 assigns the method parameter to itself, which leaves the color instance variable on line 2 set to its default value of null.

The following code rewrites the code in above and shows the output.

public class Main{
  public static void main(String[] args) { 
    Rectangle e = new Rectangle(); 
    System.out.println("Color:" + e.color); 
   }   //from ww  w . j a  va 2  s. c om
}

class Rectangle { 
  public String color; 
  public Rectangle() { 
    this("white"); 
  } 
  public Rectangle(String color) { 
    color = color; 
  } 

} 

The code above generates the following result.