Date: 10-02-2026
Roll No. and Name: 24BCE179 DEEP HIRPARA
Course Code and Name: JAVA PROGRAMMING
Practical No: 4
Aim: Create a class called complex for performing arithmetic operations with
complex numbers. Use floating point variables to represent the private data of
the class. Provide a default constructor that initialises the object with some
default values. Provide public member methods for each of the following:
Addition of two complex numbers: It returns the result obtained by adding
the respective real parts and the imaginary parts of the two complex
numbers. The method must return complex class object.
Subtraction of two complex numbers: It returns the result obtained by
subtracting the respective real parts and the imaginary parts of 02 2 the
two complex numbers. The method must return complex class object.
display () – It displays the complex number in a+bi format. The output
should be displayed as follows: - Sum of a1+b1 i & a2+b2 i is: a3+b3 i
// import [Link].*;
class Complex {
private float real;
private float imag;
public Complex(){
[Link] = 0.0f;
[Link] = 0.0f;
}
public Complex(float real,float imag){
[Link] = real;
[Link] = imag;
}
public Complex add(Complex other){
float r = [Link] + [Link];
float i = [Link] + [Link];
return new Complex(r, i);
}
public Complex subtract(Complex other){
float r = [Link] - [Link];
float i = [Link] - [Link];
return new Complex(r, i);
}
public void display(){
[Link]("%.1f + %.1fi", real, imag); // [Link](real + " + " +
imag + "i");
}
}
public class Java4{
public static void main(String[] args){
Complex c1 = new Complex(5.2f,3.1f);
Complex c2 = new Complex(2.1f,1.4f);
Complex sum = [Link](c2);
[Link]("Sum of ");
[Link]();
[Link](" & ");
[Link]();
[Link](" is: ");
[Link]();
[Link]();
Complex diff = [Link](c2);
[Link]("Difference is: ");
[Link]();
}