Java: Practical How-to Articles

158 practical Java articles covering Basics, Strings, Collections, IO, Advanced patterns, Modern Java from Java 8 through Java 24, Testing with JUnit 5, Mockito, AssertJ, WireMock and Testcontainers, Reactive Programming with Project Reactor, JVM Performance & Profiling, JDBC database access, Networking, Cryptography, Concurrency Primitives, XML Processing, and JSON with Jackson. Each article focuses on one topic with working code examples, pitfalls, and best-practice guidance.

Share
Beginner Intermediate Advanced

Java Basics

26 articles
Java Data Types

Primitive types (int, long, double, boolean, char), wrapper classes, autoboxing, and type casting with examples.

Bitwise Operators

AND, OR, XOR, NOT, left/right shift operators with bit-level examples and practical use cases.

Java Math Class: Methods and Safe Arithmetic

abs, min, max, pow, sqrt, floor, ceil, round, log, random, ThreadLocalRandom, and overflow-safe exact methods that throw instead of silently wrapping.

equals() and hashCode(): Contract and Best Practices

The equals-hashCode contract, why they must be consistent, IDE generation, and Records as the modern approach.

Control Flow: if, switch, loops

if/else, switch expressions, for, while, do-while, for-each, break/continue, and labeled jumps.

Arrays: Declaration, Init, and Utilities

Single and multi-dimensional arrays, Arrays.sort, Arrays.copyOf, Arrays.fill, binarySearch, and common pitfalls.

Exception Handling: try, catch, finally

Exception hierarchy, multi-catch, exception chaining, try-with-resources, and writing custom exceptions.

var: Local Type Inference

Where var is allowed, where it isn't, var with generics, and best-practice guidelines for readable code.

Interfaces: Default, Static and Private Methods

default methods (Java 8+), static interface methods, private methods (Java 9+), functional interfaces, and abstract class vs interface.

Generics: Bounded Types and Wildcards

Generic classes and methods, upper bounded wildcards (extends), lower bounded wildcards (super), unbounded wildcards, and multiple bounds.

Enums: Fields, Methods and Patterns

Enum with fields and constructor, enum methods, abstract methods per constant, switch on enum, and iterating values().

Inner Classes: Static, Anonymous and Local

Static nested class, non-static inner class, local class inside methods, anonymous class, and when to use each vs lambdas.

Autoboxing, Unboxing and the Integer Cache

How autoboxing and unboxing work, the Integer cache range (-128 to 127), == vs equals() pitfall, and NullPointerException from null unboxing.

Immutability in Java

What immutability means, why it matters for thread safety and HashMap keys, String internals, the final keyword, building a custom immutable class with defensive copies, and Records.

Date & Time API: LocalDate, ZonedDateTime, Instant

The java.time package: LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant, Duration, Period, DateTimeFormatter, TemporalAdjusters, and legacy interop.

Inheritance & Polymorphism

extends, method overriding, @Override, super keyword, constructor chaining, dynamic dispatch, covariant return types, method hiding, and the Liskov Substitution Principle.

The final Keyword in Depth

final local variables, blank finals, final fields, final parameters, effectively final, final methods (no override), final classes (no extend), and Java Memory Model guarantees.

try-with-resources & AutoCloseable

Automatic resource management, AutoCloseable vs Closeable, multiple resources and close order, suppressed exceptions, custom closeable types, and the nested-constructor pitfall.

Access Modifiers: public, protected, private & package-private

Visibility rules for all four access levels, class-level modifiers, the overlooked package-private default, and API design guidelines.

The static Keyword in Depth

Static fields, static methods, static initializer blocks, initialization order, static nested classes, and common pitfalls including memory leaks and thread safety.

Abstract Classes: Template Method, Constructors & Best Practices

abstract keyword, abstract methods, constructor chaining, Template Method pattern, shared state, and the definitive abstract class vs interface decision guide.

Java BigDecimal & BigInteger: Precise Arithmetic

Precise decimal arithmetic, rounding modes, scale, division pitfalls, money handling, and cryptographic integer math with examples.

Lambda Expressions & Method References

Lambda syntax, variable capture, effectively final, the four kinds of method references, and best practices with examples.

The Object Class in Depth

toString, equals, hashCode, getClass, clone, wait/notify/notifyAll, and finalize: the methods every Java object inherits and when to override them.

Varargs: Variable-Length Argument Lists

The ... syntax, how varargs become arrays inside the method, ordering rules, overload resolution priority, passing existing arrays, and @SafeVarargs for generic varargs.

Type Casting: Widening, Narrowing, instanceof & ClassCastException

Automatic widening conversions, explicit narrowing with data-loss risks, safe reference downcasting with instanceof, pattern-matching instanceof, and array covariance pitfalls.

Java Strings

17 articles
String: substring()

Extracting substrings by index and range, index bounds, and common one-liner patterns.

String: indexOf()

Finding first and last occurrences, searching from a position, and indexOf vs contains comparison.

String: intern()

The string pool, how intern() works, memory implications, and when to use or avoid interning.

Remove Whitespace from a String

trim(), strip(), stripLeading/Trailing (Java 11+), replaceAll with regex, and blank-line removal.

split(): Splitting Strings

Splitting with delimiters and regex patterns, limit parameter, empty tokens, and edge cases.

replace() and replaceAll()

Character replacement, substring replacement, regex-based replaceAll, and back-references.

String Formatting: format, printf, formatted()

Format specifiers (%s, %d, %f), width and alignment, formatted() Java 15+, and locale-aware formatting.

String Comparison: equals, compareTo, Collator

equals vs ==, equalsIgnoreCase, compareTo, Collator for locale-aware sorting, and null-safe patterns.

Regular Expressions: Pattern and Matcher

Pattern.compile, Matcher.find/matches, capturing groups, named groups, flags, and common patterns.

StringBuilder and StringBuffer

append, insert, delete, replace, reverse, capacity management, and when to choose StringBuffer.

String Utility Methods: join(), repeat(), chars(), strip()

String.join() with delimiter, repeat() (Java 11+), strip() vs trim(), chars() stream, isBlank(), and toUpperCase/toLowerCase with Locale.

Charset and Encoding: UTF-8, Bytes and String Conversion

String.getBytes(charset), new String(bytes, charset), StandardCharsets constants, encoding pitfalls, and reading/writing files with explicit charset.

String Tokenizing: StringTokenizer vs split vs Scanner

split() with regex and limit, StringTokenizer (legacy), Scanner for token-by-token reading, and handling empty tokens.

Java String Performance: Concatenation, Interning & Best Practices

String immutability overhead, intern() costs, StringBuilder vs String concatenation, compact strings, and performance tips.

StringJoiner, String.join() and Collectors.joining()

Building delimited strings with delimiter, prefix and suffix: StringJoiner for incremental building, String.join() for one-liners, Collectors.joining() for streams.

Number–String Conversion: parseInt, valueOf, toString & NumberFormat

Parsing strings to numbers (parseInt, parseDouble, valueOf), converting numbers to strings (toString, format), handling NumberFormatException, and locale-aware formatting with NumberFormat and DecimalFormat.

String Characters: charAt, chars(), toCharArray & Character Class

Accessing individual characters with charAt, stream-based processing with chars() and codePoints(), mutable char[] with toCharArray, Character classification methods, and the Unicode supplementary character trap.

Java Collections

30 articles
List6
Looping Through a List

for, for-each, Iterator, ListIterator, stream forEach: patterns and when to use each.

Removing Elements from a List

remove by index, remove by value, removeIf, removeAll, avoiding IndexOutOfBoundsException.

Remove While Iterating a List

ConcurrentModificationException explained, safe removal with Iterator.remove() and removeIf.

Filter and Collect from a List

Stream filter + collect patterns, custom Collectors, and filtering into multiple groups.

Filter and Find in a List

findFirst, findAny, anyMatch, allMatch, noneMatch: short-circuit stream terminal operations.

Manipulate List Items with Lambda

replaceAll, removeIf, forEach, sort: declarative in-place list manipulation patterns.

ArrayList vs LinkedList: When to Use Each

Internal data structures, time complexity of get/add/remove, cache locality explained, why ArrayList wins most benchmarks, and the narrow cases where LinkedList is appropriate.

Advanced Map API: computeIfAbsent, merge, getOrDefault & replaceAll

Java 8 Map default methods that replace verbose get-check-put patterns: getOrDefault, putIfAbsent, computeIfAbsent for lazy init, merge for counters and accumulators, compute, computeIfPresent, and replaceAll.

Map7
Looping Through a Map

entrySet, keySet, forEach, stream on entries: iteration patterns and performance notes.

Removing Entries from a Map

remove by key, remove if value matches, entrySet.removeIf, and ConcurrentHashMap patterns.

Convert List to Map with Streams

Collectors.toMap, handling duplicate keys with merge functions, and downstream collectors.

Convert Map to List with Streams

Extracting key/value lists, mapping entries to objects, and sorting the resulting list.

TreeMap and LinkedHashMap

Sorted keys and range queries with TreeMap's NavigableMap, insertion-order LinkedHashMap, and LRU cache pattern.

WeakHashMap and IdentityHashMap

WeakHashMap keys held by weak references for cache use cases, IdentityHashMap using == for key comparison, and when to use each.

NavigableMap and NavigableSet: floor, ceiling, range queries

floorKey, ceilingKey, lowerKey, higherKey, headMap, tailMap, subMap on TreeMap, and NavigableSet range operations on TreeSet.

Set, Queue & Deque3
Set: HashSet, LinkedHashSet, TreeSet

O(1) HashSet, insertion-order LinkedHashSet, sorted TreeSet, and union/intersection/difference operations.

Queue and Deque: ArrayDeque, PriorityQueue

FIFO queues, LIFO stacks with ArrayDeque, priority-ordered PriorityQueue, and BlockingQueue for concurrency.

EnumMap and EnumSet

Bit-vector EnumSet for flags, enum-keyed EnumMap: faster and more memory-efficient than HashMap.

Iterators, Sorting & Utilities6
Iterator vs ListIterator

Key differences, bidirectional traversal, add/set during iteration, and when to prefer each.

Sorting: Comparable and Comparator

Natural order with Comparable, custom order with Comparator, thenComparing, reversed, and nullsFirst/Last.

Collections Utility Class

sort, reverse, shuffle, binarySearch, min/max, frequency, unmodifiableList, synchronizedList.

CopyOnWriteArrayList and Concurrent Collections

Thread-safe list for read-heavy workloads, ConcurrentHashMap, and choosing the right concurrent collection.

Stream API: filter, map, reduce, collect

The Java Stream API: creating streams, filter, map, reduce, collect, sorted, primitive streams, parallel streams, and best practices.

Stream groupingBy and partitioningBy

Collectors.groupingBy() with downstream collectors (counting, mapping, joining), multi-level grouping, and partitioningBy for true/false splits.

flatMap: Flattening Nested Streams and Collections

Stream.flatMap() vs map(), flattening List-of-Lists, flatMap with Optional (Java 9+), and mapMulti() alternative (Java 16+).

Java ConcurrentHashMap: Thread-Safe Maps

ConcurrentHashMap internals, segment locking, atomic compute methods, bulk operations, and comparison with synchronized maps.

Java Immutable Collections: List.of, Map.of, Set.of

Immutable collection factories (Java 9+), Collections.unmodifiable wrappers, copyOf, and defensive copying best practices.

HashMap Internals: Hashing, Buckets & Performance

Bucket array structure, hash computation, collision chaining, Java 8 treeification, load factor and resize, equals/hashCode contract for keys, and ConcurrentModificationException.

PriorityQueue: Heaps & Priority-Based Processing

Binary heap internals, min-heap by default, max-heap with Comparator, offer/poll/peek, time complexity, top-K patterns, merging sorted sequences, and PriorityBlockingQueue.

Comparable & Comparator: Natural and Custom Ordering

Implementing Comparable for natural ordering, building Comparator chains with comparing() and thenComparing(), reversing, null handling, and TreeSet/TreeMap ordering.

Java IO

16 articles
Reading a Text File

BufferedReader, Files.readAllLines, Files.lines stream: patterns for small and large files.

Writing a Text File

BufferedWriter, FileWriter, Files.write, append mode, and charset handling.

File Open Options (StandardOpenOption)

CREATE, APPEND, TRUNCATE_EXISTING, READ, WRITE, SYNC: NIO open option flags explained.

Reading Large Files Efficiently

Stream-based processing, memory-mapped files, chunked reading, and avoiding OutOfMemoryError.

NIO.2 Path and Files API

Path manipulation, Files.copy/move/delete, directory walking, attribute reading, and WatchService.

WatchService: Filesystem Change Monitoring

Register directories for create/modify/delete events, event polling loop, and cross-platform notes.

Buffered Streams: BufferedReader and BufferedWriter

Why buffering matters, readLine, newLine, BufferedInputStream/OutputStream, and NIO Files convenience methods.

Object Serialization

Serializable, transient, serialVersionUID, custom readObject/writeObject, Externalizable, and security risks.

HttpClient: Modern HTTP Requests

GET/POST, async CompletableFuture, timeouts, redirect handling, body handlers, and BodyPublishers.

ZIP and GZIP Compression

Creating and extracting ZIP archives, GZIP single-file compression, NIO ZipFileSystem, and Zip Slip prevention.

Properties Files: Reading and Writing .properties

Properties.load(), getProperty() with defaults, loading from classpath, storing properties, and System.getProperties().

Files.walk and DirectoryStream: Traversing Directories

Files.walk() with stream filter, walkFileTree() with FileVisitor, DirectoryStream for single-level listing, and glob patterns.

Loading Resources from Classpath

getClass().getResourceAsStream(), ClassLoader.getResourceAsStream(), reading as String, Properties, or BufferedReader, and path prefix rules.

Java NIO: Channels & Buffers

FileChannel for fast file I/O, ByteBuffer operations, scatter/gather, zero-copy transferTo, SocketChannel, Selector, and memory-mapped files.

Reading Input: Scanner and Console

Scanner for stdin and file token parsing, typed nextInt/nextDouble, the nextLine-after-nextInt pitfall, Console for echo-free password input, and Scanner vs BufferedReader comparison.

RandomAccessFile: Seek, Read and Write at Arbitrary Positions

File pointer, seek(), typed reads/writes, fixed-length record files with O(1) access by index, in-place updates, open modes (r/rw/rws/rwd), and comparison with FileChannel.

Advanced

30 articles
Optional: Avoiding null

Creating Optional, map/flatMap/filter, orElse/orElseGet/orElseThrow, and Optional anti-patterns to avoid.

Memory Management: Heap, GC, Memory Leaks

Heap and stack, GC algorithms (G1, ZGC, Shenandoah), object lifecycle, and diagnosing memory leaks.

Functional Interfaces: Function, Predicate, Consumer

java.util.function interfaces, composition with andThen/compose, chaining Predicates, and custom interfaces.

Advanced Stream Collectors

groupingBy, partitioningBy, teeing, collectingAndThen, and building fully custom Collectors.

CompletableFuture: Async Pipelines

thenApply, thenCompose, thenCombine, allOf, anyOf, error handling with exceptionally and handle.

ByteBuffer: NIO High-performance IO

Direct vs heap buffers, flip/clear/compact, channel integration, and byte order handling.

Reference Types: Weak, Soft, Phantom

WeakReference for caches, SoftReference for memory-sensitive caches, PhantomReference for cleanup.

ThreadLocal and ScopedValue

Per-thread state with ThreadLocal, InheritableThreadLocal, and the modern ScopedValue (Java 21+).

StampedLock: Optimistic Reads

Write/read/optimistic-read modes, tryConvertToWriteLock, and comparison with ReentrantReadWriteLock.

VarHandle: Atomic Field Access

compareAndSet, getAndAdd, memory ordering (acquire/release/volatile), replacing Unsafe patterns.

ServiceLoader: Plugin and SPI Mechanism

Defining service interfaces, registering providers, loading at runtime, and module-system integration.

Cleaner API: Post-GC Resource Cleanup

Registering cleaners for native/off-heap resources, phantom-reference semantics, and Cleaner vs finalize().

MethodHandles: JVM-native Invocation

findVirtual, findStatic, lookup, invokeExact, and MethodHandle as a fast alternative to reflection.

Reflection: Class Introspection

Class objects, getDeclaredFields/Methods, setAccessible, Method.invoke, dynamic instantiation, and limitations.

Annotations: @interface, Retention, ElementType

Creating custom annotations, meta-annotations, reading at runtime with reflection, and repeatable annotations.

ExecutorService: Thread Pools and Future

Fixed/cached/single thread pools, Callable, Future, invokeAll/invokeAny, ScheduledExecutorService, and shutdown.

ReentrantLock and Condition

tryLock with timeout, lockInterruptibly, Condition await/signal, ReadWriteLock, and synchronized comparison.

synchronized, volatile and the Java Memory Model

happens-before relationship, synchronized blocks and methods, volatile visibility guarantee, double-checked locking, and common concurrency bugs.

Atomic Classes: AtomicInteger, AtomicReference and CAS

AtomicInteger operations (getAndIncrement, compareAndSet), AtomicReference, LongAdder for high-contention counters, and lock-free patterns.

ThreadPoolExecutor: Custom Thread Pool Configuration

corePoolSize, maxPoolSize, queue types (LinkedBlockingQueue, SynchronousQueue), rejection policies, monitoring, and graceful shutdown.

Type Erasure: How Generics Work at Runtime

Generic types erased to raw types at bytecode level, bridge methods, instanceof limitations, heap pollution, and Class<T> token workaround.

Design Patterns: Strategy, Observer, Factory & More

Seven essential patterns with modern Java implementations: lambdas, sealed interfaces, records, and functional composition.

Garbage Collection & JVM Memory Model

JVM memory areas, generational collection, G1, ZGC, Shenandoah, GC tuning flags, and detecting memory leaks with jmap and heap dumps.

Fork/Join Framework & RecursiveTask

Parallel divide-and-conquer with ForkJoinPool, RecursiveTask, RecursiveAction, work stealing, threshold tuning, and common pitfalls.

Java Class Loading: Bootstrap, Platform & Custom ClassLoaders

Parent-delegation model, built-in classloaders, writing a custom ClassLoader, URLClassLoader for JAR plugins, class isolation, and memory leak prevention.

Bytecode & Instrumentation: javap, Java Agents & Byte Buddy

Read bytecode with javap, write Java agents with Instrumentation API, transform classes with ASM ClassFileTransformer, and use Byte Buddy for high-level weaving.

Java Security: KeyStore, TrustManager & TLS

Load and create PKCS12 keystores, build SSLContext, configure mutual TLS (mTLS), certificate pinning, and secure HttpClient connections.

Java Flight Recorder (JFR): Profiling & JMC

Built-in JVM events, custom JFR events, programmatic Recording API, live streaming with RecordingStream, and analysing recordings in Java Mission Control.

Java Dynamic Proxy: Proxy, InvocationHandler & Practical Patterns

Runtime-generated proxies that implement interfaces: Proxy.newProxyInstance(), InvocationHandler, logging proxy, retry proxy, and limitations vs CGLIB.

ProcessBuilder & Process API: Running OS Commands from Java

Launch external processes, capture stdout/stderr, send stdin, avoid the deadlock trap, ProcessHandle for PID queries and lifecycle events, and process pipelines.

Implementing Iterable and Iterator: Custom For-Each Support

Make custom classes work in for-each loops: Iterable and Iterator contracts, lazy and infinite iterators, fail-fast modification detection, and Spliterator for parallel stream support.

Modern Java

20 articles
Records: Immutable Data Classes

Canonical constructor, compact constructor, implementing interfaces, serialization, and when to use records.

Sealed Classes and Interfaces

Restricting subclasses with permits, sealed + pattern matching synergy, and exhaustive switch.

Text Blocks: Multi-line Strings

Triple-quoted strings, incidental whitespace handling, \\ line continuation, and text block + formatted().

Switch Expressions: Arrow Syntax and yield

Arrow case labels, yield for multi-statement arms, exhaustiveness, and switch as an expression.

Pattern Matching for instanceof

Combining type test and cast in one expression, binding variables, and simplifying type-dispatch code.

Pattern Matching for switch

Type patterns, guarded patterns, null handling in switch, and exhaustiveness with sealed hierarchies.

Record Patterns: Destructuring in switch

Deconstructing records in instanceof and switch, nested patterns, and combining with sealed classes.

Virtual Threads: Project Loom

Lightweight threads for I/O-bound workloads, Thread.ofVirtual, ExecutorService integration, and structured concurrency.

Sequenced Collections

SequencedCollection, SequencedSet, SequencedMap: getFirst/getLast, reversed views on all standard collections.

Structured Concurrency

StructuredTaskScope, ShutdownOnFailure, ShutdownOnSuccess, and scope-based lifecycle for async tasks.

Unnamed Patterns and Variables (_)

Underscore _ in patterns, catch clauses, enhanced for, lambda parameters: explicit discard of unused values.

String Templates and Text Blocks

STR/FMT template processors (Java 21 preview), text block + formatted() stable combo, and safe interpolation.

Foreign Memory API: MemorySegment, Arena

Off-heap and native memory with MemorySegment, Arena lifetime management, MemoryLayout, and calling native functions.

Stream Gatherers: Custom Intermediate Ops

Gatherer interface, built-in gatherers (windowFixed, windowSliding, fold, scan, mapConcurrent), and custom gatherers.

Record: Compact Constructors and Custom Accessors

Compact constructor for validation, overriding generated accessors, withers pattern for immutable updates, records implementing interfaces, and defensive copies.

Sealed Classes with Pattern Matching Integration

Exhaustive switch on sealed types (no default needed), pattern matching with guards (when), record patterns inside switch, and AST evaluator example.

Unnamed Classes and Instance Main: JEP 445

Instance main method without public static void, unnamed classes for scripts and learning, limitations vs named classes, and --enable-preview usage.

Scoped Values: Java 21+

Share immutable context across a call stack with ScopedValue: safer than ThreadLocal, auto-cleanup, and virtual-thread inheritance.

Virtual Threads: Java 21+

Lightweight threads for high-throughput concurrency: Thread.ofVirtual(), structured concurrency, pinning, and migration from platform threads.

Functional Programming Patterns

Function composition, monadic Optional, currying, higher-order functions, and practical FP patterns for clean Java code.

Java Module System (JPMS): module-info.java, exports & services

module-info.java, requires, exports, opens, uses/provides for services, unnamed and automatic modules, migrating to JPMS, and creating custom JRE images with jlink.

Testing

5 articles

JVM Performance & Profiling

5 articles

Reactive Programming (Project Reactor)

4 articles

JDBC: Database Access

5 articles

Cryptography

5 articles

Networking

5 articles

JSON: Jackson Deep Dive

5 articles

XML Processing

5 articles

Concurrency

7 articles
CountDownLatch & CyclicBarrier: Coordinating Thread Groups

Thread group coordination: CountDownLatch for one-shot await until N events complete, CyclicBarrier for reusable phase synchronisation, barrier actions, broken barrier handling, and choosing between them.

Semaphore: Controlling Concurrent Resource Access

Permit-based concurrency control: acquire/release, tryAcquire with timeout, fair vs non-fair mode, bulk permits, bounded connection pool pattern, simple rate limiter, and binary semaphore as mutex.

Phaser: Flexible Multi-Phase Task Coordination

Advanced synchronization barrier: dynamic party registration/deregistration, arriveAndAwaitAdvance, onAdvance() termination hook, tiered Phaser hierarchies for large party counts, and non-blocking awaitAdvance monitoring.

BlockingQueue Family: LinkedBlockingQueue, ArrayBlockingQueue & SynchronousQueue

Thread-safe queues for producer-consumer: LinkedBlockingQueue, ArrayBlockingQueue (bounded/fair), SynchronousQueue direct handoff, PriorityBlockingQueue ordering, DelayQueue for time-based release, and poison-pill shutdown.

Java Memory Model: happens-before, Visibility & Instruction Reordering

JMM fundamentals: happens-before rules, volatile visibility and limitations, synchronized memory semantics, safe publication patterns, instruction reordering causes, double-checked locking, and common pitfalls table.

Exchanger: Synchronized Data Exchange Between Two Threads

Two-thread rendezvous and data swap with Exchanger: exchange(), timed exchange with TimeoutException, the double-buffer pattern, and when to use Exchanger vs BlockingQueue vs SynchronousQueue.

Thread Basics: Creating Threads, Lifecycle, join, sleep & interrupt

Runnable vs Thread subclass, the six lifecycle states (NEW/RUNNABLE/BLOCKED/WAITING/TIMED_WAITING/TERMINATED), join/sleep/interrupt, daemon threads, uncaught exception handlers, and Thread.ofVirtual().