7.9. Answers to sample exam questions

Q7-1.

What is the output of the following code:

class Course {
    String courseName;
    Course() {
        Course c = new Course();
        c.courseName = "Oracle";
    }
}

class EJavaGuruPrivate {
    public static void main(String args[]) {
        Course c = new Course();
        c.courseName = "Java";
        System.out.println(c.courseName);
    }
}
  1. The code will print Java.
  2. The code will print Oracle.
  3. The code will not compile.
  4. The code will throw an exception or an error at runtime.

Answer: d

Explanation: This class will throw a StackOverflowError at runtime. The easiest way to look for a StackOverflowError is to locate recursive method calls. In the question’s code, the constructor of the class Course creates an object of the class Course, which ...

Get OCA Java SE 8 Programmer I Certification Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.