Implement Complex Number Class

Here we are going to implement Complex Number class and perform operations on it.

Implement Complex Number Class

You all are aware of Complex Numbers. These numbers consists of two parts,real and imaginary which can be written in the form of a+ib, where a and b are real numbers and i is the imaginary unit with the property i 2 =−1. You can extend them by adding extra numbers. Here we are going to implement Complex Number class and perform operations on it.

Here is the code:

```public class ComplexNumber {
private int a;
private int b;

public ComplexNumber() {
}

public ComplexNumber(int a, int b) {
this.a = a;
this.b = b;
}

public String getComplexValue() {
if (this.b < 0) {
return a + "" + b + "i";
} else {
return a + "+" + b + "i";
}
}

public static String addition(ComplexNumber num1, ComplexNumber num2) {
int a1 = num1.a + num2.a;
int b1 = num1.b + num2.b;
if (b1 < 0) {
return a1 + "" + b1 + "i";
} else {
return a1 + "+" + b1 + "i";
}
}

public static String substraction(ComplexNumber num1, ComplexNumber num2) {
int a1 = num1.a - num2.a;
int b1 = num1.b - num2.b;
if (b1 < 0) {
return a1 + "" + b1 + "i";
} else {
return a1 + "+" + b1 + "i";
}
}

public static String multiplication(ComplexNumber num1, ComplexNumber num2) {
int a1 = num1.a * num2.a;
int b1 = num1.b * num2.b;
int vi1 = num1.a * num2.b;
int vi2 = num2.a * num1.b;
int vi;
vi = vi1 + vi2;
if (vi < 0) {
return a1 - b1 + "" + vi + "i";
} else {
return a1 - b1 + "+" + vi + "i";
}
}

public static void main(String args[]) {
ComplexNumber com1 = new ComplexNumber(-2, -3);
ComplexNumber com2 = new ComplexNumber(-4, -5);
System.out.println(com1.getComplexValue());
System.out.println(com2.getComplexValue());
System.out.println("Addition of Complex Numbers is :"
System.out.println("Subtraction of Complex Numbers is :"
+ ComplexNumber.substraction(com1, com2));
System.out.println("Multiplication of Complex Numbers is :"
+ ComplexNumber.multiplication(com1, com2));
}
}
```

Output:

 -2-3i -4-5i Addition of Complex Numbers is: -6-8i Subtraction of Complex Numbers is: 2+2i Multiplication of Complex Numbers is: -7 + 22i