java --versionCheck the installed JDK version.javac Hello.java★Compile source →Hello.classbytecode.java Hello★Run the class (no.classsuffix).java Hello.java11Run a single source file directly — no javac.javac -d out src/*.javaCompile a package tree into an output dir.java -cp out:libs/* MainSet the classpath (;on Windows).java --enable-preview --source 25 X.java25Required to run any preview-feature code.jshell9Interactive REPL to try snippets.javap -c HelloDisassemble bytecode to see what javac produced.jar --create --file app.jar -C out .Bundle classes into an archive.java -jar app.jarRun an executable jar (needs Main-Class).
package com.acme.app;First line — the namespace of this file.import java.util.List;★Pull in a type from another package.import java.util.*;Wildcard import — a whole package (not recursive).import static java.lang.Math.max;Import a static member; callmax(a,b).public class Main { ... }One public class per file, named like the file.public static void main(String[] args)★The entry point the JVM calls.args.length args[0]Command-line arguments arrive here.System.out.println(0);★Print a line to standard output.void main() { ... }25Final in 25: instancemainin a compact source file — no class, nostatic, noargs.import module java.base;25Module import (JEP 511) — every exported package at once.0Three comment forms.
int i = 42; long L = 42L;★32-bit vs 64-bit integers (note theL).double d = 3.14; float f = 3.14f;★64-bit vs 32-bit floating point.boolean b = true; char c = 0;★true/false; a single UTF-16 code unit.byte / short8-bit and 16-bit integers.fields default: 0 · 0.0 · false · nullFields (not locals) start at these zero-values.1_000_000 1e9 0xFF 0b10107Digit separators, scientific, hex, binary.int t = (int) 3.9; 0Cast narrows & truncates; widening is automatic.long big = 10_000_000_000L;Past ~2.1 billion you needlong.int n = Integer.MAX_VALUE + 1;Silently wraps to a negative — no overflow error.1 + 1 0charis a number —+does arithmetic, not text.
int count = 0;★Declare with an explicit type + assign.final int MAX = 100;★final= assign once; the constant idiom.var list = new ArrayList<String>();★10Type inferred from the initializer.final var id = nextId();10finalandvarcombine.var x = switch(k){...};10Works with any expression that has a type.for (var i = 0; i < n; i++)10varin a loop header is fine.var y; var z = null;Illegal —varneeds an initializer with a real type.fields / params / returnsvaris local variables only.
+ - * / %★%is remainder;5/2==2for ints.++i i-- += -= *=Increment / decrement / compound assign.0 + x + 1+concatenates when either side is a String.== != < > <= >=★Comparisons — but==on objects checks identity.&& || !★Logical, short-circuiting left→right.cond ? a : bTernary — the only expressionif.& | ^ ~ << >> >>>Bitwise;>>>= unsigned right shift.Math.floorMod(-3, 5) 08True modulo;%can be negative.o instanceof String s★16Type test + bindsin one step.
String s = 0;★A literal; String objects never change.a == b vs a.equals(b)★Use.equals()for value equality, not==.s.length() s.charAt(i) s.isEmpty()Core accessors (indices are 0-based).s.substring(1,4) s.indexOf(0) s.contains(1)Slice & search.s.startsWith(p) .endsWith(q) .replace(a,b)Prefix/suffix tests & replacement.s.toUpperCase() .toLowerCase() .trim()Case & whitespace.s.split(0) String.join(1, list)★8Split to an array / join an Iterable.s.strip() .isBlank() .repeat(3) .lines()11Modern helpers (Unicode-aware strip).0.formatted(name, n)15Instance form ofString.format.var t = 0;★15Text block — literal newlines, no escaping.switch (cmd) { case 0 -> ...; }7You can switch on String values.new StringBuilder().append(x).toString()Mutable builder — use it inside loops.s.equalsIgnoreCase(t) s.compareTo(t)Case-insensitive compare / lexicographic order.
int n = Integer.parseInt(0);★Parse text → number (throws on bad input).double d = Double.parseDouble(0);Same for floating point.String s = Integer.toString(42); 0 + 42Number → text.Integer boxed = 42; int back = boxed;5Auto-boxing betweenintandInteger.Integer.MAX_VALUE Long.MIN_VALUEWrapper constants for the limits.Math.abs .max .min .pow .sqrt .round★The everyday math toolbox.Math.random() new Random().nextInt(6)Random doubles [0,1) / bounded ints.ThreadLocalRandom.current().nextInt(1, 7)7Preferred RNG in concurrent code.new BigDecimal(0).add(...)★Exact decimals — use for money, neverdouble.BigInteger.valueOf(2).pow(100)Arbitrary-precision integers.
int[] a = new int[5];★Zero-filled; length is fixed forever.int[] a = {1, 2, 3};★Literal initializer.a.lengthA field, not a method (unlike String).a[0] = 9; int x = a[i];Index access; out-of-range throws.int[][] grid = new int[3][4];Multidimensional = array of arrays.Arrays.sort(a); Arrays.toString(a);★Utilities live injava.util.Arrays.Arrays.fill(a, 7) Arrays.equals(a, b)Bulk set / value compare.Arrays.copyOf(a, n) a.clone()Grow a copy / shallow clone.Arrays.stream(a).sum()8Bridge an array into the Stream world.for (int x : a) { ... }★Enhancedforover any array/Iterable.int sum(int... nums)5Varargs — callsum(1,2,3); it's an array inside.
if (c) {...} else if (d) {...} else {...}★Standard branching.while (c) {...} do {...} while (c);Pre- vs post-tested loops.for (int i=0; i<n; i++) {...}★Classic counting loop.for (var e : coll) {...}★For-each over arrays & collections.break; continue;Exit / skip the current iteration.outer: for(...) { break outer; }Labeled break jumps out of nested loops.if (x == null) return;Guard clause — bail early to cut nesting.assert x > 0 : 0;Off by default — enable withjava -ea.
switch(x){ case 1: ...; break; default: ...; }Classic statement — beware fall-through.switch(x){ case 1 -> a(); default -> b(); }★14Arrow form: no fall-through, nobreak.int r = switch(x){ case 1 -> 10; default -> 0; };★14Switch expression — returns a value.case 1, 2, 3 -> ...; default -> { yield v; }14Multi-label;yieldreturns from a block.case Integer i -> i * 2;★21Pattern matching — switch on type + bind.case Integer i when i > 0 -> ...;21Guarded pattern withwhen.case null, default -> ...;21Handle null; combine with the default branch.exhaustiveness21Patterns/enums need all cases or adefault.
class Point { int x, y; }Fields hold per-object state.Point(int x, int y){ this.x = x; this.y = y; }★Constructor initializes a new instance.var p = new Point(1, 2);★newallocates on the heap.double dist(){ return Math.hypot(x, y); }Instance method — works on this object's fields.int getX(){ return x; } void setX(int v){...}Getter/setter idiom around private fields.public / private / protected / (default)★Access levels — default is package-private.static int count; static void help(){...}Belongs to the class, not an instance.Point(){ this(0,0); }Overload + delegate withthis(...).static class Node{} class Inner{}Nested (static) vs inner (holds outerthis).
class Dog extends Animal {...}★Single inheritance of a superclass.super(name); super.speak();Call the parent constructor / method.0 String speak(){...}★Opt-in check that you really override.Animal a = new Dog(); a.speak();★Upcast + dynamic dispatch = polymorphism.if (a instanceof Dog d) d.fetch();16Safe downcast with a pattern.abstract class Shape { abstract double area(); }Abstract = can't instantiate; forces override.final class / final methodfinalblocks further subclassing/overriding.0 equals / hashCode / toStringThe Object methods you usually redefine together.
interface Drawable { void draw(); }★Pure abstract methods = a capability.class C implements A, B {...}★Multiple interfaces (unlike class extends).interface Shape extends Drawable, Sized {}Interfaces can extend several others.int MAX = 100;Interface fields are implicitlypublic static final.default void hi(){...}8A method body inside an interface.static Drawable of(){...}8Static factory on the interface itself.private helper(){...}9Shared internals for default methods.0 interface F { R apply(T t); }★8Exactly one abstract method → usable as a lambda.
record Point(int x, int y) {}★16Immutable data class in one line.p.x() p.y()16Auto accessors named after components.equals / hashCode / toString16Generated for you from the components.record R(int x){ R { if(x<0) throw...; } }16Compact constructor validates/normalizes.record P(...){ double d(){...} static P zero(){...} }16Add methods & static factories freely.record Pair<A,B>(A a, B b) {}16Records can be generic andimplementinterfaces.case Point(int x, int y) -> x + y;★21Record pattern deconstructs in a switch.case Line(Point(var x,var y), var e) -> ...;21Patterns nest arbitrarily deep.records are immutable & final16No setters, no subclassing — that's the point.
enum Day { MON, TUE, WED }★A fixed set of named constants.Day.values() Day.valueOf(0) d.ordinal()Built-in helpers on every enum.enum P { A(1); final int n; P(int n){this.n=n;} }Enums can hold fields, constructors, methods.switch (day) { case MON -> ...; }In a switch, use bare constant names.enum Op { ADD { int f(){...} }; abstract int f(); }Per-constant method bodies.EnumSet.of(A, B) new EnumMap<>(Day.class)5Fast, compact enum-keyed set/map.sealed interface Shape permits Circle, Square {}★17Restrict who may implement/extend.sealed class Base permits A, B {}17Sealing works on classes too.final / sealed / non-sealed17Each permitted subtype picks one of these.
class Box<T> { T get(){...} }★Parameterize a class by a type.Box<String> b = new Box<>();★7Diamond<>infers the type.class Pair<K, V> { ... }Several type parameters.<T> T first(List<T> xs){...}Generic method with its own type var.<T extends Number> ...Upper bound — T is a Number or subtype.<T extends Comparable<T>>Recursive bound — T comparable to itself.List<? extends Number> List<? super Integer>Wildcards: producer-extends, consumer-super (PECS).new T[] x instanceof List<String>Impossible — generics are erased at runtime.
List<String> xs = new ArrayList<>();★Resizable, ordered, indexable.Map<String,Integer> m = new HashMap<>();★Key→value; keys need good equals/hashCode.Set<Integer> s = new HashSet<>();Unique elements, no order.Deque<Integer> dq = new ArrayDeque<>();6Stack (push/pop) & queue (offer/poll) in one.xs.add / .get(i) / .size() / .contains(x)Everyday operations.xs.removeIf(x -> x.isBlank());8Filter in place with a predicate.m.getOrDefault / .putIfAbsent / .computeIfAbsent★8Ergonomic Map methods.for (var e : m.entrySet()) e.getKey()Iterate entries; alsokeySet()/values().List.of(1,2,3) Map.of(0,1)9Compact immutable factories.xs.getFirst() xs.getLast() xs.reversed()★21Sequenced Collections — uniform ends.LinkedHashMap (order) TreeMap (sorted)Pick the map that matches your ordering need.Collections.max / .min / .frequencyHandy static helpers.
class P implements Comparable<P> { ... }★Give a type a natural order.public int compareTo(P o){ return age - o.age; }Negative / 0 / positive = before / equal / after.xs.sort(Comparator.naturalOrder());★8Sort usingComparableorder.Comparator.comparing(P::name)★8Build a comparator from a key extractor..thenComparing(P::age)8Break ties with a second key..reversed() Comparator.reverseOrder()8Flip the direction.Comparator.comparingInt(String::length)8Primitive-specialized — avoids boxing.Comparator.nullsFirst(naturalOrder())8Decide wherenulls sort.Collections.sort(list) list.sort(cmp)8In-place sorts; streams have.sorted(cmp).
Runnable r = () -> System.out.println(0);★8Lambda = an inline implementation.(a, b) -> a + b x -> x * 28Params infer types; one expr needs no braces/return.Function / Predicate / Consumer / Supplier★8The corejava.util.functionshapes.BiFunction / UnaryOperator / BinaryOperator8Two-arg & same-type variants.Math::sqrt 08Method reference to a static method.str::length 08Bound to a specific instance.String::toUpperCase 0★8Unbound — the first arg becomes the receiver.ArrayList::new 08Constructor reference = a factory.
list.stream() Arrays.stream(a) Stream.of(1,2)8Get a stream from a source..filter(x -> x > 0) .map(String::trim)★8Lazy intermediate ops — nothing runs yet..sorted(comparing(P::age)) .distinct()8Order / dedupe..limit(10) .skip(5) .peek(sysout)8Slice / debug mid-pipeline..flatMap(List::stream)8Flatten a stream of collections into one..toList() .collect(Collectors.toSet())★16Terminal — materialize the result..collect(groupingBy(f, counting()))★8Group into aMapwith a downstream..collect(joining(0)) toMap(k, v)8Join to a String / build a map..reduce(0, Integer::sum) .count() .anyMatch(p)8Fold to one value / other terminals.IntStream.range(0,n).sum() .average()8Primitive streams avoid boxing.Optional<T> .map .filter .orElse(x) .ifPresent★8Model "maybe absent" instead of null.reuse a streamA stream is one-shot — build a fresh one each time.
try {...} catch (IOException e) {...} finally {...}★Handle;finallyalways runs.try (var f = open()) {...}★7try-with-resources auto-closes (AutoCloseable).catch (IOException | SQLException e) {...}7Multi-catch shares one handler.throw new IllegalArgumentException(0);★Raise an exception.void read() throws IOException {...}Checked exceptions must be declared.class MyException extends RuntimeException {}Define your own (unchecked here).throw new MyException(0, cause);Wrap & chain the original via the cause.e.getMessage() e.getCause() e.printStackTrace()Inspect what went wrong.Objects.requireNonNull(x, 0);7Fail fast on null arguments.checked vs unchecked★RuntimeExceptionneedn't be caught/declared; others must.helpful NullPointerException messages14The NPE now names the exact null variable.
LocalDate d = LocalDate.now();★8A date with no time or zone.LocalDate.of(2023, 9, 19) d.plusDays(10)★8Construct / shift (returns a new object).LocalTime LocalDateTime ZonedDateTime8Time, date+time, and zoned variants.Instant.now()8A machine timestamp (UTC epoch).Duration.ofHours(3) Period.ofDays(10)8Time-based vs date-based amounts.Duration.between(a, b) Period.between(x, y)8Difference between two temporals.d.getYear() .getMonthValue() .getDayOfWeek()8Read individual fields.d.isBefore(x) d.isAfter(x)8Compare chronologically.DateTimeFormatter.ofPattern(0)★8Parse & format with a pattern.java.util.Date / Calendar8Legacy & mutable — preferjava.time.
System.out.println(x) .print(x)★Line / no-newline output.System.out.printf(0, k, v)★5Formatted output (%n= newline).System.err.println(msg)Write to standard error.var sc = new Scanner(System.in);5Read typed input:nextInt(),nextLine().Path p = Path.of(0);★11Build a filesystem path.Files.writeString(p, text)★11Write a whole String to a file.String s = Files.readString(p);★11Read a whole file into a String.Files.readAllLines(p) Files.lines(p)8List of lines / lazy Stream of lines.try (var br = Files.newBufferedReader(p))7Stream a large file line by line.Files.exists(p) .createDirectories(p) .delete(p)7Everyday filesystem checks & ops.
new Thread(runnable).start();Spin up an OS-backed platform thread.Thread.sleep(1000); t.join();Pause / wait for a thread to finish.var ex = Executors.newFixedThreadPool(4);5Reuse a bounded pool of platform threads.Future<Integer> f = ex.submit(callable); f.get();5Callablereturns a value;get()blocks.Thread.ofVirtual().start(task);★21A lightweight virtual thread (millions are fine).Executors.newVirtualThreadPerTaskExecutor()★21One virtual thread per task — for blocking I/O.synchronized volatile AtomicIntegerGuard shared state / ensure visibility.var lock = new ReentrantLock(); lock.lock();5Explicit lock — always unlock infinally.ConcurrentHashMap CopyOnWriteArrayList5Thread-safe collections.CompletableFuture.supplyAsync(f).thenApply(g)★8Compose async stages.list.parallelStream().filter(p).count()8Data parallelism for CPU-bound work.new StructuredTaskScope.ShutdownOnFailure()21ᴾPreview: treat related tasks as one unit.