Java Cheatsheet — Quick Reference
A concise cheatsheet for Java 17+ syntax, OOP, collections, and the most commonly used standard library APIs, covering roughly 80% of daily scenarios.
Java Java 17 (LTS)
JDK (OpenJDK / Oracle) · OOP, generics, functional · static, strong, nominal typing
Recommended Learning Path
Start by getting Hello World and the build environment running (javac/java or Maven) → get comfortable with variables, types, and control flow → process data with collections and the Stream API → dive into OOP (inheritance, interfaces, generics) → master exception handling and lambda → finally look up files, network, time, and build/debug on demand. The FAQ section is best revisited to avoid pitfalls.
1.Hello World and Build Environment
Write, compile, and run a Java program from scratch: the main method, javac/java, packages, and build tools.
Minimal Program
Every Java program starts with the main method: public static void main(String[] args). System.out.println prints a line.
Compile and Run
javac compiles .java into .class bytecode, and java launches the JVM to run it. Use javap to disassemble and inspect bytecode.
Command-Line Arguments
main(String[] args) receives command-line arguments; args[0] is the first user argument. Check args.length for the count.
Exit Code
System.exit(code) terminates the JVM and returns an exit code: 0 for success, non-zero for failure. It force-exits even if non-main threads are still running.
Package Declaration
package declares the package the type belongs to, mapped to a directory layout, and is used in fully qualified names. Omitting it puts the type in the unnamed package.
import Statement
import brings in classes or static members from other packages so you can skip fully qualified names. java.lang is imported by default.
Class and File Name
The public class name must match the file name. A single .java file may contain multiple non-public classes, but at most one public class.
Maven / Gradle
Larger projects use build tools: Maven (pom.xml) and Gradle (build.gradle) manage dependencies, compilation, testing, and packaging.
2.Variables and Constants
Variable declarations, type inference, final constants, scope, and type conversion.
Variable Declaration
A declaration = type + name + optional initializer. Local variables must be initialized before use; fields have default values.
var Type Inference
var (Java 10+) lets the compiler infer the type. It is limited to local variables. Use explicit types when readability suffers.
final Constants
A final local variable can be assigned only once; a final field must be initialized at declaration or in a constructor; static final is a constant.
Scope
Block scope: variables declared inside a block are visible only within it. Nested blocks can shadow an outer variable with the same name (not recommended).
Naming Conventions
Class names use UpperCamelCase, variables and methods use lowerCamelCase, constants use UPPER_SNAKE_CASE, and package names are all lowercase.
Type Conversion
Implicit conversion widens (int to long to double). Explicit casts may lose precision (truncation).
null and NPE
null is the empty value of a reference type. Calling a method or accessing a field on null throws NullPointerException (NPE). Use Objects utilities to handle null safely.
Literals
Integer literals can use _ separators for readability, 0x for hex, 0b for binary. Append L to long literals and f to float literals.
3.Data Types
Primitives and wrappers, strings, arrays, enums, generics, and record.
Primitive Types
Java has 8 primitive types: byte/short/int/long (integers), float/double (floating point), char, and boolean. Values are stored directly.
Wrapper Classes
Wrapper classes such as Integer, Double, and Boolean box primitives into objects. Autoboxing/unboxing happens implicitly when needed.
String
String is an immutable sequence of characters. equals compares content; == compares references. Every modification produces a new object.
Arrays
Arrays have a fixed length, accessed by index, with a length property. Declare int[], create with new int[n], or initialize with {}.
Enum
enum defines a set of constants, which may carry fields and methods. switch can use enum values directly, with compile-time type safety.
Generics
Generics parameterize types: List<T>, Map<K,V>. The compiler enforces type checks; at runtime types are erased (type erasure).
record Type
record (preview in Java 14, finalized in 16) declares an immutable data carrier in one line: the constructor, equals, hashCode, and toString are auto-generated.
Autoboxing Pitfall
Boxing/unboxing hides pitfalls in == and arithmetic: Integer values from -128 to 127 are cached, so == outside that range may be false.
Object Root Class
All classes implicitly extend Object: toString, equals, hashCode, clone, finalize. Whenever you override equals, also override hashCode.
4.References and Memory
Reference semantics, null, object copies, heap/stack, GC, and the string pool.
Reference Semantics
Java has no pointers; object variables hold references (pointer-like). Assignment shares the same object, so mutations are visible to all aliases.
null Reference
null means the reference points to no object. Compare with == / !=; passing null into a method can produce an NPE. Use defensive null checks.
Object Methods
toString describes the object, equals compares content, and hashCode provides a hash. The defaults are reference comparison; override for value semantics.
Heap and Stack
Objects are allocated on the heap (managed by GC); local variables and references live on the stack. The reference of a new object lives on the stack; the body lives on the heap.
GC Garbage Collection
The JVM automatically reclaims unreachable objects, so you never call free. System.gc() is only a hint and is not guaranteed to run immediately.
Copy Semantics
Assignment of arrays or objects shares the reference. For an independent copy use clone, Arrays.copyOf, or manual copying. Deep copies must be done layer by layer.
String Constant Pool
Literal strings are cached in the constant pool: identical literals share the same object. new String(...) creates a new object outside the pool. Use intern() to put it in.
finalize and Cleaner
finalize runs before GC but its timing is not guaranteed (deprecated). To release external resources use AutoCloseable with try-with-resources.
5.Control Flow
if/else, switch, for/while loops, break/continue, and the ternary operator.
if / else
if/else branches on a condition. The condition must be a boolean expression. Chain else-if for multiple branches.
switch Expression
switch (Java 14+) can use -> to return a value and merge cases. The classic switch statement also accepts arrow syntax.
for Loop
Classic for: initializer, condition, step. Use it when you need indices or reverse iteration. Prefer enhanced for to iterate collections.
Enhanced for
for-each iterates arrays and Iterable collections without indices. Do not structurally modify the collection (it throws an exception).
while / do-while
while checks the condition before each iteration; do-while runs at least once. Use while when the iteration count is unknown (reading streams, polling).
break and continue
continue skips the current iteration, break exits the loop, and labelled break/continue controls nested loops.
Ternary Operator
cond ? a : b expresses an if/else in one line. The two branches must have compatible types. Avoid nested ternaries: they hurt readability.
return and Early Return
return ends the method and returns a value (use plain return; for void). Early returns keep methods readable (guard clauses).
6.Methods and Lambda
Method signatures, parameters, overloading, recursion, Lambda, and functional programming.
Method Definition
A method = access modifier + return type + name + parameter list + body. void means no return value.
Parameter Passing
Java is always pass-by-value: primitives pass a copy; reference types pass a copy of the reference (mutating members affects the caller, reassigning the parameter does not).
Varargs
... (varargs) accepts any number of arguments of the same type; it is essentially an array. It must be last and you can have only one.
Method Overloading
Methods with the same name but different parameter lists (count or types) are overloads. The compiler picks the best match by argument types. Return type does not participate.
Recursion
A method that calls itself is recursion. Without a base case the call stack overflows.
Lambda Expression
A Lambda is (params) -> expression and is an instance of a functional interface. You can omit type inference and the parentheses for a single parameter.
Method Reference
:: method references are shorthand for Lambdas: ClassName::staticMethod, obj::instanceMethod, ClassName::new.
Functional Interface
An interface with exactly one abstract method can be used as a Lambda target. Common ones: Runnable, Function, Consumer, Predicate, Supplier.
Stream API
Stream chains process collections: filter, map, collect. Streams are lazy and do not mutate the source.
7.Strings
String literals, concatenation, StringBuilder, common methods, and formatting.
String Literals
Double-quoted strings, \n escape sequences, and text blocks (Java 15+) wrapped in triple double quotes preserve multi-line formatting.
Concatenation
+ concatenates strings; concatenating with another type implicitly converts it to a string. It is fine for a few concatenations; use StringBuilder inside loops.
Common Methods
Common methods: length, substring, indexOf, replace, split, trim, and case conversion.
StringBuilder
For heavy concatenation use StringBuilder (not thread-safe) or StringBuffer (thread-safe): append then toString.
Formatting
String.format: %d for integers, %s for strings, %.2f for decimals, %n for line breaks. Width and flags are supported.
Regex Match
String.matches matches the whole string, replaceAll replaces via regex, split splits via regex. Remember to escape regex meta-characters.
Character Handling
charAt retrieves a character; Character.isDigit/isLetter/isWhitespace classify characters. Strings are immutable, but you can iterate their characters.
String Conversion
Integer.parseInt parses a string into a number; valueOf/toString convert a number into a string. Parsing throws NumberFormatException on failure.
8.Collections and Stream
Common List/Set/Map/Queue implementations, iteration, Stream, and sorting.
List
List is an ordered collection. ArrayList is backed by an array (fast reads); LinkedList is a linked list (fast inserts/removes). List.of creates immutable lists.
Set
Set deduplicates. HashSet is unordered with O(1) operations; LinkedHashSet preserves insertion order; TreeSet is sorted. Adding a duplicate returns false.
Map
Map is a key/value mapping. HashMap is O(1); LinkedHashMap preserves insertion order; TreeMap sorts by key. getOrDefault safely handles missing keys.
Queue / Deque
Queue is FIFO (offer/poll/peek); Deque is a double-ended queue (addFirst/addLast). ArrayDeque is faster than LinkedList.
Iteration and Traversal
Use enhanced for, Iterator, or forEach to iterate a collection. To remove during iteration use Iterator.remove or collect first and remove later.
Sorting
List.sort or Collections.sort to sort; Comparator customizes the order; Comparator.comparing enables chaining.
Stream Chained Operations
filter/map/sorted/distinct/limit form a chain; a terminal operation triggers execution. collect gathers results back into a collection.
Grouping and Aggregation
Collectors.groupingBy groups by key, partitioningBy splits by a boolean, summarizingInt computes statistics.
Immutable Collections
List.of, Set.of, Map.of create immutable collections. Collections.unmodifiableList wraps a read-only view.
9.Memory and Performance
GC, weak references, memory leaks, string concatenation performance, and buffers.
String Concatenation Performance
Using + inside a loop repeatedly creates new (immutable) Strings. Use StringBuilder to assemble once for a big performance win.
Weak and Soft References
WeakReference does not prevent GC (good for caches); SoftReference is collected only under memory pressure; PhantomReference fires after collection.
Memory Leak
Common leaks: static collections holding objects, unclosed resources, unregistered listeners, ThreadLocal not cleaned up. Avoid long-lived holders around short-lived objects.
ThreadLocal
ThreadLocal gives each thread its own copy. In web containers with thread pools, forgetting to remove() leaks state across requests.
ByteBuffer
ByteBuffer on direct memory (allocateDirect) reduces GC pressure and suits NIO and large transfers. It must be managed manually.
OutOfMemoryError
OOM means memory is exhausted: heap full, metaspace full of classes, or too many direct buffers. Tune JVM flags or find the leak.
Array Copy
System.arraycopy efficiently copies array ranges. Arrays.copyOf copies and may grow the array. Manual copy loops are slow.
Object Pool Reuse
Frequently creating large objects increases GC pressure. An object pool caches reusable instances but must be thread-safe and track return paths.
10.Object-Oriented Programming
Classes, encapsulation, inheritance, polymorphism, abstract classes, interfaces, and access modifiers.
Class and Object
class defines a data type: fields hold state, methods define behavior, constructors initialize, and new creates instances.
Encapsulation
Private fields with public methods control access. Add validation to getters/setters to protect invariants.
Inheritance
extends inherits from a base class. Java uses single inheritance. super calls into the parent's constructor or methods; a subclass is-a parent.
Polymorphism
A parent-class or interface reference can point to a subclass instance; virtual methods dispatch on the actual type. Mark overrides with @Override.
Abstract Class
An abstract class cannot be instantiated and may declare abstract methods (subclasses must implement them). Use it as a template base that shares state.
Interface
interface defines a contract: methods are implicitly public abstract. Java 8+ added default and static methods. A class can implement multiple interfaces.
Access Modifiers
public opens everywhere; protected means package + subclasses; default (no modifier) means package; private means the same class only. Class members default to package-private.
static Members
static fields and methods belong to the class, not instances. static methods cannot access instance members. Use static blocks for initialization.
Inner and Anonymous Classes
Inner classes, anonymous classes, and lambdas simplify callbacks. A static inner class does not hold an outer reference, avoiding leaks.
11.Exception Handling
try/catch/finally, exception hierarchy, checked/unchecked, try-with-resources, and custom exceptions.
try / catch / finally
try holds code that may fail, catch handles errors, and finally always runs (for cleanup). Exceptions propagate upward.
Multi-catch
Multiple catch clauses match by type; put more specific exceptions first, broader ones last. Use multi-catch with | to combine unrelated types.
Throw and Rethrow
throw new throws an exception. throw; inside a catch (Java 7+) rethrows the original, preserving the stack. Declare throws to mark checked exceptions a method may throw.
Custom Exception
Custom exceptions extend Exception (checked) or RuntimeException (unchecked). By convention, end the class name with Exception.
Checked and Unchecked Exceptions
Checked exceptions (e.g. IOException) must be caught or declared; unchecked exceptions (RuntimeException subclasses) are not enforced at compile time.
try-with-resources
try (resource) { } automatically calls AutoCloseable.close(), even on exception. It replaces manual finally cleanup.
Cost of Exceptions
Catching exceptions is expensive (stack walking); do not use it for control flow. Use return values, null checks, or Optional for predictable errors.
Logging and Exceptions
Log exceptions (with stack traces); do not just System.out and continue. Use a logging framework (SLF4J + Logback) for level-based output.
12.Files and IO
Modern Files/Path IO, Scanner, Reader/Writer, and streaming reads.
Files Read/Write
java.nio.file.Files is the modern API: readString/writeString, readAllLines, copy/move/delete.
Scanner Input
Scanner reads from the console or files: nextLine for a line, nextInt/nextDouble for typed values. Use hasNext to check for more input.
Reader / Writer
Character streams read and write text: BufferedReader for line-by-line, BufferedWriter for writing, and try-with-resources for auto-close.
Byte Streams
InputStream/OutputStream read and write bytes: FileInputStream, BufferedInputStream for buffering. Use transferTo for bulk data movement.
Console IO
System.out for output, System.in for input, System.err for errors. printf formats output.
Path
Path represents a path. resolve joins, getFileName reads the name, toAbsolutePath resolves, exists checks, Files.walk recursively iterates.
Serialization
ObjectOutputStream/ObjectInputStream serialize objects (the class must implement Serializable). JSON is more common in modern code.
Temporary Files
Files.createTempFile creates a file in the system temp directory. Delete it with Files.deleteIfExists when done to avoid residue.
13.Common Pitfalls (FAQ)
The most common Java pitfalls: == vs equals, boxing cache, concurrency, exceptions, and collection mutation.
== vs equals
Compare string/object content with equals; == compares references. The literal pool can make == accidentally true - never rely on it.
Integer Cache
Autoboxed values from -128 to 127 are cached, so == can be true; outside that range it is false. Always use equals for object comparison.
Null Check and NPE
Calling a method on null throws an NPE. Use Optional or check null up front; do not sprinkle try-catch NPE everywhere.
Swallowing Exceptions
An empty catch silently swallows the exception and makes debugging hard. At least log it, or rethrow (wrapped in a suitable exception).
equals and hashCode
When you override equals you must also override hashCode, otherwise HashSet/HashMap will treat equal objects as different keys.
Removing During Iteration
Calling List.remove inside an enhanced for throws ConcurrentModificationException. Use Iterator.remove or collect-then-remove.
Date Mutability
The legacy Date/Calendar are mutable and error-prone. Use java.time (LocalDate, LocalDateTime) - immutable and safe.
Thread Safety
HashMap and ArrayList are not thread-safe and break under concurrent writes. Use ConcurrentHashMap or a synchronized wrapper.
Stream Null Values
When a Stream contains null elements, filter/map may NPE. Filter first with filter(Objects::nonNull).
Loop Concatenation
Using += in a loop creates many intermediate Strings and is slow. Use StringBuilder.
14.Concurrency and Threads
Thread, synchronized, thread pools (ExecutorService), and CompletableFuture.
Thread
Use Thread or Runnable to create a thread; start to launch, join to wait, sleep to pause. A thread pool is usually preferable.
synchronized
synchronized locks for mutual exclusion. An instance method locks this; a static method locks the Class; a block can lock any object.
volatile
volatile guarantees visibility (writes are immediately visible to other threads) but not atomicity. Use volatile for flags and AtomicInteger for counters.
Thread Pool
ExecutorService manages thread reuse. newFixedThreadPool / newCachedThreadPool; call shutdown when done.
Future and Callable
Callable is a task with a return value; Future.get blocks for the result. FutureTask can be controlled manually.
CompletableFuture
Async composition: thenApply to transform, thenCombine to merge, allOf to wait for many. Callbacks chain without blocking the caller.
Concurrent Collections
ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue are thread-safe. Prefer them over manual locking on ordinary collections.
Lock Interface
ReentrantLock is more flexible than synchronized: timeout, interruptible, fair. You must unlock it manually (in finally).
15.Network and HTTP
HttpClient, URL requests, JSON serialization, and WebSocket.
HttpClient Basics
java.net.http.HttpClient (Java 11+) sends HTTP requests. send is synchronous; sendAsync is asynchronous. Configure with a builder.
POST and JSON
POST requests with a JSON body. Use Jackson or Gson to (de)serialize JSON.
Async Request
sendAsync returns a CompletableFuture and does not block the caller. Chain thenApply for concurrent requests.
URL and URLConnection
The legacy URL/HttpURLConnection works for simple requests. HttpClient is cleaner for most cases. URL-encode query parameters.
JSON Parsing
Jackson and Gson are the mainstream JSON libraries. Use @JsonProperty to map field names; combine with Java 17 records.
Calling Web APIs
Compose: build the request, check the status code, then deserialize. Handle non-success codes like 404 / 500.
WebSocket
java.net.http.WebSocket is a bidirectional long-lived connection. A Listener receives callbacks; onOpen/onText handle events.
Timeout and Retry
HttpRequest.timeout sets the request timeout; HttpClient.connectTimeout sets the connect timeout. On timeout an HttpTimeoutException is thrown.
16.Date and Time
java.time local date/time, Instant, Duration/Period, and formatting.
LocalDate
LocalDate is a date without time: now, of, plusDays, minusMonths. It is immutable and thread-safe.
LocalTime
LocalTime is a time without a date: now, of, plusMinutes. Combine with LocalDate to form LocalDateTime.
Instant Timestamp
Instant is a UTC point in time (epoch seconds/nanoseconds), suitable for cross-time-zone storage. Use System.currentTimeMillis for system time.
Duration and Period
Duration is a time-based amount (seconds/nanoseconds); Period is a date-based amount (years, months, days).
Formatting and Parsing
DateTimeFormatter formats and parses. Built-in ISO formatters exist; custom patterns like yyyy-MM-dd HH:mm:ss are supported.
Time Zone
ZonedDateTime carries a time zone; ZoneOffset is a fixed offset. ZoneId.systemDefault is the local zone. Store in UTC.
Old API Conversion
Convert between java.util.Date/Calendar and the new API. Date is mutable and error-prone; use java.time for new code.
Timestamp Utilities
System.currentTimeMillis gives milliseconds; nanoTime gives nanosecond deltas (intervals only, not wall time). Convert between timestamps and formats.
17.Processes and System
ProcessBuilder to launch processes, system properties, environment variables, and runtime information.
ProcessBuilder
ProcessBuilder launches external programs. Pass arguments as a list to avoid injection. redirectErrorStream merges stderr into stdout.
System Properties
System.getProperty reads JVM system properties: user.home, java.version, os.name. Use setProperty to set them.
Environment Variables
System.getenv reads environment variables (read-only); getenv() returns them all. Distinguish system properties from environment variables.
Runtime Information
Runtime exposes JVM info: availableProcessors, maxMemory, totalMemory. gc() is a hint.
Command-Line Argument Parsing
Parse options from main args: simple manual loops for simple cases, picocli/JCommander for complex ones.
Shutdown Hook
Runtime.addShutdownHook registers cleanup that runs on JVM exit. System.exit triggers it. Avoid long-running work in the hook.
Working Directory
The user.dir system property is the process's current working directory. ProcessBuilder.directory sets the starting directory for a child process.
System Platform Info
System properties expose platform info: os.name (OS), os.arch (architecture), file.separator (path separator), line.separator (newline).
18.Regular Expressions
Pattern/Matcher, matching, capture groups, replacement, and common patterns.
Pattern and Matcher
Pattern.compile compiles a regex (cache and reuse), matcher matches against text. find, matches, and lookingAt are three match modes.
Capture Groups
Parentheses capture substrings; group(1) returns the first group, named groups (?<name>...) use group("name"). Loop find to get all matches.
Find All
Loop find or use matcher.results to iterate all matches. Use replaceAll for all replacements (supports $1 group references).
Replace
replaceAll / replaceFirst replace via regex with $1/$2 group references. Matcher.appendReplacement processes segments one by one.
Pattern Flags
Pattern.CASE_INSENSITIVE ignores case; MULTILINE makes ^ $ match per line; DOTALL makes . match newlines.
Common Patterns
Common regexes for email, URL, IP, and phone numbers. For production-grade validation (e.g. real email format) use a dedicated library.
Quantifiers and Anchors
* zero or more, + one or more, ? zero or one, {n,m} a specific count. ^ line start, $ line end, \b word boundary.
Lookahead and Lookbehind
Lookahead (?=...) checks what follows, negative lookahead (?!...) excludes it, lookbehind (?<=...) checks what precedes. None consume characters.
19.Build and Debug
Maven/Gradle, javac/jar, JUnit, and JVM debugging.
Maven Lifecycle
mvn compile/test/package/install are Maven lifecycle phases. The target directory holds classes and jars.
pom.xml
pom.xml defines the project: groupId/artifactId/version coordinates, dependencies, and properties.
Gradle
Gradle is based on Groovy/Kotlin DSL. Tasks define build steps; dependencies resolve from a central repo.
JUnit Tests
JUnit 5: @Test for test methods, @BeforeEach for setup, assert* for assertions. Run with mvn test.
jar Packaging
jar packages classes into a jar. An executable jar needs a Main-Class entry in the manifest. Run with java -jar.
JVM Flags
-Xmx max heap, -Xms initial heap, -XX:+PrintGCDetails GC logs, -D system properties.
Logging Configuration
SLF4J as the facade with Logback as the implementation. Configure level and outputs in logback.xml. Avoid System.out in production.
Dependency Management
Maven dependencies are scoped: compile/test/runtime. Use exclusions to drop transitive deps; manage version conflicts in dependencyManagement.
Official Links
Direct links to the official docs and resources.
About this Cheatsheet
This page is a self-contained cheatsheet for Java 17 (LTS), covering around 80% of the everyday usage of the core language, the commonly used JDK libraries, and the build ecosystem in real projects. The content favors modern idioms: var local variable type inference, switch expressions, text blocks, record, sealed classes, and the Stream API. Java was first released by Sun Microsystems in 1995 and is best known for its JVM ecosystem / "write once, run anywhere" promise; it is one of the most widely used languages for enterprise backends, Android development, and big data. The 19 sections each focus on a single topic: basics, variables, types and references, control flow, functions, strings, collections (List/Set/Map), memory management (GC), object-oriented programming, exception handling, I/O, common pitfalls, concurrency, network, time, processes, regex, and build tools (Maven/Gradle). Each subsection pairs a concept intro with a copy-ready code snippet. All code and text are rendered locally in your browser; no data leaves your device. For authoritative reference, see the official Oracle Java documentation.
Version 2.1.0