Add Complex Numbers Java


 

Add Complex Numbers Java

In this Java Tutorial section, you will learn how to add complex Numbers using Java Program.

In this Java Tutorial section, you will learn how to add complex Numbers using Java Program.

How to Add Complex Numbers Java

In this Java tutorial section, you will learn how to add complex Numbers in Java Programming Language. As you are already aware of Complex numbers. It is composed of two part - a real part and an imaginary part. A "real" part (being any "real" number that you're used to dealing with) and an "imaginary" part (being any number with an "i" in it). The standard format of complex numbers is "a + bi". We have taken two variables a and b.The method getComplexValue() returns string representation of the complex number and the method addition(ComplexNumber num1, ComplexNumber num2) returns the addition of two complex numbers.

Here is the code:

public class ComplexNumber {
	private int a;
	private int b;

	public ComplexNumber() {
	}

	public ComplexNumber(int a, int b) {
		this.a = a;
		this.b = b;
	}

	public String getComplexValue() {
		if (this.b < 0) {
			return a + "" + b + "i";
		} else {
			return a + "+" + b + "i";
		}
	}

	public static String addition(ComplexNumber num1, ComplexNumber num2) {
		int a1 = num1.a + num2.a;
		int b1 = num1.b + num2.b;
		if (b1 < 0) {
			return a1 + "" + b1 + "i";
		} else {
			return a1 + "+" + b1 + "i";
		}
	}

	public static void main(String args[]) {
		ComplexNumber com1 = new ComplexNumber(-2, -3);
		ComplexNumber com2 = new ComplexNumber(-4, -5);
		System.out.println(com1.getComplexValue());
		System.out.println(com2.getComplexValue());
		System.out.println("Addition of Complex Numbers are :"
				+ ComplexNumber.addition(com1, com2));

	}
}


Output

-2-3i
-4-5i
Addition of Complex Numbers are :-6-8i

Ads