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.

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

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

>> Learn Java Basics

1. Introduction

Enums provide a powerful way to define a set of named constants in the Java programming language. These are useful for representing fixed sets of related values, such as HTTP status codes. As we know, all web servers on the Internet issue HTTP status codes as standard response codes.

In this tutorial, we’ll delve into creating a Java enum that includes all the HTTP status codes.

2. Understanding HTTP Status Codes

HTTP status codes play a crucial role in web communication by informing clients of the results of their requests. Furthermore, servers issue these three-digit codes, which fall into five categories, each serving a specific function in the HTTP protocol.

3. Benefits of Using Enums for HTTP Status Codes

Enumerating HTTP status codes in Java offers several advantages, including:

  • Type Safety: using enum ensures type safety, making our code more readable and maintainable
  • Grouped Constants: Enums group related constants together, providing a clear and structured way to handle fixed sets of values
  • Avoiding Hardcoded Values: defining HTTP status codes as enum helps prevent errors from hardcoded strings or integers
  • Enhanced Clarity and Maintainability: this approach promotes best practices in software development by enhancing clarity, reducing bugs, and improving code maintainability

4. Basic Approach

To effectively manage HTTP status codes in our Java applications, we can define an enum that encapsulates all standard HTTP status codes and their descriptions.

This approach allows us to leverage the benefits of enum, such as type safety and code clarity. Let’s start by defining the HttpStatus enum:

public enum HttpStatus {
    CONTINUE(100, "Continue"),
    SWITCHING_PROTOCOLS(101, "Switching Protocols"),
    OK(200, "OK"),
    CREATED(201, "Created"),
    ACCEPTED(202, "Accepted"),
    MULTIPLE_CHOICES(300, "Multiple Choices"),
    MOVED_PERMANENTLY(301, "Moved Permanently"),
    FOUND(302, "Found"),
    BAD_REQUEST(400, "Bad Request"),
    UNAUTHORIZED(401, "Unauthorized"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found"),
    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    NOT_IMPLEMENTED(501, "Not Implemented"),
    BAD_GATEWAY(502, "Bad Gateway"),
    UNKNOWN(-1, "Unknown Status");

    private final int code;
    private final String description;

    HttpStatus(int code, String description) {
        this.code = code;
        this.description = description;
    }

    public static HttpStatus getStatusFromCode(int code) {
        for (HttpStatus status : HttpStatus.values()) {
            if (status.getCode() == code) {
                return status;
            }
        }
        return UNKNOWN;
    }

    public int getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }
}

Each constant in this Enum is associated with an integer code and a string description. Moreover, the constructor initializes these values, and we provide getter methods to retrieve them.

Let’s create unit tests to ensure our HttpStatus Enum class works correctly:

@Test
public void givenStatusCode_whenGetCode_thenCorrectCode() {
    assertEquals(100, HttpStatus.CONTINUE.getCode());
    assertEquals(200, HttpStatus.OK.getCode());
    assertEquals(300, HttpStatus.MULTIPLE_CHOICES.getCode());
    assertEquals(400, HttpStatus.BAD_REQUEST.getCode());
    assertEquals(500, HttpStatus.INTERNAL_SERVER_ERROR.getCode());
}

@Test
public void givenStatusCode_whenGetDescription_thenCorrectDescription() {
    assertEquals("Continue", HttpStatus.CONTINUE.getDescription());
    assertEquals("OK", HttpStatus.OK.getDescription());
    assertEquals("Multiple Choices", HttpStatus.MULTIPLE_CHOICES.getDescription());
    assertEquals("Bad Request", HttpStatus.BAD_REQUEST.getDescription());
    assertEquals("Internal Server Error", HttpStatus.INTERNAL_SERVER_ERROR.getDescription());
}

Here, we verify that the getCode() and getDescription() methods return the correct values for various HTTP status codes. The first test method checks if the getCode() method returns the correct integer code for each enum constant. Similarly, the second test method ensures the getDescription() method returns the appropriate string description.

5. Using Apache HttpComponents

Apache HttpComponents is a popular library for HTTP communication. To use it with Maven, we include the following dependency in our pom.xml:

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3.1</version>
</dependency>

We can find more details about this dependency on Maven Central.

We can use our HttpStatus enum to handle HTTP responses:

@Test
public void givenHttpRequest_whenUsingApacheHttpComponents_thenCorrectStatusDescription() throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet request = new HttpGet("http://example.com");
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        String reasonPhrase = response.getStatusLine().getReasonPhrase();
        assertEquals("OK", reasonPhrase);
    }
}

Here, we start by creating a CloseableHttpClient instance using the createDefault() method. Moreover, this client is responsible for making HTTP requests. We then construct an HTTP GET request to http://example.com with new HttpGet(“http://example.com”). By executing the request with the execute() method, we receive a CloseableHttpResponse object.

From this response, we extract the status code using response.getStatusLine().getStatusCode(). We then use HttpStatusUtil.getStatusDescription() to retrieve the status description associated with the status code.

Finally, we use assertEquals() to ensure that the description matches the expected value, verifying that our status code handling is accurate.

6. Using RestTemplate Framework

Spring Framework’s RestTemplate can also benefit from our HttpStatus enum for handling HTTP responses. Let’s first include the following dependency in our pom.xml:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>6.1.11</version>
</dependency>

We can find more details about this dependency on Maven Central.

Let’s explore how we can utilize this approach with a simple implementation:

@Test
public void givenHttpRequest_whenUsingSpringRestTemplate_thenCorrectStatusDescription() {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity("http://example.com", String.class);
    int statusCode = response.getStatusCode().value();
    String statusDescription = HttpStatus.getStatusFromCode(statusCode).getDescription();
    assertEquals("OK", statusDescription);
}

Here, we create a RestTemplate instance to perform an HTTP GET request. After obtaining the ResponseEntity object, we extract the status code using response.getStatusCode().value(). We then pass this status code to HttpStatus.getStatusFromCode.getDescription() to retrieve the corresponding status description.

7. Using OkHttp Library

OkHttp is another widely-used HTTP client library in Java. Let’s incorporate this library into the Maven project by adding the following dependency to our pom.xml:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version>
</dependency>

We can find more details about this dependency on Maven Central.

Now, let’s integrate our HttpStatus enum with OkHttp to handle responses:

@Test
public void givenHttpRequest_whenUsingOkHttp_thenCorrectStatusDescription() throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
      .url("http://example.com")
      .build();
    try (Response response = client.newCall(request).execute()) {
        int statusCode = response.code();
        String statusDescription = HttpStatus.getStatusFromCode(statusCode).getDescription();
        assertEquals("OK", statusDescription);
    }
}

In this test, we initialize an OkHttpClient instance and create an HTTP GET request using Request.Builder(). We then execute the request with the client.newCall(request).execute() method and obtain the Response object. We extract the status code using the response.code() method and pass it to the HttpStatus.getStatusFromCode.getDescription() method to get the status description.

8. Conclusion

In this article, we discussed using Java enum to represent HTTP status codes, enhancing code readability, maintainability, and type safety.

Whether we opt for a simple enum definition or use it with various Java libraries like Apache HttpComponents, Spring RestTemplate Framework, or OkHttp, Enums are robust enough to handle fixed sets of related constants in Java.

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.

Course – LS – NPI (cat=REST)
announcement - icon

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

>> CHECK OUT THE COURSE

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