source file name:  ComplexDemo.java

import java.io.*;

class Complex

{

float x,y;

public Complex()

{

x=y=0;

}

public Complex(float m)

{

x=y=m;

}

public Complex(float m, float n)

{

x=m;

y=n;

}

public void disp()

{

System.out.println(x+"+i "+y);

}


public Complex sum(Complex p, Complex q)

{

Complex r = new Complex();

r.x=p.x+q.x;

r.y=p.y+q.y;

return r;

}

public Complex diff(Complex p, Complex q)

{

Complex r = new Complex();

r.x=p.x-q.x;

r.y=p.y-q.y;

return r;

}

public Complex product(Complex p, Complex q)

{

Complex r = new Complex();

float x=p.x*q.x;

float y=p.y*q.y;

r.x=x-y;

float x1=p.x*q.y;

float y1=p.y*q.x;

r.y=x1+y1;

return r;

}

float realpart()

{

return x;

}

float realimg()

{

return y;

}

}

class ComplexDemo

{

public static void main(String as[])

Complex c1=new Complex();

Complex c2=new Complex(5.8f,10.4f);

Complex c3=new Complex(12.7f,15.6f);

Complex c4=new Complex();

System.out.println("Complex 1 :");

c1.disp();

System.out.println("Complex 2 :");

c2.disp();

System.out.println("Complex 3 :");

c3.disp();

c1=c1.sum(c2,c3);

System.out.println("Complex sum :");

c1.disp();

c4=c4.diff(c2,c3);

System.out.println("Complex difference :");

c4.disp();

c4=c4.product(c2,c3);

System.out.println("Complex product :");

c4.disp();

}

}

output:

D:\JavaPrograms\Constructors>javac ComplexDemo.java

D:\JavaPrograms\Constructors>java ComplexDemo
Complex 1 :
0.0+i 0.0
Complex 2 :
5.8+i 10.4
Complex 3 :
12.7+i 15.6
Complex sum :
18.5+i 26.0
Complex difference :
-6.8999996+i -5.200001
Complex product :
-88.58+i 222.56