Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

no errors but there is no output

+3 votes
asked Oct 24, 2022 by Gopi Krishna (400 points)
ublic class Main

{

int a,b,c;

{

c=a+b;

}

void display()

{

System.out.println(c);

}

public static void main(String args[])

{

Main m=new Main();

m.a=10;

m.b=50;

        m.display(); }

}

1 Answer

+1 vote
answered Oct 24, 2022 by Peter Minarik (86,180 points)

The problem is that you set the value of a and b after you've created a new instance of Main, i.e. after the constructor is executed.

You should pass in the values of  a and b to the constructor:

public class Main
{
    int a;
    int b;
    int c;
    
    public Main(int _a, int _b)
    {
        a = _a;
        b = _b;
        c = a + b;
    }

    void display()
    {
        System.out.println(c);
    }

    public static void main(String args[])
    {
        Main m = new Main(10, 50);
        m.display();
    }
}

Note: I do not work with Java and it surprised me that you can define a constructor just by opening a new scope in the class without specifying the function name. Wow.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...