1.b.
Complex number operations
Date:
Question:
Write a program for complex number operation using constructors.
Aim:
Write a Java program for complex number operation using constructors
Algorithm:
Step 01: Create a ComplexNumber class.
Step 02: Define private instance variables real (real part) and imaginary (imaginary part) to represent
a complex number.
Step 03: Create a constructor ComplexNumber(double real, double imaginary) to initialize the real
and imaginary parts of the complex number.
Step 04: Create a method add(ComplexNumber other) to add two complex numbers by summing
their real and imaginary parts separately.
Step 05: Create a method subtract(ComplexNumber other) to subtract two complex numbers by
subtracting their real and imaginary parts separately.
Step 06: Create a method multiply(ComplexNumber other) to multiply two complex numbers
Step 07: Override the toString() method to provide a readable string representation of a complex
number in the format a + bi.
Step 08: Create another class called ComplexNumberDemo.
Step 09: Inside the ComplexNumberDemo class, create the main() method.
Step 10: Create two objects of the ComplexNumber class, c1 and c2, and initialize them with
example values.
Step 11: Use the add(), subtract(), and multiply() methods on these objects to perform the respective
operations.
Step 12: Print the results of the operations using the toString() method.
Step 13: Save and run the program to verify the results.
Code:
class ComplexNumber {
private double real; // Real part
private double imaginary; // Imaginary part
// Constructor to initialize a complex number
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
// Add two complex numbers
public ComplexNumber add(ComplexNumber other) {
return new ComplexNumber(this.real + other.real, this.imaginary + other.imaginary);
// Subtract two complex numbers
public ComplexNumber subtract(ComplexNumber other) {
return new ComplexNumber(this.real - other.real, this.imaginary - other.imaginary);
// Multiply two complex numbers
public ComplexNumber multiply(ComplexNumber other) {
return new ComplexNumber(
this.real * other.real - this.imaginary * other.imaginary,
this.real * other.imaginary + this.imaginary * other.real
);
// String representation of the complex number
@Override
public String toString() {
return real + " + " + imaginary + "i";
public class ComplexNumberDemo {
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(4.5, 7.2);
ComplexNumber c2 = new ComplexNumber(3.1, 2.8);
System.out.println("Sum: " + c1.add(c2));
System.out.println("Difference: " + c1.subtract(c2));
System.out.println("Product: " + c1.multiply(c2));
}
Output: