Java OCA OCP Practice Question 3148

Question

What will be the output of this program?

class Color {
         int red, green, blue;

         void Color() {
                 red = 10;// w  w w.  ja v a 2  s .com
                 green = 10;
                 blue = 10;
         }

     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: no constructor provided for the class.
  • 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.


B.

Note

Remember that a constructor does not have a return type; if a return type is provided, it is treated as a method in that class.

In this case, since Color had void return type, it became a method named Color() in the Color class, with the default Color constructor provided by the compiler.

By default, data values are initialized to zero, hence the output.




PreviousNext

Related