Java Complex Number Class with Arithmetic (partial)
🧩 Syntax:
public class Complex implements Comparable<Complex>, Cloneable {
private double a; // real part
private double b; // imaginary part
// Constructor
public Complex(double a, double b) {
this.a = a;
this.b = b;
}
// Getters
public double getRealPart() { return a; }
public double getImaginaryPart() { return b; }
// Arithmetic operations
public Complex add(Complex other) {
return new Complex(this.a + other.a, this.b + other.b);
}
public Complex subtract(Complex other) {
return new Complex(this.a - other.a, this.b - other.b);
}
public Complex multiply(Complex other) {
double real = this.a * other.a - this.b * other.b;
double imag = this.a * other.b + this.b * other.a;
return new Complex(real, imag);
}
public Complex divide(Complex other) {
double denominator = other.a * other.a + other.b * other.b;
double real = (this.a * other.a + this.b * other.b) / denominator;
double imag = (this.b * other.a - this.a * other.b) / denominator;
return new Complex(real, imag);
}
// Absolute value
public double abs() {
return Math.sqrt(a * a + b * b);
}
// toString
@Override
public String toString() {
if (b >= 0) return a + " + " + b + "i";
else return a + " - " + (-b) + "i";
}
// equals
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Complex)) return false;
Complex other = (Complex) obj;
return this.a == other.a && this.b == other.b;
}
// compareTo (by absolute value)
@Override
public int compareTo(Complex other) {
return Double.compare(this.abs(), other.abs());
}
// clone
@Override
public Complex clone() {
try {
return (Complex) super.clone();
} catch (CloneNotSupportedException e) {
return new Complex(this.a, this.b);
}
}
}