Java OCA OCP Practice Question 2075

Question

What will be the output of this program?

class Color {
     int red, green, blue;

     void Color() {
             red = 10;/*from  w  w  w. j  a va 2 s  . c om*/
             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 fine, and when run, it prints the following: red: 0 green: 0 blue: 0
  • C. Compiles fine, and when run, it prints the following: red: 10 green: 10 blue: 10
  • D. Compiles fine, and when run, crashes by throwing NullPointerException


B.

Note

A constructor does not have a return type.

If a return type is provided, it is treated as a method in that class.

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