Header Ads Widget

write a program to implement constructor in java.

 Code:- 

import java.util.Scanner;
class example
{
    int a,b,c;
    public example()
    {
        
        a=2;
        b=2;
        c=3;
    }
    public example(int x,int y,int z)
    {
     a=x;
     b=y;
c=z; 
    }
    public void calculate()
    {
        System.out.print("The sum of "+a+" "+b+" "+c+" is "+(a+b+c));
    }

}
class constructor
{
    public static void main(String args[])
    {
        int x,y,z;
        Scanner sc=new Scanner(System.in);
example obj1=new example();
obj1.calculate();
        x=sc.nextInt();
        y=sc.nextInt();
        z=sc.nextInt();
     example obj=new example(x,y,z);
        obj.calculate();
    }
}

Output:-

The sum of 2 2 3 is 7
8
5
4
The sum of 8 5 4 is 17


Recommended Post:

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-