Category Archives: Java

A Developer’s Guide to Testing Spring REST Clients with @RestClientTest

In modern microservices architecture, it’s rare for a service to live in complete isolation. Most applications need to communicate with other services over the network, typically via REST APIs. When you build a component that consumes an external REST API, a critical question arises: how do you test it reliably without actually making network calls to a live, and potentially unstable, external service?

This is where Spring Boot’s test slices come to the rescue. For testing your REST clients, the framework provides a powerful and elegant solution: the @RestClientTest annotation. Let’s dive deep into how you can use it to write clean, fast, and reliable tests for your HTTP client components.

What Exactly is @RestClientTest?

@RestClientTest is a “test slice” annotation specifically designed to test REST client components. Instead of loading your entire Spring application context (like @SpringBootTest does), it focuses only on the beans relevant to REST client operations. This makes your tests significantly faster and less prone to side effects from unrelated configurations.

When you use @RestClientTest, Spring Boot will auto-configure the following for you:

  • The Client Under Test: The specific REST client bean you want to test.
  • MockRestServiceServer: A bean that lets you mock the server-side responses. You can instruct it: “When my client calls /api/employees/1, respond with this specific JSON.”
  • RestTemplateBuilder: Used to help construct RestTemplate instances.
  • Jackson/Gson Support: It automatically includes support for serializing and deserializing JSON, so you can test your client-side data mapping.

In short, it provides the perfect, minimal environment to verify that your client builds the correct HTTP request and correctly parses the HTTP response — all without a single packet leaving your machine.

Continue reading A Developer’s Guide to Testing Spring REST Clients with @RestClientTest

Dozer Bean Mapping in Java: Practical Guide with Benchmark vs MapStruct

In modern Java applications — particularly those built on Spring Boot or Jakarta EE — moving data between object models is a daily reality. You have DTOs (Data Transfer Objects) arriving from REST APIs and you need to convert them into Domain Entities for persistence, or vice versa. Writing manual getter-setter copy code for every field is tedious, error-prone, and buries your business logic under a mountain of boilerplate that grows with every new field added to your model.

Enter Dozer — a robust, open-source Java Bean mapper that recursively copies data from one object to another using reflection. Dozer has been a production staple for over a decade. While compile-time alternatives like MapStruct have gained popularity for performance-critical applications, Dozer remains a compelling choice for its runtime flexibility, zero build-plugin setup, and its ability to handle complex mapping scenarios without annotation proliferation on your model classes.

In this guide, we will cover practical Dozer usage from basic field mapping through nested objects, custom converters, and Spring integration — then benchmark Dozer against MapStruct so you can make an informed architectural decision for your next project.

Continue reading Dozer Bean Mapping in Java: Practical Guide with Benchmark vs MapStruct

Java HashMap vs ConcurrentHashMap: Complete Interview Guide

In Java collections framework, HashMap and ConcurrentHashMap are two of the most frequently discussed topics in technical interviews. While HashMap provides fast key-value storage for single-threaded environments, ConcurrentHashMap extends these capabilities to support concurrent access. This comprehensive guide covers essential interview questions about both data structures, their internal workings, and key differences.


HashMap Fundamentals

What is HashMap?

HashMap is a hash table based implementation of the Map interface in Java. It stores key-value pairs and provides constant-time performance for basic operations like get() and put() assuming the hash function disperses elements properly. HashMap is part of the Java Collections Framework and resides in java.util package.

How HashMap Works Internally

The internal architecture of HashMap consists of an array of buckets where each bucket is a linked list (or tree in Java 8+) of entries. When you store a key-value pair, HashMap calculates the hash of the key to determine the bucket location. In Java 8+, when a bucket contains too many entries (default threshold is 8), it converts the linked list into a balanced red-black tree for faster lookups.

Continue reading Java HashMap vs ConcurrentHashMap: Complete Interview Guide

How to Check if a Number is a Pronic Number in Java

Whether you are preparing for a technical interview or exploring the fascinating world of number theory, encountering Pronic numbers is almost a rite of passage for Java developers. These numbers, often hidden in pattern-matching puzzles, have unique properties that make them a favorite for practicing algorithmic efficiency.

In this guide, we will dive deep into what Pronic numbers are and demonstrate two distinct ways to identify them using Java—ranging from a beginner-friendly loop to a high-performance mathematical “trick.”


What is a Pronic Number?

A Pronic number (also known as an oblong or rectangular number) is a number that is the product of two consecutive integers. Mathematically, a number P is pronic if it can be expressed as:

P = n X (n + 1)

For some integer n.

Examples of Pronic Numbers:

  • 0: 0 X 1 = 0
  • 2: 1 X 2 = 2
  • 6: 2 X 3 = 6
  • 12: 3 X 4 = 12
  • 20: 4 X 5 = 20
Continue reading How to Check if a Number is a Pronic Number in Java

Disarium Number in Java – Definition, Algorithm, and Complete Program

A Disarium number is a positive integer in which the sum of each digit raised to the power of its position (1-indexed from the left) equals the number itself. For example, 135 qualifies because 1¹ + 3² + 5³ = 1 + 9 + 125 = 135. In this tutorial you will learn exactly what makes a number Disarium, work through a manual verification, study a clean single-pass Java algorithm, and run a complete program that checks individual numbers and prints all Disarium numbers up to 100,000.

Continue reading Disarium Number in Java – Definition, Algorithm, and Complete Program

Log4j2 Logging Levels – Complete Guide

Imagine your application’s log file as a constant stream of information. In a production crisis, this stream becomes a firehose. How do you find the single critical error message in a flood of routine status updates? The answer lies in logging levels.

These aren’t just labels; they are the fundamental control mechanism in Log4j2. They allow developers to filter noise, pinpoint failures, and monitor application health effectively. Mastering this hierarchy is the key to creating logs that are helpful, not overwhelming. This guide explores Log4j2’s levels, from configuration to real-world best practices.


The Logging Threshold: How Levels Work

Think of logging levels as a gatekeeper’s volume knob. Each log message you write (an “event”) is assigned a level of importance, or severity. The logger itself is then configured with a threshold level.

When a message arrives, the framework compares its severity to the logger’s threshold. Only messages at or above the configured threshold are processed and sent to their destination (like a file or the console).

This simple mechanism provides fine-grained control over your application’s verbosity. You can run the exact same code in different environments and get drastically different log outputs—all without changing a single line of Java. In development, you might set the threshold low to see everything. In production, you set it high to capture only significant errors.

Continue reading Log4j2 Logging Levels – Complete Guide

Compact Strings in Java 9: How They Save Memory and Boost Performance

Starting with Java 9, the JVM quietly adopted a new internal representation for the java.lang.String class. The feature is called Compact Strings and, unless you went looking, you probably never noticed the change—yet it can shrink your application’s heap by 10-30% and speed up operations on text-heavy workloads.

This post explains what compact strings are, how this subtle change delivers massive performance wins, and how you can measure the benefit on your own code. Get ready to reclaim your RAM!


The Memory Drain Java 9 Tried to Solve

Prior to JDK 9, every character inside a String was stored as a 16-bit char, using the UTF-16 encoding.

The problem? For common languages like English, or text data formats like XML, JSON, log messages, and HTTP headers, most characters fall within the Latin-1 (ISO-8859-1) set, which perfectly fits into a single 8-bit byte.

This meant that for a vast majority of applications, half of every character array was filled with redundant zeroes. That silent waste translated directly to:

  • Larger Heap Footprint: Your application demands more RAM.
  • More GC Pressure: The Garbage Collector has to work harder and longer.
  • Lower CPU-Cache Locality: Data is scattered, slowing down processing.

While developers could manually pack bytes, it came at the cost of code clarity and API compatibility. Clearly, a JVM-level fix was needed to make string handling efficient by default.

Continue reading Compact Strings in Java 9: How They Save Memory and Boost Performance