Given: 10: public class Hello { 11: String title; 12: int value; 13: public Hello() { 14: title += " World"; 15: } 16: public Hello(int value) { 17: this.value = value; 18: title = "Hello"; 19: Hello(); 20: } 21: } and: 30: Hello c = new Hello(5); 31: System.out.println(c.title); What is the result

  1. Hello

  2. Hello World

  3. Compilation fails

  4. Hello World 5

  5. The code runs with no output.

  6. An exception is thrown at runtime


Correct Option: C

AI Explanation

To answer this question, we need to understand the concept of constructors in Java.

In the given code, we have a class named "Hello" with two constructors: a default constructor (line 13) and a parameterized constructor (line 16).

The default constructor (line 13) initializes the "title" variable by concatenating it with " World". However, since the "title" variable is not initialized before this line, it will result in a NullPointerException at runtime.

The parameterized constructor (line 16) takes an integer value and initializes the "value" variable with it. It also sets the "title" variable to "Hello".

On line 19, the code tries to call the default constructor using the syntax "Hello();". However, in Java, you cannot call a constructor directly like a regular method. The correct way to call a constructor is by using the "new" keyword.

Therefore, the given code will fail to compile with a "Compilation fails" error.

The correct answer is C. Compilation fails.

Find more quizzes: