Java code snippets with use cases
29 ready-made code building blocks, sorted by topic.
Basics
- Hello World – A first test of whether the JDK and environment work.
- Variables and Types – Store values with a fixed type and use type inference with var.
- Date and time (java.time) – Calculate deadlines, determine time spans, format dates.
Control flow
- if / else if / else – React differently, e.g. compute grades or price tiers.
- for loops – Process every element of a collection or repeat n times.
- switch expression – Map values by case (weekdays, status codes, price tiers).
Data structures
- Working with lists – Manage collections of values: add, sort, filter.
- Map (dictionary) – Store mappings, e.g. configurations or counters per key.
- Sorting with Comparator – Order records by several fields, e.g. users by age, then name.
OOP
- Class with inheritance – Bundle data and behavior, e.g. users, products, game characters.
- Record with validation – Immutable data objects (DTOs, return values) without getter boilerplate.
- Enum with fields – Model fixed sets of choices (status, roles, weekdays) in a type-safe way.
Error handling
- try / catch / finally – Guard user input or network access without the program crashing.
- Optional instead of null – Safely handle search results that may be missing (user, configuration value).
- try-with-resources – Reliably close files, database connections or sockets.
Modern Java
- sealed interface + switch – Model closed sets of cases, e.g. payment methods, shapes or event types.
- Record patterns: expression tree – Evaluate tree structures (expressions, syntax trees, rules) recursively.
- instanceof with pattern – Safely check objects of unknown type and keep using them without a cast.
- Sequenced collections (Java 21) – Conveniently read the first and last element of a list or reverse the list.
Strings
- Text block and formatted – Embed multi-line JSON, SQL or HTML readably in code.
- Formatted output – Print tables, reports and logs in fixed columns.
- Counting words with merge – Text analysis, e.g. most frequent words in a document.
More snippets
- Method with overloading – Bundle recurring logic, e.g. greeting texts or calculations.
- Read and write a file – Save and load logs, configurations or text data.
- Streams: grouping and evaluating – Group data from databases or CSV files, e.g. users per city.
- Combining CompletableFuture – Start several independent queries (price, discount) in parallel and merge them.
- Virtual threads – Thousands of blocking tasks (HTTP calls, DB queries) without complicated async code.
- Generic method – Write helper functions that work with any comparable type.
- HTTP request (HttpClient) – Fetch data from a web API – without any external library.