Java OCA OCP Practice Question 3150

Question

Look at the following code and predict the output:

class Color {
     int red, green, blue;

     Color() {//  ww w.j  a  v a  2  s.c o  m
             Color(10, 10, 10);
     }

     Color(int r, int g, int b) {
             red = r;
             green = g;
             blue = b;
     }

     void printColor() {
             System.out.println("red: " + red + " green: " + green + " blue: " +  blue);
     }

     public static void main(String [] args) {
             Color color = new Color();
             color.printColor();
     }
}
  • A. Compiler error: cannot find symbol.
  • B. Compiles without errors, and when run, it prints the following: red: 0 green: 0 blue: 0.
  • C. Compiles without errors, and when run, it prints the following: red: 10 green: 10 blue: 10.
  • D. Compiles without errors, and when run, crashes by throwing NullPointerException.


A.

Note

The compiler looks for the method Color() when it reaches this statement: Color(10, 10, 10);.

The right way to call another constructor is to use the this keyword as follows: this(10, 10, 10);.




PreviousNext

Related