Java Program to Add Two Complex Numbers
A complex number has a real part and an imaginary part and is written a + bi, where i is the square root of -1. For example, 3 + 4i has real part 3 and imaginary part 4.
To add two complex numbers, add the real parts and the imaginary parts separately:
(a + bi) + (c + di) = (a + c) + (b + d)i
For example, (4 + 5i) + (5 + 2i) = 9 + 7i. Java has no built-in complex type, so we create a small class for it.
1. Add Complex Numbers Using a Class
The Complex class stores the two parts. Its add() method returns a new Complex object holding the sum, and toString() controls how the number is printed, including the sign of the imaginary part.
public class ComplexAddition {
static class Complex {
private final double real;
private final double imaginary;
Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
Complex add(Complex other) {
return new Complex(real + other.real, imaginary + other.imaginary);
}
@Override
public String toString() {
String sign = imaginary < 0 ? " - " : " + ";
return real + sign + Math.abs(imaginary) + "i";
}
}
public static void main(String[] args) {
Complex first = new Complex(4, 5);
Complex second = new Complex(5, 2);
System.out.println("(" + first + ") + (" + second + ") = " + first.add(second));
Complex third = new Complex(1.5, -3);
Complex fourth = new Complex(-2, 1);
System.out.println("(" + third + ") + (" + fourth + ") = " + third.add(fourth));
}
}
(4.0 + 5.0i) + (5.0 + 2.0i) = 9.0 + 7.0i (1.5 - 3.0i) + (-2.0 + 1.0i) = -0.5 - 2.0i
2. Add Complex Numbers Using a Record
Since Java 16, a record creates a simple data class in one line, with the constructor and getters written for you. This version also reads the numbers from the user.
import java.util.Scanner;
public class ComplexRecord {
record Complex(double re, double im) {
Complex plus(Complex other) {
return new Complex(re + other.re, im + other.im);
}
@Override
public String toString() {
return re + (im < 0 ? " - " : " + ") + Math.abs(im) + "i";
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter real and imaginary parts of the first number: ");
Complex a = new Complex(scanner.nextDouble(), scanner.nextDouble());
System.out.print("Enter real and imaginary parts of the second number: ");
Complex b = new Complex(scanner.nextDouble(), scanner.nextDouble());
scanner.close();
System.out.println("Sum: " + a.plus(b));
}
}
Enter real and imaginary parts of the first number: 2 7 Enter real and imaginary parts of the second number: 3.5 -4 Sum: 5.5 + 3.0i
3. Summary
- A complex number
a + bihas a real partaand an imaginary partb. - Add complex numbers by adding the real parts and the imaginary parts separately.
- A small class or record with an
add()method models complex numbers cleanly. - Override
toString()to print the number ina + biform.