Java Reference
Every Java keyword, operator, core class, collection, stream, concurrency utility and language feature in one place. Concise, accurate pages with live examples that run on Java 25, with syntax, parameters and return values.
Keywords and Statements
-
if and elseConditional execution. -
switchSwitch statements and switch expressions. -
forCounter-based loops. -
for-each loopIterating arrays and Iterables. -
while and do-whileCondition-controlled loops. -
break and continueLeaving and skipping iterations, labels. -
returnReturning from methods. -
yieldProducing a value in a switch expression. -
try, catch and finallyException handling. -
try-with-resourcesAutomatic resource closing. -
throw and throwsThrowing and declaring exceptions. -
assertAssertions. -
synchronizedIntrinsic locks. -
volatileVisibility of variables across threads. -
transientExcluding fields from serialization. -
finalConstants, final methods and classes. -
staticStatic members and initializers. -
abstractAbstract classes and methods. -
classDeclaring classes. -
interfaceInterfaces, default and static methods. -
enumEnumerations. -
recordRecords. -
sealed, permits and non-sealedSealed hierarchies. -
extends and implementsInheritance and interface implementation. -
this and superSelf and parent references. -
newCreating objects and arrays. -
instanceofType tests and pattern matching. -
varLocal variable type inference. -
package and importPackages and imports. -
public, protected, privateAccess control. -
native and strictfpRare modifiers. -
moduleThe module system (module-info). -
defaultDefault methods and switch default. -
Text blocksMulti-line string literals. -
Lambda expressionsSyntax and functional interfaces. -
Method referencesThe :: operator. -
Generics syntaxType parameters and wildcards. -
Annotation syntaxUsing and declaring annotations. -
VarargsVariable arity methods. -
Labeled statementsLabels for loops. -
Reserved wordsThe keyword list.
Operators
-
Arithmetic operators+, -, *, / and % and integer behavior. -
Increment and decrement++ and --. -
Assignment operators=, += and friends. -
Comparison operators==, !=, <, >, <=, >=. -
Logical operators&&, ||, ! and short-circuit. -
Bitwise operators&, |, ^, ~. -
Shift operators<<, >>, >>>. -
Conditional operator?: expressions. -
String concatenation+ with strings. -
instanceof operatorPattern matching for instanceof. -
CastingPrimitive and reference casts. -
Operator precedenceThe precedence table. -
== vs. equals()Identity vs. equality. -
Integer overflowWrapping and the exact arithmetic methods.
Types and Literals
-
Primitive typesThe eight primitives. -
int32-bit integers. -
long64-bit integers. -
short and byteSmall integers. -
charUTF-16 code units. -
float and doubleFloating-point numbers. -
booleanTruth values. -
Wrapper classesInteger, Long, Double, Boolean, Character. -
AutoboxingBoxing, unboxing and pitfalls. -
LiteralsNumeric, character and string literals. -
ArraysDeclaring and using arrays. -
Multidimensional arraysArrays of arrays. -
Reference typesReferences, null and identity. -
nullThe null reference. -
Type conversionsWidening, narrowing and promotion. -
Enum typesEnum details. -
Type inferencevar and the diamond operator.
java.lang
-
ObjectThe root class: equals, hashCode, toString, getClass. -
StringImmutable strings. -
String.length()Length of a string. -
String.charAt()Character at an index. -
String.substring()Extracting parts. -
String.indexOf()Finding substrings. -
String.split()Splitting by regex. -
String.replace()Replacing text. -
String.trim() and strip()Removing whitespace. -
String.equals()Comparing strings. -
String.compareTo()Ordering strings. -
String.contains()Containment checks. -
String.startsWith()Prefix and suffix checks. -
String.format()Formatted strings. -
String.formatted()Instance formatting and conversion. -
String.join()Joining strings. -
String.repeat()Repeating strings. -
String.chars()Character streams. -
String.toCharArray()Character arrays. -
toUpperCase() and toLowerCase()Case conversion. -
isEmpty(), isBlank()Emptiness checks. -
String.lines()Line handling. -
String.intern()Interning. -
String.matches()Regex matching. -
StringBuilderMutable strings. -
StringBufferThread-safe builders. -
MathMath functions. -
Math.round(), floor(), ceil()Rounding. -
Math.random()Pseudo-random numbers. -
Math.addExact() and friendsOverflow-checked arithmetic. -
StrictMathDeterministic math. -
IntegerThe int wrapper. -
Integer.parseInt()Parsing integers. -
Integer.toString() and toBinaryString()Converting integers. -
Integer.compare()Comparing ints. -
LongThe long wrapper. -
DoubleThe double wrapper. -
BooleanThe boolean wrapper. -
CharacterCharacter utilities. -
NumberThe numeric superclass. -
BigIntegerArbitrary-precision integers. -
BigDecimalExact decimals. -
SystemSystem utilities. -
System.out and System.errStandard output. -
System.inStandard input. -
System.currentTimeMillis() and nanoTime()Timing. -
System.arraycopy()Copying arrays. -
System.getProperty() and getenv()Properties and environment. -
System.exit()Terminating the JVM. -
RuntimeThe runtime environment. -
ThreadThreads. -
ClassRuntime class objects. -
ClassLoaderLoading classes. -
RecordThe record base class. -
EnumThe enum base class. -
IterableTypes usable in for-each. -
ComparableNatural ordering. -
AutoCloseableClosable resources. -
Cloneable and clone()Copying objects. -
ThrowableThe root of errors. -
ExceptionChecked exceptions. -
RuntimeExceptionUnchecked exceptions. -
ErrorSerious problems. -
NullPointerExceptionNull dereference. -
IllegalArgumentExceptionBad arguments. -
IllegalStateExceptionBad state. -
IndexOutOfBoundsExceptionIndex errors. -
ClassCastExceptionBad casts. -
NumberFormatExceptionParse failures. -
ArithmeticExceptionDivision by zero. -
UnsupportedOperationExceptionUnsupported operations. -
ConcurrentModificationExceptionModifying while iterating. -
StackOverflowErrorToo-deep recursion. -
OutOfMemoryErrorHeap exhaustion. -
IOExceptionI/O failures. -
InterruptedExceptionInterrupted threads. -
Checked vs. unchecked exceptionsDesign guidance. -
ObjectsNull-safe object utilities. -
OptionalContainers for maybe-values. -
StackWalkerStack inspection. -
ProcessBuilderStarting processes. -
Record patternsDeconstruction patterns.
Collections
-
The collections frameworkInterfaces and implementations. -
CollectionThe root interface. -
ListOrdered collections. -
ArrayListResizable arrays. -
LinkedListDoubly linked list and deque. -
Vector and StackLegacy collections. -
List.of()Immutable lists. -
List.add() and remove()Modifying lists. -
List.get() and set()Indexed access. -
List.sort()Sorting lists. -
List.subList()Views of ranges. -
List.contains() and indexOf()Searching lists. -
removeIf() and replaceAll()Bulk operations. -
SetSets without duplicates. -
HashSetHash-based sets. -
LinkedHashSetInsertion-ordered sets. -
TreeSetSorted sets. -
Set operationsUnion, intersection, difference. -
MapKey-value mappings. -
HashMapHash-based maps. -
LinkedHashMapOrdered maps, LRU caches. -
TreeMapSorted maps. -
Map.of() and Map.entry()Immutable maps. -
Map.getOrDefault()Defaults on lookup. -
Map.computeIfAbsent()Lazy value creation. -
Map.merge()Combining values. -
Map.entrySet()Iterating entries. -
putIfAbsent(), compute() and replace()Atomic-style updates. -
EnumMap and EnumSetEnum collections. -
QueueFIFO collections. -
DequeDouble-ended queues. -
ArrayDequeArray-backed deque. -
PriorityQueueHeap-based priority queue. -
CollectionsCollection utilities. -
Collections.sort()Sorting. -
Collections.unmodifiableList()Read-only views. -
Collections.reverse(), shuffle(), max()Utility methods. -
ArraysArray utilities. -
Arrays.sort()Sorting arrays. -
Arrays.toString() and deepToString()Printing arrays. -
Arrays.asList()Fixed-size lists. -
Arrays.copyOf() and copyOfRange()Copying arrays. -
Arrays.fill(), equals(), hashCode()Array utilities. -
Arrays.binarySearch()Binary search. -
Arrays.stream()Array streams. -
IteratorIteration with removal. -
ListIteratorBidirectional iteration. -
ComparatorCustom ordering. -
Comparator.comparing()Building comparators. -
BitSetBit vectors. -
SequencedCollectionJava 21 sequenced collections. -
List.copyOf() and immutabilityUnmodifiable copies. -
Collections and genericsTyping collections. -
Collection complexityBig-O of common operations. -
Concurrent collectionsThread-safe collections overview. -
ConcurrentHashMapConcurrent hash map. -
CopyOnWriteArrayListSnapshot iteration lists.
Streams and Functional
-
Stream APIPipelines, sources, operations. -
Stream.of() and generate()Creating streams. -
Collection.stream()Streams from collections. -
Stream.filter()Filtering elements. -
Stream.map()Transforming elements. -
Stream.flatMap()Flattening. -
distinct() and sorted()Deduplicate and sort. -
limit() and skip()Slicing streams. -
Stream.peek()Debugging pipelines. -
takeWhile() and dropWhile()Prefix operations. -
forEach()Terminal iteration. -
Stream.collect()Mutable reduction. -
Stream.reduce()Reduction. -
count(), min(), max()Simple terminals. -
anyMatch(), allMatch(), noneMatch()Predicates. -
findFirst() and findAny()Searching. -
Stream.toList()Immutable results. -
Stream.mapMulti()Flexible mapping. -
Stream gatherersCustom intermediate operations. -
Stream.iterate()Sequences. -
IntStreamPrimitive int streams. -
IntStream.range()Integer ranges. -
IntSummaryStatisticsStatistics. -
LongStream and DoubleStreamOther primitive streams. -
CollectorsCollector factories. -
toList(), toSet(), toMap()Basic collectors. -
groupingBy()Grouping. -
partitioningBy()Two groups. -
joining()Joining strings. -
counting(), summing, averagingAggregating collectors. -
teeing()Two collectors at once. -
Parallel streamsparallel() and pitfalls. -
Laziness and short-circuitingHow pipelines run. -
Streams vs. loopsWhen to use which. -
Functional interfacesThe java.util.function package. -
Function and BiFunctionTransforming values. -
Predicate and BiPredicateBoolean tests. -
Consumer and BiConsumerSide effects. -
SupplierProducing values. -
UnaryOperator and BinaryOperatorSame-type operators. -
Primitive functional interfacesIntFunction and friends. -
Runnable and CallableTasks. -
Optional.of() and ofNullable()Creating Optionals. -
Optional.orElse() and orElseThrow()Getting values. -
Optional.map() and flatMap()Transforming Optionals. -
Optional.ifPresent()Conditional actions.
Text, Formatting and Regex
-
printf and format specifiersFormat specifiers. -
FormatterThe Formatter class. -
DecimalFormatNumber patterns. -
NumberFormatLocale-aware numbers. -
MessageFormatMessage templates. -
LocaleLocales. -
Text blocks in depthIndentation and escapes. -
Escape sequencesCharacters in literals. -
Unicode and code pointsCode points and surrogates. -
Charset and StandardCharsetsEncodings. -
ScannerParsing input. -
StringTokenizerLegacy tokenizer. -
PatternCompiled regexes. -
MatcherMatching and groups. -
Regex syntaxConstructs reference. -
Pattern flagsCASE_INSENSITIVE and more. -
Named capture groups(?<name>...). -
replaceAll() and appendReplacement()Replacement. -
Pattern.split()Splitting. -
Regex pitfallsBacktracking and escaping. -
Base64Encoding. -
HexFormatHex conversion. -
UUIDIdentifiers. -
RandomPseudo-random generator. -
RandomGeneratorJava 17 random API. -
ThreadLocalRandomConcurrent random. -
SecureRandomSecure random. -
Objects.hash()Hash codes. -
StringJoinerJoining pieces.
Date and Time
-
java.time overviewThe API at a glance. -
LocalDateDates without time. -
LocalTimeTimes without date. -
LocalDateTimeDate and time. -
ZonedDateTimeZoned date-times. -
InstantMachine time. -
DurationTime-based amounts. -
PeriodDate-based amounts. -
ChronoUnitUnits and between(). -
DateTimeFormatterFormatting and parsing. -
ZoneId and ZoneOffsetTime zones. -
DayOfWeek and MonthEnums. -
TemporalAdjustersAdjusting dates. -
Year, YearMonth and MonthDayPartial dates. -
ClockTestable time. -
Date, Calendar and SimpleDateFormatLegacy classes. -
Converting legacy and modern typesBridges.
Object-Oriented Concepts
-
Classes and objectsFundamentals. -
ConstructorsConstructor rules. -
Initialization orderStatic, instance, constructors. -
EncapsulationAccess and invariants. -
InheritanceSubclassing rules. -
PolymorphismDynamic dispatch. -
OverridingOverriding rules. -
OverloadingOverload resolution. -
Abstract classes vs. interfacesChoosing. -
Default and static interface methodsEvolution. -
Private interface methodsJava 9 feature. -
Inner and nested classesMember classes. -
Anonymous classesAnonymous classes. -
Local classes and recordsLocal types. -
Records in depthCompact constructors, accessors. -
Sealed classes in depthExhaustiveness. -
Pattern matchinginstanceof and switch patterns. -
Pattern matching for switchGuards and dominance. -
Advanced enumsFields, methods, abstract. -
equals() and hashCode() contractThe contract. -
toString()String representations. -
Immutable classesDesigning immutable types. -
Singleton patternSafe singletons. -
Builder patternFluent builders. -
Object cloningCopy constructors. -
Static nested classesStatic nested types. -
Generic classes and methodsGeneric design. -
Wildcards and PECSextends and super. -
Type erasureErasure consequences. -
Bounded type parametersextends bounds. -
SOLID in JavaDesign principles.
Concurrency
-
Concurrency overviewModels and vocabulary. -
Creating threadsThread and Runnable. -
Thread lifecycleStates and joins. -
Virtual threadsJava 21 virtual threads. -
ExecutorServiceThread pools. -
Executors factory methodsPool types. -
FutureTask results. -
CompletableFutureAsync pipelines. -
CallableTasks with results. -
ScheduledExecutorServiceTimers. -
ForkJoinPoolFork/join. -
synchronized in depthMonitors. -
Lock and ReentrantLockExplicit locks. -
ReadWriteLock and StampedLockRead/write locks. -
Atomic classesAtomicInteger and friends. -
volatile and the memory modelHappens-before. -
CountDownLatchLatches. -
CyclicBarrier and PhaserBarriers. -
SemaphorePermits. -
BlockingQueueProducer-consumer. -
ThreadLocalPer-thread values. -
wait() and notify()Low-level coordination. -
DeadlockCauses and prevention. -
Race conditionsDetection. -
Structured concurrencyStructuredTaskScope (preview). -
Scoped valuesScopedValue. -
InterruptionCooperative cancellation. -
TimeUnitTime units.
I/O and Files
-
Java I/O overviewStreams, readers, NIO. -
FileLegacy file class. -
Path and PathsNIO paths. -
Files.readString() and readAllLines()Reading files. -
Files.writeString() and write()Writing files. -
Files.walk() and list()Traversing directories. -
Files.copy(), move(), delete()File operations. -
Files.createTempFile()Temporary files. -
BufferedReaderReading text. -
BufferedWriter and PrintWriterWriting text. -
InputStream and OutputStreamByte streams. -
ByteArrayInputStream and ByteArrayOutputStreamIn-memory streams. -
DataInputStream and DataOutputStreamBinary data. -
ObjectInputStream and serializationSerialization. -
SerializableSerialization rules. -
Channels and ByteBufferNIO buffers. -
RandomAccessFileRandom access. -
ConsoleConsole I/O. -
ZipOutputStream and GZIPOutputStreamCompression. -
PropertiesProperty files. -
URI and URLAddresses. -
HttpClientHTTP client (read-only). -
SocketsTCP basics. -
com.sun.net.httpserverEmbedded HTTP server. -
Reading and writing with charsetsEncodings. -
Closing resourcesPatterns.
Language Features by Version
-
Java versions overviewLTS releases and cadence. -
Java 8 featuresLambdas, streams, java.time. -
Java 9 to 11 featuresModules, var, HTTP client. -
Java 12 to 17 featuresSwitch expressions, records, sealed. -
Java 18 to 21 featuresVirtual threads, pattern matching. -
Java 22 to 25 featuresUnnamed variables, simple main, scoped values. -
Simple source files and instance mainCompact programs. -
Unnamed variables and patternsThe underscore. -
Preview featuresEnabling previews. -
Deprecated and removed APIsWhat to stop using. -
Modules (JPMS)module-info basics. -
JShellThe REPL. -
JavadocDocumentation comments. -
Built-in annotations@Override, @FunctionalInterface, @SuppressWarnings. -
Custom annotationsDeclaring and reading annotations. -
ReflectionThe reflection API. -
Method, Field and ConstructorReflective access. -
Dynamic proxiesjava.lang.reflect.Proxy. -
Class loadingClass loaders. -
JVM memoryHeap, stack, metaspace. -
Garbage collectionCollectors overview. -
JIT compilationHotSpot basics. -
Useful JVM flagsCommon options. -
JDK toolsjavac, java, jar, jlink, jpackage. -
Maven and GradleBuild tools (read-only). -
Testing with JUnitJUnit basics. -
LoggingSystem.Logger and java.util.logging. -
Code conventionsNaming and formatting. -
Secure codingCommon practices. -
GlossaryKey Java terms.
Nothing matches โโ. Try the site search.