eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

In this tutorial, we’ll examine arithmetic operations on complex numbers. Specifically, we’ll explore how to perform addition, subtraction, multiplication, and division of two complex numbers in Java.

2. What Is a Complex Number?

Complex numbers are expressed using a combination of real and imaginary parts. They are generally denoted as a+bi, where a and b are real numbers and i represents the imaginary unit equivalent to the square root of -1. In formal mathematical notation, a is the real part of the complex number, and the term bi is the imaginary component. Complex numbers, although initially confusing for newcomers, play a crucial role in various practical applications, such as physics and mathematics, including fields like quantum mechanics, signal processing, and economics.

Like real numbers, we can perform arithmetic operations such as addition, subtraction, multiplication, and division. Performing arithmetic operations on complex numbers introduces complexities due to the combination of real and imaginary parts. However, specific formulas exist for each of these operations, which streamline them and ensure accurate results.

3. Set Up

We can set up the required foundational code before implementing the arithmetic operations on complex numbers. Let’s start with defining a class for representing complex numbers:

public record ComplexNumber(double real, double imaginary) {
    public static ComplexNumber fromString(String complexNumberStr) {
        Pattern pattern = Pattern.compile("(-?\\d*\\.?\\d+)?(?:([+-]?\\d*\\.?\\d+)i)?");
        Matcher matcher = pattern.matcher(complexNumberStr.replaceAll("\\s", ""));
        if (matcher.matches()) {
            // Extract real and imaginary parts
            String realPartStr = matcher.group(1);
            String imaginaryPartStr = matcher.group(2);
            // Parse real part (if present)
            double real = (realPartStr != null) ? Double.parseDouble(realPartStr) : 0;
            // Parse imaginary part (if present)
            double imaginary = (imaginaryPartStr != null) ? Double.parseDouble(imaginaryPartStr) : 0;
            return new ComplexNumber(real, imaginary);
        } else {
            throw new IllegalArgumentException("Invalid complex number format(" + complexNumberStr + "), supported format is `a+bi`");
        }
    }
    public String toString() {
        return real + "+" + imaginary + "i";
    }

The above class defines the real and imaginary parts of a complex number. We utilized the record keyword to define the class to represent the complex number. Moreover, we defined the toString() method to return the complex number in the typical format of a+bi.

Additionally, the fromString() method is overridden to parse a string representation of a complex number into the ComplexNumber record. We utilized regular expression groups to extract the real and imaginary parts from the string.

In the subsequent sections, we can enhance this record by adding methods to perform various arithmetic operations.

4. Addition of Two Complex Numbers

Now that the basic setup is ready, let’s implement the method for adding two complex numbers. Complex number addition involves adding the real and imaginary parts of two numbers separately to obtain the resultant number. To provide a clearer understanding, let’s establish the addition formula. Let’s look at the formula for addition of two complex numbers:

Addition of Complex Numbers

Let’s translate this formula into Java code and incorporate it into the ComplexNumber record:

public ComplexNumber add(ComplexNumber that) {
    return new ComplexNumber(real + that.real, imaginary + that.imaginary);
}

We can directly access the real and imaginary components from the record and combine them with the given complex number within the method.

5. Subtraction of Two Complex Numbers

Subtracting two complex numbers involves subtracting their real and imaginary parts separately. When subtracting complex numbers a+bi and c+di, we subtract the real parts (a and c) and the imaginary parts (b and d) separately, resulting in a new complex number with the real part as the difference of the original real parts and the imaginary part as the difference of the original imaginary parts. Here is the formula for the subtraction operation:

Subtraction of Two Complex Numbers

Let’s implement the method for subtraction in Java:

public ComplexNumber subtract(ComplexNumber that) {
    return new ComplexNumber(real - that.real, imaginary - that.imaginary);
}

This implements the subtraction using the formula (a-c)+(b-d)i.

6. Multiplication of Two Complex Numbers

Unlike addition and subtraction, multiplication of two complex numbers is not so straightforward. Let’s look at the formula for the multiplication:

Multiplication of Two Complex Numbers

We can translate this formula into Java code and add the method to multiply two complex numbers:

public ComplexNumber multiply(ComplexNumber that) {
    double newReal = this.real * that.real - this.imaginary * that.imaginary;
    double newImaginary = this.real * that.imaginary + this.imaginary * that.real;
    return new ComplexNumber(newReal, newImaginary);
}

The above method implements the algorithm for the complex number multiplication.

7. Division of Two Complex Numbers

Division of two complex numbers is even more complicated than multiplication. It involves a more complex formula:

Division of Two Complex Numbers

Let’s translate this into a Java method:

public ComplexNumber divide(ComplexNumber that) {
    if (that.real == 0 && that.imaginary == 0) {
        throw new ArithmeticException("Division by 0 is not allowed!");
    }
    double c2d2 = Math.pow(that.real, 2) + Math.pow(that.imaginary, 2);
    double newReal = (this.real * that.real + this.imaginary * that.imaginary) / c2d2;
    double newImaginary = (this.imaginary * that.real - this.real * that.imaginary) / c2d2;
    return new ComplexNumber(newReal, newImaginary);
}

The above method effectively divides two complex numbers. It incorporates error handling to prevent division by zero and provides a clear error message in such cases.

8. Testing the Implementation

Now that we have implemented the arithmetic operations on two complex numbers, let’s write test cases for each method. Complex numbers can have various forms, including those with only a real part, only an imaginary part, or both. To guarantee a robust implementation, we must thoroughly test our implementations across all these scenarios. For comprehensive coverage, we can utilize the parameterized tests from JUnit to test different inputs.

To maintain conciseness within this article, we will focus on a single test case demonstrating complex number division:

@ParameterizedTest(name = "Dividing {0} and {1}")
@CsvSource({
    "3+2i, 1+7i, 0.34-0.38i",
    "2, 4, 0.5",
    "2, 4i, 0-0.5i",
    "1+1i, 1+1i, 1",
    "3 +   2i, 1  +   7i, 0.34-0.38i",
    "0+5i, 3+0i, 0+1.6666666666666667i",
    "0+0i, -2+0i, 0+0i",
    "-3+2i, 1-7i, -0.34-0.38i",
    "2+4i, 1, 2+4i"
})
public void givenTwoComplexNumbers_divideThemAndGetResult(String complexStr1, String complexStr2, String expectedStr) {
    ComplexNumber complex1 = ComplexNumber.fromString(complexStr1);
    ComplexNumber complex2 = ComplexNumber.fromString(complexStr2);
    ComplexNumber expected = ComplexNumber.fromString(expectedStr);
    ComplexNumber sum = complex1.divide(complex2);
    Assertions.assertTrue(isSame(sum, expected));
}
public boolean isSame(ComplexNumber result, ComplexNumber expected){
    return result.real() == expected.real() && result.imaginary() == expected.imaginary();
}

In the above implementation, we created a comprehensive test suite using @CsvSource to cover many complex number divisions. A custom utility method, isSame(), is implemented to compare the test results effectively. Similarly, we can implement the tests for other arithmetic operations with the same test parameters.

Additionally, we can also write an individual test to verify the divide-by-zero scenario:

@Test
public void givenAComplexNumberAsZero_handleDivideByZeroScenario() {
    ComplexNumber complex1 = new ComplexNumber(1, 1);
    ComplexNumber zero = new ComplexNumber(0, 0);
    Exception exception = Assertions.assertThrows(ArithmeticException.class, () -> {
        complex1.divide(zero);
    });
    Assertions.assertEquals(exception.getMessage(), "Division by 0 is not allowed!");
}

Here, we create a complex number where the real and imaginary parts are zero and then attempt to divide by it. Using assertThrows(), the test ensures an exception is thrown with the expected error message.

9. Conclusion

In this article, we implemented arithmetic operations on two complex numbers in Java. We explored addition, subtraction, multiplication, and division of complex numbers, implementing robust functionality through extensive test coverage. This includes utilizing parameterized tests to ensure the code functions correctly across various input values.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)