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

Casting in Java is a fundamental concept that allows one data type to be converted into another. It’s a crucial process to manipulate objects and variables in a program efficiently. In the real world, casting can be akin to converting a measurement from one unit to another, such as inches to centimeters.

In Java, casting is often used when working with polymorphism, when a superclass refers to an object of a subclass. We then need to access the subclass’s specific methods or properties and rely upon casting to achieve the same. This is essential since Java is a strongly typed language and variables are of specific data types.

In this tutorial, let’s take a deep dive into the nuances of these two options, evaluate their purposes, and subsequently highlight the best practices around each option.

2. Define Our Use Case

To illustrate the differences between the cast operator and Class.cast(), we’ll consider a fun use case involving a hierarchy of video game characters.

We’ll create an example with a superclass Character and subclasses Warrior and Commander. Our objective will be to learn how to cast a generic Character object to a specific subclass type to access its unique methods.

The use case involves creating instances of Warrior and Commander. These instances are stored in a list of Character objects. Later, they’re retrieved and cast back to their specific types. This casting allows calling subclass-specific methods.

3. Define Model Classes

Let’s start by defining our first subclass, a Character namely Warrior with a method obeyCommand():

public class Warrior extends Character {
    public void obeyCommand(String command) {
        logger.info("Warrior {} obeys a command {}", this.getName(), command); 
    }
}

Now, let’s create a second subclass of  Character called Commander. This implements an issueCommand() method that issues a command to the warriors:

public class Commander extends Character {
    public void issueCommand(String command) {
        log.info("Commander {} issues a command {}: ", this.getName(), command); 
    }
}

4. The cast Operator

In Java, the cast operator is a straightforward option for converting one object type to another. We use parentheses to specify the target type.

To demonstrate this, let’s write a new class PlayGame that creates several characters (one of each type). Then it attempts to execute a command or issue a random command depending on whether the character is a Warrior or Commander.

Let’s begin by building some characters in a new class PlayGame:

public class PlayGame { 
    public List<Character> buildCharacters() { 
        List<Character> characters = new ArrayList<>(); 
        characters.add(new Commander("Odin")); 
        characters.add(new Warrior("Thor")); 
        return characters; 
    } 
}

We’ll now add the ability to play the game based on each character. Depending on our character, we either execute a given command or issue a new command. Let’s use the cast operator to demonstrate this:

public void playViaCastOperator(List<Character> characters, String command) { 
    for (Character character : characters) {
        if (character instanceof Warrior) { 
            Warrior warrior = (Warrior) character; 
            warrior.obeyCommand(command); 
        }
        else if (character instanceof Commander) { 
            Commander commander = (Commander) 
            character; commander.issueCommand(command); 
        }
    } 
}

In the above code, we used the approach called downcasting, which means we restrict the instance of the parent class to a derived class. This way the available operations are only limited to the derived class’s methods.

Let’s break down our implementation and understand the steps:

  • In our PlayGame class, we define a method playViaCastOperator() which is given a list of characters and a command
  • We iterate through the list of characters and perform specific actions depending on whether the character is a Warrior or a Commander. We use the instanceof keyword to confirm the types
  • If the Character is a Warrior, we use the cast operator (Warrior) to get an instance of Warrior and invoke the obeyCommand() method
  • If the Character is a Commander, we use the cast operator (Commander) to get an instance of Commander and invoke the issueCommand() method

5. The Class.cast() Method

Let’s see how to achieve the same using the Class.cast() method which is part of java.lang.Class.

We’ll now add a playViaClassCast() method to our PlayGame class to see this approach:

public void playViaClassCast(List<Character> characters, String command) {
    for (Character character : characters) {
        if (character instanceof Warrior) {
            Warrior warrior = Warrior.class.cast(character);
            warrior.obeyCommand(command);
        } else if (character instanceof Commander) {
            Commander commander = Commander.class.cast(character);
            commander.issueCommand(command);
        }
    }
}

As we can see, we now use a Class.cast() to cast the Character to either a Warrior or a Commander.

6. Class.cast() vs cast Operator

Let’s now compare the two approaches against various criteria:

Criteria Class.cast() cast operator
Readability and Simplicity Makes the type-casting explicit and clear, especially in complex or generic code where type safety is a concern Used for simple casting operations where the type is known at compile time, favoring readability
Type Safety Provides better type safety by making type checking explicit. This is especially useful in generic programming, where the type is unknown until runtime, ensuring type-safe casting and avoiding class cast issues The cast is partially checked at compile-time. Although the compiler generates errors for clearly incompatible casts, for cases involving generics or inheritance, it may allow the code to compile. In such cases, a ClassCastException can occur at runtime if the cast is invalid.
Performance Adds slight overhead due to the additional method call, but this is usually minor and outweighed by the benefits of type safety in complex scenarios Provides a slight performance advantage as it’s a direct type cast, but the difference is negligible in most practical applications
Code Maintenance Increases clarity in complex or generic codebases, making it easier to maintain and debug type issues Easier to use and understand in simple scenarios, making code maintenance simpler for straightforward casts
Flexibility Better suited for generic programming or frameworks that rely heavily on reflection, ensuring type safety and clarity Not a great choice for generic programming

We should always validate the type before casting via the instanceof  operator to avoid class cast exceptions. Utilizing libraries and frameworks can help handle casting and type-checking more robustly.

7. Conclusion

In this article, we’ve discussed the two casting options in Java and learned about their limitations and advantages using a relevant use case with a practical comparison.

Using the cast operator makes the casting process less verbose. It’s more concise compared to the Class.cast() method. However, both methods have their pros and cons. We need to consider these advantages and disadvantages carefully. The choice depends on our use case and the implementation context.

Considering the criteria listed in the above table, we can always make the right choice for casting.

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