Skip to main content

Java

Compact Strings in Java: Measured with JOL on JDK 25 (plus Compact Object Headers)

Compact Strings measured with JOL on JDK 25: one million strings weigh 89.8 MB, against 132.0 MB with -XX:-CompactStrings (31.9% less), and one euro sign per string makes them 49% bigger. Includes the Latin-1 vs UTF-16 coder byte, byte[] sizes by length, a JMH comparison and compact object headers (opt-in on JDK 25, default on JDK 27).

Java Stream API: How to Get the Last Element

Java Streams provide elegant ways to process collections, but retrieving the last element isn't as straightforward as calling a getLast() method. Since streams are designed for sequential processing without inherent indexing, developers need specific techniques to fetch the final element efficiently. This guide explores practical approaches to solve this common programming challenge. Whether you're processing large datasets or building concise functional pipelines, understanding these methods will help you write cleaner, more maintainable code. The Core Challenge Unlike List or Deque collections, Java Streams don't maintain bidirectional iteration or direct index access. Once elements pass through the pipeline, they're consumed. This design makes operations like stream().last() impossible without workarounds. However, several clever techniques leverage stream reduction and size information to achieve the desired result. Approach 1: Using reduce() Method The reduce() operation processes each element while retaining only the last one seen. This approach works beautifully for both sequential and parallel streams. import java.util.Optional; import java.util.stream.Stream; public class LastElementWithReduce { public static void main(String[] args) { Stream fruitStream = Stream.of("apple", "banana", "cherry", "date"); Optional lastElement = fruitStream.reduce((first, second) -> second); lastElement.ifPresent(element -> System.out.println("Last fruit: " + element) ); } }

Get Year, Month, Day from Date in Java

Extracting individual date components like year, month, and day is a common requirement in Java applications. Whether you're working with legacy Date objects or modern date-time APIs, this guide will show you multiple approaches to accomplish this task efficiently. 1. Using Calendar Class (Legacy Approach) Before Java 8, the Calendar class was the standard way to extract date fields from a Date object. While it's still supported, this approach is considered outdated and less intuitive than modern alternatives. import java.util.Calendar; import java.util.Date; public class DateExtractor { public static void main(String[] args) { Date currentDate = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(currentDate); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // Months are 0-based int day = calendar.get(Calendar.DAY_OF_MONTH); System.out.println("Year: " + year); System.out.println("Month: " + month); System.out.println("Day: " + day); } } Note: The Calendar.MONTH field returns values from 0 (January) to 11 (December), so you need to add 1 to get the standard 1-12 month numbering.

GraalVM Native Images for Spring Boot 4.1: The Reflection Trap, the Fix, and the Trap Inside the Fix

GraalVM native-image compiles a Spring Boot 4.1 app into a binary that starts in 0.09 seconds instead of 3.5 -- but only after a real ClassNotFoundException, a fix using the tracing agent, and a metadata-collision trap that silently undoes that fix. Rewritten with verified Boot 4.1.1 and current GraalVM versions, honest costs, and where Project Leyden fits as the non-native alternative.

Java 8: Exact Arithmetic Operations in the Math Class

This post has been merged into a newer, more comprehensive guide: Add Two Numbers in Java Without Overflow: addExact, Widening, and BigInteger. It covers the full Math "exact" arithmetic family — addExact, subtractExact, multiplyExact, incrementExact, decrementExact, negateExact, toIntExact, and absExact…

Securing Spring MVC with SiteMinder Pre‑Authentication – A Step‑by‑Step Guide

Enterprise Java applications frequently live behind a corporate Single Sign-On (SSO) gateway such as Broadcom (formerly CA) SiteMinder. SiteMinder authenticates users at the reverse-proxy layer — before any request ever reaches your application server — and then injects the verified identity into a well-known HTTP request header (typically SM_USER). Your Spring Boot application simply trusts that header and builds a security context from it, with no login form and no password handling of its own. This pattern is called pre-authentication: the heavy lifting of credential verification is delegated to an external system, and your app only needs to map the already-authenticated identity to application-level roles. Spring Security has first-class support for this via RequestHeaderAuthenticationFilter and PreAuthenticatedAuthenticationProvider. This tutorial walks through a complete Spring Boot 3.x / Spring Security 6.x configuration, covering Maven dependencies, the security filter chain using the modern lambda DSL, a UserDetailsService implementation, and tips for testing locally without a real SiteMinder agent.

Why You Should Never Use == to Compare Floats and Doubles in Java

Picture this: you’ve written a piece of Java code that performs some calculations. The logic seems flawless. You have an if statement that checks if two double or float values are equal. But for some reason, the check keeps failing, even when you’re sure the numbers should be identical. What’s going on? Welcome to one of the most common pitfalls in programming: comparing floating-point numbers. If you’ve ever written code like if (myDouble == 0.3), you might be in for a surprise. Let’s dive into why this is a bad idea and how to do it correctly. The Hidden Problem with Floating-Point Numbers The root of the issue lies in how computers store fractional numbers. Both float and double types in Java use a binary representation format (specifically, the IEEE 754 standard). The problem is that just like the fraction 1/3 cannot be perfectly represented as a finite decimal (it’s 0.33333…), many decimal fractions cannot be perfectly represented in binary. For example, the number 0.1 in decimal is an infinitely repeating fraction in binary. Because the computer has to truncate this at some point, the value it stores is not exactly 0.1, but a very, very close approximation. When you perform arithmetic with these approximations, the tiny precision errors can add up, leading to unexpected results.

Demystifying Thread Safety in Java: A Practical Guide

Imagine you’re collaborating on a Google Doc. You write a sentence, and at the exact same moment, your colleague deletes the paragraph it’s in. The result? Chaos. A corrupted document, lost work, and confusion. This is precisely what can happen inside your Java application when multiple threads—independent paths of execution—try to access and modify the same data simultaneously. Welcome to the world of concurrency and the critical concept of thread safety. An object or a piece of code is considered “thread-safe” if it continues to function correctly, without causing data corruption or unexpected behavior, even when accessed by multiple threads at the same time. Getting this right is the difference between a robust, predictable application and one that suffers from mysterious, hard-to-reproduce bugs. The Villain of Our Story: The Race Condition The most common concurrency problem is the race condition. It occurs when multiple threads “race” to access and change a shared resource, and the final outcome depends on the unpredictable order in which they execute.

Understanding LinkedHashMap in Java

Let's dive into a fascinating corner of Java’s Collections Framework: the LinkedHashMap. You might already be familiar with HashMap for its speedy key-value pair storage and LinkedHashSet for maintaining insertion order in a set. Well, LinkedHashMap is the best of both worlds, offering the familiar map interface with the added benefit of predictable iteration order. Let’s break down what makes LinkedHashMap so special and when you should consider using it. What is LinkedHashMap? In simple terms, LinkedHashMap is a hash table and a linked list implementation of the Map interface. It inherits all the goodness from HashMap (fast lookups, insertions, and deletions) but adds an internal doubly-linked list that runs through all of its entries. This linked list defines the iteration order, which can either be: Insertion Order: The default behavior, where elements are iterated in the order they were first inserted into the map. Access Order: Elements are iterated in the order they were last accessed (read or written). This is particularly useful for implementing LRU (Least Recently Used) caches. Like HashMap, LinkedHashMap allows one null key and multiple null values. Interface Hierarchy LinkedHashMap implements the following interfaces and extends the following class: java.io.Serializable java.util.Map java.lang.Cloneable And it extends java.util.HashMap.

Using Regular Expressions with Java 8 Predicates for Clean Code

Java 8 introduced some powerful functional interfaces, and one of the most versatile is Predicate. A Predicate represents a boolean-valued function of one argument. While it’s commonly used for simple checks, combining it with regular expressions opens up a world of possibilities for more complex data validation and filtering, all within a concise and readable lambda expression. In this post, we’ll explore how to leverage Java’s Pattern.compile() method to create efficient and reusable regex-based predicates. This approach is particularly useful when you need to perform the same regex validation multiple times, avoiding recompilation overhead for each check. The Problem with Repeated Regex Matching Let’s say you have a list of strings, and you want to filter them based on whether they match a specific regular expression. A naive approach might look something like this: