Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – 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

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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.

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

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

1. Overview

Application size is crucial for start-up time and memory usage, both of which impact performance. Even with today’s powerful hardware, we can significantly reduce an application’s memory footprint through careful coding practices and optimized technical decisions.

The choice of data types, data structures, and class design affects the size of an application. Selecting the most appropriate data types can reduce the cost of running an application in production.

In this tutorial, we’ll learn how to manually estimate the memory size of a Java application, explore various techniques to reduce the memory footprint and use the Java Object Layout (JOL) library to verify our estimations. Finally, because JVMs can have different memory layouts for objects, we’ll use Hotspot JVM. It’s the default JVM in OpenJDK.

2. Maven Dependency

First, let’s add the JOL library to the pom.xml:

<dependency>
    <groupId>org.openjdk.jol</groupId>
    <artifactId>jol-core</artifactId>
    <version>0.17</version>
</dependency>

This library provides classes for analyzing and reporting the memory layout of Java objects. Notably, computing the memory footprint depends on the JVM architecture. Different JVMs may have different object memory layouts.

3. Size of Java Primitives and Objects

The RAM of a system is structured like a table with rows and columns. Each data type occupies a specific number of bits used to estimate memory usage. Java primitive types and objects have different memory representations.

3.1. Memory Word

The memory word represents the amount of data a processor can transfer in a single operation. Based on the system architecture, the memory word size is 4 bytes for a 32-bit system and 8 bytes for a 64-bit system.

When a data type can’t fill the minimal size, it’s rounded up to 4 bytes in a 32-bit system and 8 bytes in a 64-bit system, meaning objects are padded to fit these boundaries.

Understanding this gives us in-depth insight into our program memory usage.

3.2. The Size of an Object

An empty class in Java without any fields contains only metadata. This metadata includes:

  • Mark Word: 8 bytes on a 64-bit system
  • Class Pointer: 4 bytes with compressed oops on 64-bit systems

Thus, the minimum size of an object is 16 bytes with memory alignment on a 64-bit system.

3.3. The Size of Primitive Wrappers

Furthermore, primitive wrappers are objects that encapsulate the primitive types. They consist of an object header, a class pointer, and a primitive field.

Here’s an estimation of their size with the memory padding in a 64 bit-system:

Type Mark Word Class Pointer Primitive Value Memory Padding Total
Byte 8 4 1 3 16
Short 8 4 1 3 16
Characters 8 4 1 3 16
Integer 8 4 4 16
Float 8 4 4 16
Long 8 4 8 4 24
Double 8 4 8 4 24

In the table above, we define the memory size of wrappers by analyzing the components that contribute to their total size.

4. Example Setup

Now that we know how to estimate the memory size of different Java primitives and objects, let’s set up a simple project and estimate its initial size. First, let’s create a class named Dinosaur:

class Dinosaur {
    Integer id;
    Integer age;
    String feedingHabits;
    DinosaurType type;
    String habitat;
    Boolean isExtinct;
    Boolean isCarnivorous;
    Boolean isHerbivorous;
    Boolean isOmnivorous;

    // constructor
}

Next, let’s define a class that represents the Dinosaur taxonomy:

class DinosaurType {
    String kingdom;
    String phylum;
    String clazz;
    String order;
    String family;
    String genus;
    String species;

    // constructor
}

Here, we create a class named DinosaurType that is referenced in the Dinosaur class.

5. Estimating Initial Memory Size

Let’s compute the initial memory size of our application without any optimization yet. First, let’s instantiate the Dinosaur class:

DinosaurType dinosaurType 
  = new DinosaurType("Animalia", "Chordata", "Dinosauria", "Saurischia", "Eusaurischia", "Eoraptor", "E. lunensis");
Dinosaur dinosaur = new Dinosaur(1, 10, "Carnivorous", dinosaurType, "Land", true, false, false, true);

Then, let’s use the JOL library to estimate the size of a dinosaur object:

LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaur).totalSize()));

Estimating the size without optimization gives us 624 bytes. Notably, this could vary based on JVM implementation.

6. Optimizing Initial Memory Size

Now that we have an understanding of the initial memory footprint, let’s explore how we can optimize it.

6.1. Using Primitive Types

Let’s revisit the Dinosaur class and replace primitive wrappers with primitive equivalents:

class Dinosaur {
    int id;
    int age;
    String feedingHabits;
    DinosaurType type;
    String habitat;
    boolean isExtinct;
    boolean isCarnivorous;
    boolean isHerbivorous;
    boolean isOmnivorous;
    // constructor
}

In the code above, we change the types of id, age, isExtinct, isCarnivorous, and other wrappers to use primitive types instead. This action saves us some bytes. Next, let’s estimate the memory size:

LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaur).totalSize()));

Here’s the log output:

[main] INFO com.baeldung.reducememoryfootprint.DinosaurUnitTest -- 552

The new size is 552 bytes compared to the initial 624 bytes. Therefore, using primitive types instead of wrappers saves us 72 bytes.

Furthermore, we can use a short type for Dinosaur age. A short in Java can store up to 32767 whole numbers:

// ...
short age;
// ...

Next, let’s see the console output after using short type for age:

[main] INFO com.baeldung.reducememoryfootprint.DinosaurUnitTest -- 552

From the console output, the memory size is still 552 bytes — no difference in this case. However, we can always use the most narrow type possible for memory efficiency.

In the case of fields like feedingHabits, habitat, and taxonomy information, we retain the String type due to its flexibility. Alternatives like char[] lack the functionality that String provides, such as built-in methods for manipulating text.

To further reduce our memory footprint, we can merge the fields in related classes, consolidating them into a single class. Let’s merge the Dinosaur and DinosaurType classes into a single class:

class DinosaurNew {
    int id;
    short age;
    String feedingHabits;
    String habitat;
    boolean isExtinct;
    boolean isCarnivorous;
    boolean isHerbivorous;
    boolean isOmnivorous;
    String kingdom;
    String phylum;
    String clazz;
    String order;
    String family;
    String genus;
    String species;
    // constructor
}

Here, we create a new class by merging the two initial classes’ fields. This is beneficial since Dinosaur instances have unique taxonomy. Assuming Dinosaur instances share the same taxonomy, this won’t be an efficient approach. It’s crucial to analyze the use case before merging classes.

Next, let’s instantiate the new class:

DinosaurNew dinosaurNew
  = new DinosaurNew(1, (short) 10, "Carnivorous", "Land", true, false, false, true, "Animalia", "Chordata", "Dinosauria", "Saurischia", "Eusaurischia", "Eoraptor", "E. lunensis");

Then, let’s compute the memory size:

LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaurNew).totalSize()));

Here’s the console output:

[main] INFO com.baeldung.reducememoryfootprint.DinosaurUnitTest -- 536

By merging the Dinosaur and DinosaurType classes, we save 16 bytes that would otherwise be used for the object’s mark word, class pointer, and memory padding.

6.3. Bit Packing for Boolean Fields

In a case where we have multiple boolean fields, we can pack them into a single short type. First, let’s define the bit positions:

static final short IS_EXTINCT = 0, IS_CARNIVOROUS = 1, IS_HERBIVOROUS = 2, IS_OMNIVOROUS = 3;

Next, let’s write a method to convert the booleans to short:

static short convertToShort(
  boolean isExtinct, boolean isCarnivorous, boolean isHerbivorous, boolean isOmnivorous) {
    short result = 0;
    result |= (short) (isExtinct ? 1 << IS_EXTINCT : 0);
    result |= (short) (isCarnivorous ? 1 << IS_CARNIVOROUS : 0);
    result |= (short) (isHerbivorous ? 1 << IS_HERBIVOROUS : 0);
    result |= (short) (isOmnivorous ? 1 << IS_OMNIVOROUS : 0);
    return result;
}

The method above takes four boolean parameters and converts them to a single short value where each bit represents a boolean. If the boolean value is true, it shifts 1 to the left by the position of that flag. If the boolean is false, it uses zero with no bits set. Finally, we use the bitwise OR operator to combine all these values.

Also, let’s write a method to convert back to boolean:

static boolean convertToBoolean(short value, short flagPosition) {
    return (value >> flagPosition & 1) == 1;
}

The method above extracts a single boolean value from the packed short.

Next, let’s remove the four boolean fields and replace them with a single short flag:

short flag;

Finally, let’s instantiate the Dinosaur object and compute the memory footprint:

short flags = DinousaurBitPacking.convertToShort(true, false, false, true);
DinousaurBitPacking dinosaur 
  = new DinousaurBitPacking(1, (short) 10, "Carnivorous", "Land", flags, "Animalia", "Chordata", "Dinosauria", "Saurischia", "Eusaurischia", "Eoraptor", "E. lunensis");
 
LOGGER.info("{} {} {} {}", 
  DinousaurBitPacking.convertToBoolean(dinosaur.flag, DinousaurBitPacking.IS_EXTINCT),
  DinousaurBitPacking.convertToBoolean(dinosaur.flag, DinousaurBitPacking.IS_CARNIVOROUS),
  DinousaurBitPacking.convertToBoolean(dinosaur.flag, DinousaurBitPacking.IS_HERBIVOROUS), 
  DinousaurBitPacking.convertToBoolean(dinosaur.flag, DinousaurBitPacking.IS_OMNIVOROUS));
LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaur).totalSize()));

Now, we have a single short value to represent the four boolean values. Here’s the JOL computation:

[main] INFO com.baeldung.reducememoryfootprint.DinosaurUnitTest -- true false false true
[main] INFO com.baeldung.reducememoryfootprint.DinosaurUnitTest -- 528

We’re now down to 528 bytes from 536 bytes.

7. Java Collections

Java Collections have complex internal structures, and computing this structure manually might be tedious. However, we can use the Eclipse Collection library for additional memory optimization.

7.1. Standard Java Collections

Let’s compute the memory footprint of an ArrayList of Dinosaur type:

List<DinosaurNew> dinosaurNew = new ArrayList<>();
dinosaurPrimitives.add(dinosaurNew);
LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaurNew).totalSize()));

The code above outputs 616 bytes to the console.

7.2. Eclipse Collection

Now, let’s use the Eclipse Collection library to reduce the memory footprint:

MutableList<DinosaurNew> dinosaurPrimitivesList = FastList.newListWith(dinosaurNew);
LOGGER.info(String.valueOf(GraphLayout.parseInstance(dinosaurNew).totalSize()));

In the code above, we create a collection of MutableList of Dinosaur using the third-party collection library, which outputs 584 bytes to the console. This means that there’s a 32-byte difference between the standard and Eclipse collections libraries.

7.3. Primitive Collections

Also, the Eclipse Collection provides collections of primitive types. These primitive collections avoid the overhead cost of wrapper classes, leading to substantial memory savings.

Furthermore, libraries like Trove, Fastutil, and Colt provide primitive collections. Also, these third-party libraries are performance-efficient compared to the Java standard collections.

8. Conclusion

In this article, we learned how to estimate the memory size of Java primitives and objects. Also, we estimated the initial memory footprint of an application and then used approaches such as using primitives instead of wrappers, combining classes for related objects, and using narrow types like short to reduce the memory footprint.

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.
Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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.

Course – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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