Analyze the following code. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Test1 extends JFrame { public Test1() { add(new MyCanvas()); } public static void main(String[] args) { JFrame frame = new Test1(); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } class MyCanvas extends JPanel { private String message; public void setMessage(String message) { this.message = message; } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(message, 20, 20); } }

Analyze the following code.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test1 extends JFrame {
  public Test1() {
    add(new MyCanvas());
  }

  public static void main(String[] args) {
    JFrame frame = new Test1();
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}

class MyCanvas extends JPanel {
  private String message;

  public void setMessage(String message) {
    this.message = message;
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    g.drawString(message, 20, 20);
  }
}

A. The program runs fine and displays nothing since you have not set a string value.
B. The program would display Welcome to Java! if you replace new MyCanvas() by new MyCanvas("Welcome to Java!").
C. The program has a compile error because new Test1() is assigned to frame.
D. The program has a NullPointerException since message is null when g.drawString(message, 20, 20) is executed.

The correct answer is D

Explanation: (B) is incorrect since MyCanvas does not have a constructor with a string argument. (C) is incorrect since new Test1() is an instance of JFrame so it is fine to assign it to frame.


Java

Learn More Multiple Choice Question :