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.jshell9Interactive REPL to try snippets.jar --create --file app.jar -C out .Bundle classes into a runnable 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 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[] a)★The entry point the JVM calls.void main() { ... }21ᴾPreview: instancemain, no class needed.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.int m = 1_000_000;7Underscores group digits for readability.0xFF 0b1010 071Hex, binary, and (legacy) octal literals.int n = Integer.MAX_VALUE + 1;Silently wraps to a negative — no overflow error.
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.var x = switch(k){...};10Works with any expression that has a type.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.== != < > <= >=★Comparisons — but==on objects checks identity.&& || !Logical, short-circuiting left→right.cond ? a : bTernary — the only expressionif.& | ^ ~ << >> >>>Bitwise;>>>= unsigned right shift.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==.0 + 1 + true+concatenates, coercing to text.s.length() .charAt(i) .substring(1,4)Core accessors (indices are 0-based).s.strip() .isBlank() .repeat(3) .lines()11Modern String helpers.0.formatted(name, n)15Instance form ofString.format.var t = 0;★15Text block — literal newlines, no escaping.new StringBuilder().append(x).toString()Mutable builder — use it inside loops.
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).int[][] grid = new int[3][4];Multidimensional = array of arrays.Arrays.sort(a); Arrays.toString(a);Utilities live injava.util.Arrays.Arrays.asList(a) Arrays.copyOf(a,n)Bridge to List / grow a copy.for (int x : a) { ... }★Enhancedforover any array/Iterable.
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.
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 -> ...;21Handle null as its own case.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.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(...).
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.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).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.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.
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.sealed interface Shape permits Circle, Square {}★17Restrict who may implement/extend.final / sealed / non-sealed17Each permitted subtype picks one of these.sealed + switch17Compiler checks the switch covers every subtype.
class Box<T> { T get(){...} }★Parameterize a class by a type.Box<String> b = new Box<>();★7Diamond<>infers the type.<T> T first(List<T> xs){...}Generic method with its own type var.<T extends Number> ...Upper bound — T is a Number or subtype.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.xs.add / .get(i) / .size() / .contains(x)Everyday operations.m.getOrDefault / .putIfAbsent / .computeIfAbsent8Ergonomic Map methods.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.
Runnable r = () -> System.out.println(0);★8Lambda = an inline implementation.list.forEach(System.out::println);8Method reference::— terse lambda.Function / Predicate / Consumer / Supplier8The corejava.util.functionshapes.stream().filter(x -> x>0).map(f).toList()★8Lazy pipeline;toList()collects..collect(Collectors.groupingBy(f))8Group / join / count into a result..reduce(0, Integer::sum) .count() .anyMatch(p)8Fold to a single value / terminal ops.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.checked vs uncheckedRuntimeExceptionneedn't be caught/declared; others must.helpful NullPointerException messages14The NPE now names the exact null variable.
new Thread(runnable).start();Spin up an OS-backed platform thread.var ex = Executors.newFixedThreadPool(4);5Reuse a bounded pool of platform threads.ex.submit(task); future.get();Hand off work; block for the result.Thread.ofVirtual().start(task);★21A lightweight virtual thread (millions are fine).Executors.newVirtualThreadPerTaskExecutor()★21One virtual thread per task — for blocking I/O.synchronized AtomicInteger ConcurrentHashMapGuard shared mutable state.CompletableFuture.supplyAsync(f).thenApply(g)8Compose async stages.