Important Java Concept

Java Program To Add Two Complex Numbers

Complex numbers are the numbers that are expressed in the form of “a+ib”, where a and b are the real numbers (including both rational and irrational numbers) and i is an imaginary number.

The value of ‘i’ in the complex numbers is a square root of -1. To perform the addition of two complex numbers, we need to add the corresponding real and imaginary parts.

class Complex {
    int real;
    int imag;

    public Complex() {

    public Complex(int r, int i) {
        this.real = r;
        this.imag = i;

    public void show() {
        System.out.println(this.real + " + " + this.imag + "i");

    public void sum(Complex c1, Complex c2) {
        real = c1.real + c2.real;
        imag = c1.imag + c2.imag;

public class ComplexNumbers {
    public static void main(String[] args) {
        Complex n1 = new Complex(4, 5);;
        Complex n2 = new Complex(3, 5);;
        Complex n3 = new Complex();
        System.out.println("The sum of two complex numbers is : ");
        n3.sum(n1, n2);;


4 + 5i
3 + 5i
The sum of two complex numbers is :
7 + 10i

Code Explanation:

In the main class, multiple different objects are created to a single class because we are giving complex numbers as input multiple times, and the real and imaginary numbers of a single complex number are passed during the object creation only (i.e., ‘4,5’ and ‘3,5’).

The objects’ names are n1, n2, and n3. In the above program is used to display the complex number based on the input given by the object n1 identically will display another complex number based on the input given by the object n2.

n3.sum() takes two parameters as input let’s say two complex numbers (i.e., n1 and n2) and perform an addition operation and store the result and will show the result (i.e., the addition of two real numbers and two imaginary numbers).


In conclusion, the addition of two complex numbers can be simply stated as the addition of real parts of the two complex numbers and the addition of real numbers in the imaginary part of two complex numbers keeping the ‘i’ constant.

Do you want

Java Tutor?

Aniket Malik

Aniket Malik


🟢 Oracle Certified Java Expert

🟢 300 + ⭐ ⭐ ⭐ ⭐ ⭐

🟢 & in CSE

🟢 6+ Years of Teaching Experience

🟢 Worked as SE in Virtusa and Digidez

Do you want

Java Tutor?