โœ๏ธ Explanatory Question

(v) Consider the following Java program and determine its output:

class report 
{
    int a, b;

    report() 
    {
        a = 10;
        b = 15;
    }

    report(int x, int y) 
    {
        a = x;
        b = y;
    }

    void print() 
    {
        System.out.println(a * b);
    }

    public static void main(String[] args) 
    {
        report r = new report();
        r.print();

        report p = new report(4, 5);
        p.print();
    }
}

๐Ÿ‘ 113 Views
๐Ÿ“˜ Detailed Answer
๐ŸŸข Easy
๐Ÿ’ก

Answer with Explanation

Let's analyze the given Java program and determine its output.

Code Analysis:


class report {
    int a, b;

    // Default constructor
    report() {
        a = 10;
        b = 15;
    }

    // Parameterized constructor
    report(int x, int y) {
        a = x;
        b = y;
    }

    // Print method
    void print() {
        System.out.println(a * b);
    }

    public static void main(String[] args) {
        report r = new report();  // Calls default constructor
        r.print();  // Output: 10 * 15 = 150

        report p = new report(4, 5);  // Calls parameterized constructor
        p.print();  // Output: 4 * 5 = 20
    }
}

Execution Steps:

  1. report r = new report();

    • Calls the default constructor, setting a = 10 and b = 15.

    • r.print(); โ†’ 10 * 15 = 150

  2. report p = new report(4, 5);

    • Calls the parameterized constructor, setting a = 4 and b = 5.

    • p.print(); โ†’ 4 * 5 = 20

Final Output:


150
20