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.
Java Basics
26 articlesJava 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 articlesString: 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 articlesLooping 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.
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: 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.
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 articlesReading 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 articlesOptional: 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 articlesRecords: 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 articlesJUnit 5: Parameterized Tests, Dynamic Tests & Lifecycle
@ParameterizedTest with @ValueSource, @CsvSource, @MethodSource, @TestFactory for dynamic tests, assertAll, assertThrows, @Nested, and @ExtendWith.
Mockito: Mocking, Spying, Stubbing & Argument Captors
@Mock, @InjectMocks, when/thenReturn, thenThrow, doReturn for void methods, @Spy, verify(), InOrder, and ArgumentCaptor with @ExtendWith(MockitoExtension.class).
AssertJ: Fluent Assertions, Soft Assertions & Custom Assertions
assertThat chains, string and collection assertions, usingRecursiveComparison, assertThatThrownBy, SoftAssertions, and building custom AbstractAssert classes.
WireMock: Stubbing & Verifying HTTP Services in Tests
WireMockExtension setup, stubbing GET/POST, request matching on headers and JSON body, verify() call counts, fault and delay simulation, Spring Boot @AutoConfigureWireMock.
Testcontainers: Custom Images, Reusable Containers & Docker Compose
@Container PostgreSQL and Kafka in JUnit 5, @DynamicPropertySource, GenericContainer for any image, reusable containers, Docker Compose, and @ServiceConnection (Spring Boot 3.1+).
JVM Performance & Profiling
5 articlesJVM Tuning: Heap Sizing, GC Selection & Key JVM Flags
Practical JVM tuning: heap sizing with -Xms/-Xmx, Young Gen sizing, GC selection, G1GC and ZGC key flags, metaspace capping, unified GC logging, and container-aware settings.
Java Microbenchmarking with JMH: Modes, Pitfalls & Best Practices
Write reliable Java benchmarks with JMH: Throughput, AverageTime, SampleTime modes, @State, @Param, Blackhole for dead-code prevention, @Fork/@Warmup/@Measurement, and eight common pitfalls.
Java Memory Leaks: Detection, Heap Dumps & Eclipse MAT
Find and fix Java memory leaks: static collection, ThreadLocal, listener, and class-loader leak patterns; heap dump generation with jmap and jcmd; GC log signals; and Eclipse MAT dominator tree analysis.
Async-Profiler: CPU, Allocation & Lock Profiling for Java
Profile JVM applications without safepoint bias: CPU hot paths, allocation pressure, lock contention, wall-clock latency, flame graph interpretation, and IntelliJ IDEA integration.
GC Deep Dive: G1GC, ZGC & Shenandoah Tuning
Deep dive into Java GC internals: G1GC regions, IHOP, mixed GC; ZGC colored pointers and load barriers; Shenandoah Brooks forwarding pointers; side-by-side comparison table; and GC log patterns.
Reactive Programming (Project Reactor)
4 articlesProject Reactor: Mono, Flux, Operators & Error Handling
Core reactive primitives: Mono and Flux creation, cold vs hot publishers, map/flatMap, filter, error handling with onErrorReturn/onErrorResume/retry, backpressure, and subscribing.
Reactor Operators: flatMap, zip, buffer, groupBy & Transformations
Advanced Reactor operators: flatMap vs concatMap vs switchMap, combining streams with zip/merge/concat, buffer and window by count or time, groupBy, reduce and scan, and time-based operators.
Reactor Schedulers: publishOn, subscribeOn & Thread Management
Reactive thread management: built-in Schedulers (boundedElastic, parallel, single), publishOn vs subscribeOn, offloading blocking calls, parallel() for CPU work, custom thread pools, and Reactor Context propagation.
Reactor Testing: StepVerifier, Virtual Time & PublisherProbe
Test reactive pipelines with confidence: StepVerifier for sequence assertions, virtual time for interval and timeout operators, PublisherProbe for branch coverage, and WebTestClient for reactive REST APIs.
JDBC: Database Access
5 articlesJDBC Basics: Connection, Statement & ResultSet
DriverManager connection, Statement vs PreparedStatement, ResultSet iteration, auto-generated keys, DatabaseMetaData, and NULL handling with wasNull().
PreparedStatement & SQL Injection Prevention
Bind parameters vs string concatenation, SQL injection exploit and fix, all setter types, batch INSERT with addBatch/executeBatch, and reusing a PreparedStatement.
JDBC Transactions, Savepoints & Batch Operations
Manual commit/rollback with setAutoCommit(false), isolation levels and the anomalies they prevent, partial rollback with Savepoint, and large-batch DML with periodic flushes.
Connection Pooling: HikariCP Standalone Configuration
Why connection pools matter, HikariCP setup and key configuration properties, pool sizing formula, connection leak detection, and graceful shutdown.
CallableStatement, Stored Procedures & ResultSet Metadata
Calling stored procedures with IN/OUT/INOUT parameters, stored functions with return values, multiple ResultSets with getMoreResults(), and ResultSetMetaData for dynamic column inspection.
Cryptography
5 articlesMessageDigest: SHA-256, SHA-512 & MD5 Hashing
Cryptographic hashing with MessageDigest: SHA-256/512/SHA-3, hex encoding with HexFormat, file checksums via DigestInputStream, incremental update(), and algorithm selection guide.
AES Encryption: CBC, GCM Modes & SecretKey Generation
AES symmetric encryption with Java JCA: KeyGenerator, AES-GCM authenticated encryption with IV, AES-CBC with PKCS5Padding, and PBKDF2 key derivation from passwords.
RSA Encryption: Key Pairs, Encrypt/Decrypt & Digital Signatures
Asymmetric RSA cryptography: KeyPairGenerator, OAEP-SHA256 encryption, SHA256withRSA digital signatures, PEM key serialisation, and the hybrid RSA+AES encryption pattern.
HMAC: Message Authentication Codes with HmacSHA256
HMAC-SHA256 message authentication: Mac class, constant-time tag verification with MessageDigest.isEqual(), webhook signature verification, API request signing, and algorithm variants.
SecureRandom, PBKDF2 & Password-Safe Key Derivation
Cryptographic randomness with SecureRandom, PBKDF2WithHmacSHA256 password hashing with random salts, iteration count tuning benchmark, and comparison with bcrypt and Argon2.
Networking
5 articlesTCP Socket Programming: ServerSocket, Socket & Client/Server Patterns
TCP server and client from scratch: echo server, thread-per-client, thread-pool server, socket options (SO_TIMEOUT, TCP_NODELAY), length-prefix framing, and graceful shutdown.
UDP Sockets: DatagramSocket, DatagramPacket & Multicast
Connectionless UDP programming: unicast echo server/client, connected UDP, broadcast with setBroadcast(), IP multicast with MulticastSocket, packet size limits, and sequencing patterns.
Non-Blocking NIO Networking: Selector, SocketChannel & ServerSocketChannel
Reactor pattern with Java NIO: Selector event loop, OP_ACCEPT/OP_READ/OP_WRITE interest ops, non-blocking echo server, partial write handling, and when to use Netty or virtual threads instead.
Java HttpClient Deep Dive: HTTP/2, Async Requests & WebSocket Upgrade
Modern HTTP with java.net.http: GET/POST/PUT/DELETE, synchronous and async sendAsync(), HTTP/2 multiplexing, BodyHandlers/BodyPublishers reference, streaming, authentication, and WebSocket upgrade.
SSL/TLS Sockets: SSLSocket, Certificate Validation & Hostname Verification
Secure sockets with JSSE: SSLContext with KeyStore/TrustStore, SSLSocket/SSLServerSocket, hostname verification via SSLParameters, mutual TLS client auth, protocol and cipher suite control, and keytool commands.
JSON: Jackson Deep Dive
5 articlesJackson Custom Serializers & Deserializers
Write StdSerializer and StdDeserializer implementations, register via SimpleModule, use @JsonSerialize/@JsonDeserialize on specific fields, and build contextual deserializers that read per-field annotations.
Jackson Mixins, Annotations & Introspection
Apply @JsonIgnore, @JsonProperty, @JsonInclude, @JsonCreator, @JsonAlias, and @JsonTypeInfo annotations, attach them to third-party classes via addMixIn(), and inspect serialisation metadata with BeanDescription.
Jackson Tree Model: JsonNode, ObjectNode & ArrayNode
Parse JSON into a JsonNode tree with readTree(), navigate safely with path(), build and modify ObjectNode/ArrayNode programmatically, iterate fields, and convert between tree nodes and POJOs.
Jackson Modules: JavaTimeModule, Parameterized Types & Type Handling
Register JavaTimeModule for java.time, Jdk8Module for Optional, ParameterNamesModule for no-annotation constructors, use TypeReference for generics, and build your own SimpleModule.
Jackson ObjectMapper Configuration: Features, Builders & ObjectReader/Writer
Configure SerializationFeature, DeserializationFeature, and MapperFeature, use immutable ObjectReader/ObjectWriter for per-call overrides, apply JsonView, use readerForUpdating() for PATCH merges, and set naming strategies.
XML Processing
5 articlesDOM Parser: Reading & Writing XML Trees
Full DOM tree parsing with DocumentBuilder, navigating nodes, reading attributes, creating and modifying elements, serialising with Transformer, namespace-aware queries, and XXE security hardening.
SAX Parser: Event-Driven Streaming XML Parsing
Push-based streaming XML with SAX: ContentHandler callbacks, characters() accumulation pattern, ErrorHandler, early exit via SAXException, large file processing, and XXE prevention.
StAX Parser: Cursor & Iterator-Based Streaming XML
Pull-based streaming XML with StAX: XMLStreamReader cursor API, XMLEventReader iterator API, XMLStreamWriter for writing XML, event type constants, filtering with EventFilter, and XXE hardening.
XPath: Querying XML Documents with javax.xml.xpath
XPath 1.0 queries in Java: XPathConstants return types, common expressions reference, compiled XPathExpression for reuse, namespace-aware evaluation with NamespaceContext, and InputSource evaluation.
JAXB: Binding Java Objects to XML with Annotations
Object-XML mapping with Jakarta XML Binding: @XmlRootElement, @XmlElement, @XmlAttribute, marshalling/unmarshalling, JAXBContext caching, XmlAdapter for custom types, schema generation, and validation.
Concurrency
7 articlesCountDownLatch & 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().