OCA Java SE 8 Mock Exam Review - OCA Mock Question 25








Question

What is the output of the following code?

class MyClass {
  void print(long duration) {
    System.out.println("long");
  }

  void print(int duration) {
    System.out.println("int");
  }

  void print(String s) {
    System.out.println("String");
  }

  void print(Object o) {
    System.out.println("Object");
  }
}

public class Main {
  public static void main(String args[]) {
    MyClass course = new MyClass();
    char c = 10;
    course.print(c);
    course.print("Object");
  }
}

    a  Compilation error 
    b  Runtime exception 

    c  int 
       String 

    d  long 
       Object 





Answer



C

Note

You can overload methods by changing the type of the method arguments in the list.

In course.print(c) char can be passed to two overloaded print methods that accept int and long.

char is expanded to its nearest type-int so course.print(c) calls the overloaded method that accepts int, printing int.

The code course.print("Object") is passed a String value.

Although String is an Object, this method calls the specific type of the argument passed to it. So course.print("Object") calls the overloaded method that accepts String, printing String.

class MyClass {/*from ww  w. jav a  2s .  co m*/
  void print(long duration) {
    System.out.println("long");
  }

  void print(int duration) {
    System.out.println("int");
  }

  void print(String s) {
    System.out.println("String");
  }

  void print(Object o) {
    System.out.println("Object");
  }
}

public class Main {
  public static void main(String args[]) {
    MyClass course = new MyClass();
    char c = 10;
    course.print(c);
    course.print("Object");
  }
}