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

When working with objects in Java, understanding the difference between mutable and immutable objects is crucial. These concepts impact the behavior and design of your Java code.

In this tutorial, let’s explore the definitions, examples, advantages, and considerations of both mutable and immutable objects.

2. Immutable Objects

Immutable objects are objects whose state cannot be changed once they are created. Once an immutable object is instantiated, its values and properties remain constant throughout its lifetime.

Let’s explore some examples of built-in immutable classes in Java.

2.1. String Class

The immutability of Strings in Java ensures thread safety, enhances security, and helps with the efficient use of memory through the String Pool mechanism.

@Test
public void givenImmutableString_whenConcatString_thenNotSameAndCorrectValues() {
    String originalString = "Hello";
    String modifiedString = originalString.concat(" World");

    assertNotSame(originalString, modifiedString);

    assertEquals("Hello", originalString);
    assertEquals("Hello World", modifiedString);
}

In this example, the concat() method creates a new String, and the original String remains unchanged.

2.2. Integer Class

In Java, the Integer class is immutable, meaning its values cannot be changed once they are set. However, when you perform operations on an Integer, a new instance is created to hold the result.

@Test
public void givenImmutableInteger_whenAddInteger_thenNotSameAndCorrectValue() {
    Integer immutableInt = 42;
    Integer modifiedInt = immutableInt + 8;

    assertNotSame(immutableInt, modifiedInt);

    assertEquals(42, (int) immutableInt);
    assertEquals(50, (int) modifiedInt);
}

Here, the + operation creates a new Integer object, and the original object remains immutable.

2.3. Advantages of Immutable Objects

Immutable objects in Java offer several advantages that contribute to code reliability, simplicity, and performance. Let’s understand some of the benefits of using immutable objects:

  • Thread Safety: Immutability inherently ensures thread safety. Since the state of an immutable object cannot be modified after creation, it can be safely shared among multiple threads without the need for explicit synchronization. This simplifies concurrent programming and reduces the risk of race conditions.
  • Predictability and Debugging: The constant state of immutable objects makes code more predictable. Once created, an immutable object’s values remain unchanged, simplifying reasoning about code behavior.
  • Facilitates Caching and Optimization: Immutable objects can be easily cached and reused. Once created, an immutable object’s state does not change, allowing for efficient caching strategies.

Therefore, developers can design more robust, predictable, and efficient systems using immutable objects in their Java applications.

3. Creating Immutable Objects

To create an immutable object, let’s consider an example of a class named ImmutablePerson. The class is declared as final to prevent extension, and it contains private final fields with no setter methods, adhering to the principles of immutability.

public final class ImmutablePerson {
    private final String name;
    private final int age;

    public ImmutablePerson(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Now, let’s consider what happens when we attempt to modify the name of an instance of ImmutablePerson:

ImmutablePerson person = new ImmutablePerson("John", 30);
person.setName("Jane"); 

The attempt to modify the name of an ImmutablePerson instance will result in a compilation error. This is because the class is designed to be immutable, with no setter methods allowing changes to its state after instantiation.

The absence of setters and the declaration of the class as final ensure the immutability of the object, providing a clear and robust way to handle a constant state throughout its lifecycle.

4. Mutable Objects

Mutable objects in Java are entities whose state can be modified after their creation. This mutability introduces the concept of changeable internal data, allowing values and properties to be altered during the object’s lifecycle.

Let’s explore a couple of examples to understand their characteristics.

4.1. StringBuilder Class

The StringBuilder class in Java represents a mutable sequence of characters. Unlike its immutable counterpart, String, a StringBuilder allows the dynamic modification of its content.

@Test
public void givenMutableString_whenAppendElement_thenCorrectValue() {
    StringBuilder mutableString = new StringBuilder("Hello");
    mutableString.append(" World");

    assertEquals("Hello World", mutableString.toString());
}

Here, the append method directly alters the internal state of the StringBuilder object, showcasing its mutability.

4.2. ArrayList Class

The ArrayList class is another example of a mutable object. It represents a dynamic array that can grow or shrink in size, allowing the addition and removal of elements.

@Test
public void givenMutableList_whenAddElement_thenCorrectSize() {
    List<String> mutableList = new ArrayList<>();
    mutableList.add("Java");

    assertEquals(1, mutableList.size());
}

The add method modifies the state of the ArrayList by adding an element, exemplifying its mutable nature.

4.3. Considerations

While mutable objects offer flexibility, they come with certain considerations that developers need to be mindful of:

  • Thread Safety: Mutable objects may require additional synchronization mechanisms to ensure thread safety in a multi-threaded environment. Without proper synchronization, concurrent modifications can lead to unexpected behavior.
  • Complexity in Code Understanding: The ability to modify the internal state of mutable objects introduces complexity in code understanding. Developers need to be cautious about the potential changes to an object’s state, especially in large codebases.
  • State Management Challenges: Managing the internal state of mutable objects requires careful consideration. Developers should track and control changes to ensure the object’s integrity and prevent unintended modifications.

Despite these considerations, mutable objects provide a dynamic and flexible approach, allowing developers to adapt the state of an object based on changing requirements.

5. Mutable vs. Immutable Objects

When contrasting mutable and immutable objects, several factors come into play. Let’s explore the fundamental differences between these two types of objects:

Criteria Mutable Objects Immutable Objects
Modifiability Can be changed after creation Remain constant once created
Thread Safety May require synchronization for thread safety Inherently thread-safe
Predictability May introduce complexity in understanding Simplifies reasoning and debugging
Performance Impact Can impact performance due to synchronization Generally has a positive impact on performance

5.1. Choosing Between Mutability and Immutability

The choice between mutability and immutability relies on the application’s requirements. If adaptability and frequent changes are necessary, opt for mutable objects. However, if consistency, safety, and a stable state are priorities, immutability is the way to go.

Consider the concurrency aspect in multitasking scenarios. Immutability simplifies data sharing among tasks without the complexities of synchronization.

Additionally, assess your application’s performance needs. While immutable objects generally enhance performance, weigh whether this boost is more significant than the flexibility offered by mutable objects, especially in situations with infrequent data changes.

Maintaining the right balance ensures your code aligns effectively with your application’s demands.

6. Conclusion

In conclusion, the choice between mutable and immutable objects in Java plays a crucial role in shaping the reliability, efficiency, and maintainability of your code. While immutability provides thread safety, predictability, and other advantages, mutability offers flexibility and dynamic state changes.

Assessing your application’s requirements and considering factors such as concurrency, performance, and code complexity will help in making the appropriate choice for designing resilient and efficient Java applications.

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)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments