JavaPrintable

Java Cheat Sheet

Program structure, operators, input, strings, formatting, switch, loops, collections, classes, enums, records, generics, exceptions, files, dates, streams and JUnit on one printable page.

Back to the Java tutorial

Program structure

SyntaxWhat it doesLesson
public class Main { }A class; file must be Main.javaIntroduction
public static void main(String[] args)Where the program startsIntroduction
System.out.println(x);Print and new lineIntroduction
javac Main.java then java MainCompile and runIntroduction

Variables & input

SyntaxWhat it doesLesson
int double boolean char StringCommon typesVariables
final int MAX = 10;ConstantVariables
(int) 3.9 Integer.parseInt("7")Cast / parseVariables
Scanner in = new Scanner(System.in);Keyboard inputUser input
in.nextLine() in.nextInt()Read a line / an intUser input
System.out.printf("%s %.2f%n", s, d);Formatted outputUser input

Strings

SyntaxWhat it doesLesson
s.length() s.charAt(i)Length, one characterStrings
s.substring(a, b) s.indexOf("x")Part of text, find textStrings
s.trim() s.toUpperCase() s.replace(a, b)Transform (returns new String)Strings
s.split(",") String.join("-", arr)Split / joinStrings
a.equals(b) a.equalsIgnoreCase(b)Compare textStrings
new StringBuilder().append(x)Build text efficientlyStrings

Conditions & loops

SyntaxWhat it doesLesson
if (c) { } else if (d) { } else { }Branchingif/else
switch (v) { case 1 -> ...; default -> ...; }Match fixed valuesif/else
for (int i = 0; i < n; i++) { }Counted loopLoops
while (c) { } do { } while (c);Condition loopsLoops
for (int x : arr) { }Visit every itemLoops

Arrays & methods

SyntaxWhat it doesLesson
int[] a = {1, 2, 3}; new int[5]Create an arrayArrays
a.length Arrays.toString(a)Size / printArrays
Arrays.sort(a) Arrays.copyOf(a, n)Sort / copyArrays
int[][] g = new int[3][4];2D arrayArrays
static int sq(int n) { return n * n; }Method with a resultMethods

Classes & collections

SyntaxWhat it doesLesson
class Dog { String name; Dog(String n) { name = n; } }Class and constructorClasses
List<String> l = new ArrayList<>();Resizable listArrayList
l.add(x) l.get(i) l.remove(i) l.size()List methodsArrayList
Map<String, Integer> m = new HashMap<>();Key-value mapHashMap
m.put(k, v) m.getOrDefault(k, 0)Write / read safelyHashMap
Set<String> s = new HashSet<>();Unique valuesHashMap

Inheritance & interfaces

SyntaxWhat it doesLesson
class Car extends VehicleInherit from a classInheritance
super(args); super.method()Call the parentInheritance
@OverrideCheck an overrideInheritance
interface Payable { void pay(); }Define a contractInterfaces
class Card implements PayableKeep the contractInterfaces
abstract class Shape { abstract double area(); }Partial blueprintInterfaces

Exceptions & streams

SyntaxWhat it doesLesson
try { } catch (Exception e) { } finally { }Handle errorsExceptions
throw new IllegalArgumentException("msg");Report a problemExceptions
void load() throws IOExceptionDeclare a checked exceptionExceptions
x -> x * 2 String::lengthLambda / method referenceStreams
list.stream().filter(...).map(...).toList()Stream pipelineStreams
Collectors.groupingBy(f, Collectors.counting())Group and countStreams

Operators, formatting & switch

SyntaxWhat it doesLesson
7 / 2 7 % 2 (double) a / bInteger division, remainder, decimal divisionOperators & Math
x++ x += 5Update a variableOperators & Math
Math.round(x) Math.max(a, b) Math.pow(a, b)Common mathsOperators & Math
System.out.printf("%-10s%6.2f%n", s, d)Aligned, formatted outputFormatting & StringBuilder
new StringBuilder().append(x).toString()Build strings efficientlyFormatting & StringBuilder
""" text block """Multi-line textFormatting & StringBuilder
case "A", "B" -> ...Arrow case, no fall-throughswitch
int d = switch (m) { case 2 -> 28; default -> 31; };Switch expressionswitch

Collections, enums & records

SyntaxWhat it doesLesson
new TreeSet<>() new LinkedHashSet<>()Sorted / insertion-ordered setCollections
Deque<T> s = new ArrayDeque<>(); s.push(x); s.pop();StackCollections
new PriorityQueue<>()Smallest item firstCollections
list.sort(Comparator.comparing(P::age).reversed())Sort objectsCollections
enum Size { SMALL, LARGE }Fixed set of constantsEnums
Size.values() Size.valueOf("LARGE")All constants / from textEnums
record Point(int x, int y) {}Immutable data classRecords
class Box<T> { } static <T> T f(T x)Generic class and methodGenerics
List<? extends Number>Read-only wildcardGenerics

Files, dates & testing

SyntaxWhat it doesLesson
Files.readAllLines(Path.of("f.txt"))Read linesFiles & I/O
Files.writeString(p, s, CREATE, APPEND)Append to a fileFiles & I/O
try (Stream<String> l = Files.lines(p)) { }Read a big file lazilyFiles & I/O
LocalDate.of(2024, 7, 5).plusDays(3)Create and move a dateDates & Times
DateTimeFormatter.ofPattern("dd/MM/yyyy")Format and parse datesDates & Times
ChronoUnit.DAYS.between(a, b)Days between datesDates & Times
@Test void name() { assertEquals(exp, act); }A JUnit testUnit Testing (JUnit)
assertThrows(X.class, () -> code())Expect an exceptionUnit Testing (JUnit)
@ParameterizedTest @CsvSource({...})One test, many inputsUnit Testing (JUnit)

Beginner companion reference

TopicRule to rememberLesson
Syntax and StatementsExpressions produce values; statements instruct the programOpen lesson
Output: print() vs. println()println adds a line terminatorOpen lesson
Comments and Code StructureComments explain intent without executingOpen lesson
Variables, Identifiers and Constantsfinal prevents reassignment of the variableOpen lesson
Primitive Data TypesJava has eight primitive typesOpen lesson
Type Casting and varvar infers a fixed local typeOpen lesson
Operators and PrecedenceMultiplication binds before additionOpen lesson
Strings, Concatenation and EscapesString objects are immutableOpen lesson
Boolean Expressions&& requires both operands to be trueOpen lesson
switch Expressions and StatementsA switch expression produces a valueOpen lesson
if, else if and Nested ConditionsAn else-if chain takes the first matching branchOpen lesson
for, while and do-while Loopsdo-while executes its body at least onceOpen lesson
Nested and Enhanced for LoopsEnhanced for visits elements rather than indicesOpen lesson
break and continuebreak exits while continue skips one iterationOpen lesson
Methods and ParametersJava passes arguments by valueOpen lesson
Return Values and Method OverloadingOverloading requires different parameter listsOpen lesson
Variable ScopeA local variable belongs to its enclosing blockOpen lesson
Recursion: Base Cases and CallsRecursion needs a reachable base caseOpen lesson
User Input with ScannernextLine reads the remainder of a lineOpen lesson
Command-Line ArgumentsArguments arrive as strings in argsOpen lesson

Intermediate companion reference

TopicRule to rememberLesson
Classes and Objects ExplainedAn object is an instance of a classOpen lesson
Fields, Attributes and MethodsInstance fields hold each object stateOpen lesson
Constructors and Constructor OverloadingConstructors initialize newly created objectsOpen lesson
this Keywordthis refers to the current objectOpen lesson
Access and Non-Access Modifiersprivate restricts access to implementation detailsOpen lesson
Encapsulation and ValidationEncapsulation protects object invariantsOpen lesson
Inheritance and the super Keywordsuper can invoke a superclass constructor or methodOpen lesson
Polymorphism and Method OverridingOverridden instance methods dispatch using the actual objectOpen lesson
Abstraction and InterfacesInterfaces define a shared contractOpen lesson
Inner and Anonymous ClassesA non-static inner class has an enclosing instanceOpen lesson
Enums and Enum ConstructorsEnum constants are fixed named instancesOpen lesson
Packages and ImportsAn import allows a shorter type nameOpen lesson
Single and Multidimensional ArraysJava multidimensional arrays are arrays of arraysOpen lesson
Array Operations and SortingBinary search requires matching sorted orderOpen lesson
String Methods ReferenceString methods return new text when transformingOpen lesson
StringBuilder and StringBufferStringBuilder is a mutable character sequenceOpen lesson
Wrapper Classes and AutoboxingAutoboxing converts primitives to wrapper objectsOpen lesson
Collections Framework ExplainedList keeps positions while Set models uniquenessOpen lesson
List, ArrayList and LinkedListArrayList offers constant-time indexed accessOpen lesson
HashSet, TreeSet and LinkedHashSetLinkedHashSet preserves insertion orderOpen lesson
HashMap, TreeMap and LinkedHashMapA Map associates unique keys with valuesOpen lesson
Iterators and the Iterable InterfaceIterable provides an IteratorOpen lesson
Collections Sorting and ComparatorsComparator defines an external orderingOpen lesson
Generics and Generic ClassesGenerics provide compile-time type checkingOpen lesson

Files and I/O companion reference

TopicRule to rememberLesson
Exception Types and HierarchyRuntimeException subclasses are uncheckedOpen lesson
try, catch, finally, throw and throwsthrow raises an exception while throws declares itOpen lesson
Custom Exceptions and Multi-CatchCustom exceptions express domain-specific failuresOpen lesson
Try-with-ResourcesTry-with-resources closes AutoCloseable resourcesOpen lesson
File Handling: Create, Read, Write, DeleteFile open options determine overwrite or append behaviorOpen lesson
Path and Files APIsPath models a path while Files performs operationsOpen lesson
Byte Streams and Character StreamsCharacter streams decode or encode textOpen lesson
FileInputStream and FileOutputStreamInputStream.read returns minus one at end of streamOpen lesson
BufferedReader and BufferedWriterreadLine returns null at end of inputOpen lesson
Serialization and DeserializationSerializable marks types for native object serializationOpen lesson
JSON Processing with JacksonA JSON library parses structured data rather than string splittingOpen lesson

Advanced companion reference

TopicRule to rememberLesson
Lambda ExpressionsA lambda implements a functional interfaceOpen lesson
Functional InterfacesFunction transforms while Predicate tests a valueOpen lesson
Method ReferencesA method reference adapts an existing methodOpen lesson
Stream API: map, filter and reduceStream intermediate operations are lazyOpen lesson
Optional: Handling Missing ValuesOptional models a present value or absenceOpen lesson
Regular Expressionsmatches validates the whole inputOpen lesson
Date and Time API: java.timeLocalDate is a date without a time zoneOpen lesson
Annotations ExplainedAnnotations provide metadata for tools or frameworksOpen lesson
Reflection APIReflection inspects runtime type informationOpen lesson
Multithreading and Thread Lifecyclestart begins execution on a new threadOpen lesson
Synchronization and Race ConditionsSynchronization coordinates access using a shared lockOpen lesson
ExecutorService and Thread PoolsExecutorService manages submitted tasksOpen lesson
Concurrency UtilitiesAtomicInteger provides atomic single-variable updatesOpen lesson
Debugging and Logging BasicsA debugger pauses execution while logging records eventsOpen lesson

Developer Tools companion reference

TopicRule to rememberLesson
JDK, JRE and JVM ExplainedThe JDK includes development tools and runtime capabilitiesOpen lesson
Installing Java and Setting Up the JDKJAVA_HOME conventionally points to the JDK rootOpen lesson
Compiling and Running Java Programsjavac compiles source and java launches bytecodeOpen lesson
Classpath and Package LayoutClasspath entries are roots for locating classesOpen lesson
Maven and Gradle BasicsBuild files declare dependencies and repeatable tasksOpen lesson
Unit Testing with JUnitUnit tests compare observed behavior with explicit expectationsOpen lesson
Debugging Java Applications Step by StepDebugging tests a hypothesis with a reproducible caseOpen lesson
Git Basics for Java ProjectsA commit records a reviewed change in repository historyOpen lesson
Modern Java: Records, Sealed Classes and PatternsRecords are data carriers with generated component accessorsOpen lesson
Modules and module-info.javaexports exposes a package from a named moduleOpen lesson

Java DSA companion reference

TopicRule to rememberLesson
Time and Space ComplexityBig O describes growth with input sizeOpen lesson
Linear Search and Binary SearchBinary search requires sorted inputOpen lesson
Sorting Algorithms ExplainedInsertion sort maintains a sorted prefixOpen lesson
Stacks and Queues with ArrayDequeStacks use LIFO and ordinary queues use FIFOOpen lesson
Linked Lists: Nodes and LinksA linked list connects nodes through referencesOpen lesson
Hashing and Hash TablesHash collisions still require equality checksOpen lesson
Trees and Binary Search TreesIn-order traversal sorts keys of a valid BSTOpen lesson
Heaps and Priority QueuesPriorityQueue exposes the next item by priorityOpen lesson
Graphs, BFS and DFSBFS explores an unweighted graph by edge distanceOpen lesson
Recursion and BacktrackingBacktracking explores and then undoes choicesOpen lesson
Dynamic Programming BasicsDynamic programming reuses overlapping subproblem resultsOpen lesson

Practice and Projects companion reference

TopicRule to rememberLesson
Examples Library for BeginnersAn example should expose one behavior and its resultOpen lesson
Exercises by TopicExercises should state inputs and expected behaviorOpen lesson
Quizzes by ChapterQuizzes diagnose understanding rather than replace coding practiceOpen lesson
Coding Challenges with Test CasesChallenge constraints guide the algorithm choiceOpen lesson
Keywords Reference and GlossaryKeywords have reserved language-defined rolesOpen lesson
String, Math and Collections MethodsAPI references should include behavior and edge casesOpen lesson
Common Java Errors and SolutionsCompile errors, runtime failures and logic errors are differentOpen lesson
Interview Questions and Answersequals checks the equality contract while == checks reference identityOpen lesson
Beginner Java Projects with Practice StepsA small project needs clear acceptance criteriaOpen lesson
Intermediate Java Projects: Collections and FilesDomain operations should preserve state invariantsOpen lesson
Advanced Java Projects: Testing and ConcurrencyAdvanced projects need explicit failure and shutdown policiesOpen lesson
Learning Roadmap and Study PlanA roadmap orders skills by prerequisites and practiceOpen lesson

How to use this Java cheat sheet

This Java cheat sheet collects the syntax beginners and intermediate programmers look up most often, in the same order as the course: program structure, variables and types, input and output, strings, conditions, loops and arrays, methods, classes, collections, inheritance and interfaces, enums, records, generics, exceptions, files, dates, streams and testing. Each row links to the lesson that explains it with examples and common mistakes.

Keep it beside you while you write programs in IntelliJ IDEA, VS Code or Eclipse. When you can't remember whether arrays use length or length(), how to read a whole line with Scanner, or the shape of a try-with-resources block, a quick glance answers it. Type a keyword into the filter box to jump straight to the right row, or print the page as a one-sheet reference.

Java gotchas worth remembering

  • Compare strings with equals. == checks whether two references point at the same object. name.equals("Ana") compares the text.
  • Integer division truncates. 7 / 2 is 3. Use a double on one side for 3.5.
  • Arrays have length, strings have length(), lists have size(). Mixing them up is the most common compile error for beginners.
  • Scanner leaves a newline behind. After nextInt(), a following nextLine() returns an empty string. Call nextLine() once to clear it, or read every line and parse it.
  • Don't remove items while looping with for-each. It throws ConcurrentModificationException. Use removeIf or an Iterator instead.
  • Override equals and hashCode together. Otherwise your objects behave oddly as HashMap keys or in a HashSet. Records do both for you.

When a snippet surprises you, open the linked lesson for the full explanation, then test yourself with the Java quiz.

The Java lessons behind this cheat sheet