Java Program to Add two Complex Numbers

Last Updated : 23 Jan, 2026

A complex number is a number that consists of two parts: a real part and an imaginary part. It is usually written in the form a + bi, where a is the real part and b is the imaginary part.

Example:

3 + 4i -> Real part = 3, Imaginary part = 4
5 - 2i -> Real part = 5, Imaginary part = -2

Formula to Add Two Complex Numbers

If we have two complex numbers:

  • z₁ = a + bi
  • z₂ = c + di

Then their addition is calculated as:

z₁ + z₂ = (a + c) + (b + d)i

Adding Two Complex Numbers

The addition of two complex numbers is done by adding the real parts and imaginary parts separately:

Java
class ComplexNumber {
    int real, image;

    public ComplexNumber(int r, int i) {
        this.real = r;
        this.image = i;
    }

    public void showC() {
        System.out.print(this.real + " +i" + this.image);
    }

    public static ComplexNumber add(ComplexNumber n1, ComplexNumber n2) {
        ComplexNumber res = new ComplexNumber(0, 0);
        res.real = n1.real + n2.real;
        res.image = n1.image + n2.image;
        return res;
    }

    public static void main(String[] args) {
        ComplexNumber c1 = new ComplexNumber(4, 5);
        ComplexNumber c2 = new ComplexNumber(10, 5);

        System.out.print("First Complex number: ");
        c1.showC();
        System.out.print("\nSecond Complex number: ");
        c2.showC();

        ComplexNumber res = add(c1, c2);
        System.out.print("\nAddition is: ");
        res.showC();
    }
}

Output
First Complex number: 4 +i5
Second Complex number: 10 +i5
Addition is: 14 +i10

Explanation:

  • We create two complex numbers using the constructor.
  • add() method adds the real parts and imaginary parts separately and returns a new ComplexNumber.
  • showC() method prints the complex number in readable format.
  • Time Complexity: O(1) and Auxiliary Space: O(1)
Comment