Nearby lessons
123 of 125Java - Quick Cheatsheet
📌 What You Will Learn
- Revise every Java topic in minutes
- Keep the key rules at your fingertips
- Use it before exams and interviews
The complete Java quick cheatsheet — every chapter's summary box in one place. Skim it to revise a topic fast, then open the full lesson from the sidebar.
Chapter 1 — Introduction to Java
- Java is a simple, secure, object-oriented programming language created by James Gosling at Sun Microsystems (now Oracle).
- Write Once, Run Anywhere (WORA): source code (.java) is compiled to bytecode (.class), and every JVM runs that same bytecode.
- JDK > JRE > JVM. JDK is for developers, JRE is for running, JVM executes bytecode.
- Important versions: Java 8 (LTS), Java 11 (LTS), Java 17 (LTS), Java 21 (LTS).
- Java is different from C/C++ because it has no pointers, automatic memory management, and is platform independent.
Chapter 2 — Steps to Prepare Your First Java Application
- Six steps: install JDK → choose editor → write program → save file → compile with javac → run with java.
- File name must match the public class name exactly, and must end with .java.
- javac creates a .class file (bytecode); java runs it.
- public static void main(String[] args) is the entry point of every program.
- Comments (//, /* /, /* */) are ignored by the compiler and are used for documentation.
- Most beginner errors are due to PATH, folder location, or spelling mistakes.
Chapter 3 — Language Fundamentals
- Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
- Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
- Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
- if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
- Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
- Var-args (int... x) lets a method take any number of arguments.
Chapter 4 — Patterns
- Every pattern = outer loop for rows + inner loop for columns.
- Print without newline (System.out.print) for columns; println() after each row.
- Row i of a left triangle needs i+1 elements: inner condition j <= i.
- Inverted shapes use condition j < n - i.
- Shapes with spaces need a separate spaces loop before the value loop.
- Number patterns replace '*' with formulas based on i and j.
Chapter 5 — OOPs — Object Oriented Programming
- Class = blueprint; Object = real thing made from it (memory in heap).
- Four pillars: Encapsulation (hide data), Abstraction (show only essentials), Inheritance (reuse parent code), Polymorphism (one name, many forms).
- Overloading = same class, different parameters, decided at compile time. Overriding = child redefines parent method, decided at run time.
- Constructor initialises the object; name = class name, no return type.
- this = current object; super = parent class; static = belongs to class; final = cannot change.
- abstract class cannot be instantiated; interface is a contract a class implements.
- Association (weak), Aggregation (has-a, part independent), Composition (strong has-a, part dies with whole).
Chapter 6 — Inner Classes
- Inner class = a class declared inside another class.
- Member inner class needs an outer object: outer.new Inner().
- Static nested class is created with Outer.Nested, no outer object needed.
- Local inner class lives inside a method.
- Anonymous inner class has no name and is used for one-time implementations.
- Modern code prefers lambda expressions for one-method interfaces, but anonymous classes still appear in real projects.
Chapter 7 — Wrapper Classes
- Wrapper classes box each primitive into an object: int->Integer, char->Character, etc.
- Autoboxing converts primitive to wrapper automatically; unboxing does the reverse.
- parseInt returns primitive int; valueOf returns Integer object.
- Use equals() not == for wrapper objects and Strings.
- Integer values from -128 to 127 are cached, so == can be true for small values.
- Collections can store only objects, so wrappers are essential there.
Chapter 8 — Packages
- Package = folder that groups related classes; first statement of the file.
- import mypack.*; brings in classes; java.lang is auto-imported.
- Access levels: public (everywhere) > protected (package + children) > default (package) > private (class only).
- Compile packages with javac -d . to create folder structure.
- Classpath tells JVM where classes live; jar packages many classes into one file.
- Reverse-domain package names (com.company.app) keep large projects safe from clashes.
Chapter 9 — String Manipulations
- String is a class, not a primitive; it is immutable.
- Immutability gives security, thread safety and pool caching.
- Use StringBuilder (fastest, not thread-safe) or StringBuffer (thread-safe) when text changes often.
- == compares references; .equals() compares content. Always use .equals() for Strings.
- Override toString() to print objects meaningfully.
- Text blocks (Java 15+) make multi-line strings clean.
Chapter 10 — Exception Handling
- Exception = a run-time problem that stops the program; handling prevents the crash.
- try keeps risky code, catch handles the problem, finally always runs.
- Checked exceptions must be handled; unchecked (RuntimeException) are optional to handle.
- throw throws an exception; throws warns that a method may throw one.
- Custom exceptions extend Exception or RuntimeException for business rules.
- try-with-resources (Java 7+) closes files/connections automatically.
- Errors (like OutOfMemoryError) are system problems — not meant to be caught.
Chapter 11 — Multi Threading
- A thread is a small unit of work; a process is a running program.
- Create a thread by extending Thread or (better) implementing Runnable.
- Life cycle: NEW -> RUNNABLE -> BLOCKED/WAITING/TIMED_WAITING -> TERMINATED.
- Shared data races when many threads change it; synchronized gives a lock.
- wait/notify let threads talk; they need the lock.
- Deadlock = threads waiting on each other's locks; avoid by consistent lock order.
- Real projects use Executors + Callable instead of raw threads.
Chapter 12 — IO Streams (Input / Output)
- A stream is a flow of data: input brings data in, output sends it out.
- Byte streams (InputStream/OutputStream) for images/videos; character streams (Reader/Writer) for text.
- Wrap FileReader in BufferedReader to read text line by line.
- Scanner is the simplest way to read input from the keyboard.
- The File class gives file information; it does not read data.
- Serialization saves objects to files; transient fields are not saved.
- Always close streams — or better, use try-with-resources.
Chapter 13 — Networking
- Networking = programs on different computers exchanging data.
- Client asks for a service; server provides it.
- Server uses ServerSocket (accept) ; client uses Socket (connect).
- TCP is reliable and ordered; UDP is fast but not guaranteed.
- IP address finds the computer, port number finds the service.
- InetAddress works with IPs; URL works with web addresses.
- Modern apps use REST APIs over HTTP, but sockets teach the core idea.
Chapter 14 — RMI — Remote Method Invocation
- RMI lets a program call a method on an object living on another computer.
- Stub (client) sends requests; the real object (server) does the work; the registry connects them.
- Remote interface extends Remote; methods throw RemoteException.
- Implementation extends UnicastRemoteObject.
- Server registers with rebind(); client finds it with lookup().
- Modern systems prefer REST over HTTP, but RMI teaches the same distributed-thinking concepts.
Chapter 15 — Collections
- Collection is an interface; Collections is a utility class with static helpers.
- List = ordered, allows duplicates. Set = no duplicates. Map = key-value pairs. Queue = FIFO.
- ArrayList is the everyday list; HashMap is the everyday map.
- HashMap works on hashCode + buckets; collisions chain, then become trees (Java 8+).
- Comparable (compareTo) is the natural order; Comparator (compare) gives custom order.
- Always override equals() and hashCode() together for your own objects.
- Collections.sort() and Collections.reverse() are the handy helpers.
Chapter 16 — Generics
- Generics give compile-time type safety and remove manual casting.
- Generic class: class Box<T>; generic method: static <T> void m(...).
- Bounded types: <T extends Number> restricts T.
- Wildcards: ? = any, ? extends T = T or children, ? super T = T or parents.
- PECS: producers use extends, consumers use super.
- Type erasure: generics are compile-time only; at run time they are gone.
Chapter 17 — GUI — Graphical User Interface (AWT & Swing)
- GUI = windows and clickable components; AWT uses OS parts, Swing draws its own.
- JFrame is the window; components like JLabel, JTextField, JButton go inside it.
- Layout managers (Flow, Border, Grid) arrange components automatically.
- Events need listeners: addActionListener runs code on a click.
- Anonymous inner classes or lambdas provide the event code.
- Modern GUI work uses JavaFX; Swing still appears in exams and legacy projects.
Chapter 18 — Internationalization (I18N)
- I18N = writing code that supports many languages; L10N = translating to one specific language.
- Locale = language + country (en_US, hi_IN).
- ResourceBundle loads the right properties file for the locale.
- Properties files hold key=value text, one file per language.
- NumberFormat / DateFormat render currency and dates per locale.
- Supporting a new language = adding one properties file, no code changes.
Chapter 19 — Reflection API
- Reflection lets a program inspect and use its classes at run time.
- The Class object (Class.forName, .class, getClass()) is the gateway.
- We can list methods/fields, create objects, and call methods with invoke().
- setAccessible(true) reaches private members — powerful but risky.
- Reflection powers frameworks: JUnit, Spring, Hibernate, annotation processing.
- It is slower and unchecked, so use it at startup, not in hot loops.
Chapter 20 — Annotations
- Annotations are metadata — sticky notes on code; they do not change execution by themselves.
- @Override, @Deprecated, @SuppressWarnings are the common built-in ones.
- @Retention decides how long the annotation lives; @Target decides where it can be used.
- Custom annotations are declared with @interface and read using reflection.
- Frameworks like Spring, JUnit and Hibernate are powered by annotations + reflection.
Chapter 21 — Regular Expressions
- A regex is a pattern to search/match text.
- Pattern.compile() builds the pattern; Matcher.find() searches.
- Character classes [abc], [a-z] and shortcuts \d \w \s make patterns compact.
- Quantifiers: * (0+), + (1+), ? (optional), {n} (exact count).
- String methods matches(), replaceAll(), split() do most practical regex work.
- In Java code, write \d as "\\d" because of escaping.
Chapter 22 — Garbage Collection
- Garbage Collection automatically frees memory of unused objects.
- An object becomes garbage when no reference reaches it (null, reassignment, method end, unreachable cycle).
- System.gc() is only a request — the JVM decides when to collect.
- finalize() is deprecated/removed; use try-with-resources or Cleaner instead.
- Objects live in the heap; modern GC uses Young and Old generations.
- G1 is the default GC; ZGC is for huge heaps with tiny pauses.
Chapter 23 — JVM Architecture
- JVM = Load (Class Loader) + Store (Runtime Areas) + Execute (Execution Engine).
- Five memory areas: Method Area, Heap, Stack, PC Registers, Native Stack.
- Stack holds local variables and references; Heap holds actual objects.
- Objects in the heap are freed by the Garbage Collector.
- Execution Engine = Interpreter (starts fast) + JIT (speeds up hot code).
- The JVM being OS-specific is what makes bytecode platform independent.
Chapter 24 — JDBC Basics
- JDBC is the bridge between Java and a database.
- Five steps: load driver, get connection, create statement, execute SQL, close resources.
- PreparedStatement with ? placeholders is the safe, professional choice (prevents SQL injection).
- executeQuery returns ResultSet; executeUpdate returns row count.
- CRUD = Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE).
- Transactions: setAutoCommit(false) + commit/rollback for all-or-nothing changes.
- Modern drivers are Type 4 vendor drivers (the old JDBC-ODBC bridge is removed).
Chapter 25 — Java 8 Features
- Lambda = a function without a name; (params) -> logic.
- Functional interface = one abstract method, so a lambda can implement it.
- Interfaces now have default and static methods with bodies.
- Predicate (test), Function (apply), Consumer (accept), Supplier (get) are the four core functional interfaces.
- Method references (::) are shorthand for lambdas.
- Streams process collections with filter/map/sorted/collect pipelines.
- Optional prevents NullPointerException with orElse/isPresent.
- java.time (LocalDate, LocalDateTime) replaces the old Date/Calendar cleanly.
Chapter 26 — Java 9 Features
- JShell lets you test Java interactively without files.
- JPMS modules group packages with clear exports and requirements.
- Interfaces can now have private helper methods.
- List.of / Set.of / Map.of create short, immutable collections.
- try-with-resources can use existing variables (Java 9).
- New stream helpers: Optional.stream(), Stream.ofNullable().
Chapter 27 — Java 10 Features
- From Java 10, a new version arrives every six months.
- var lets Java infer the type of a local variable — but only for locals, with initialization.
- List.copyOf / Set.copyOf / Map.copyOf create immutable copies.
- Optional.orElseThrow() throws if empty, or returns the value.
- var keeps Java strongly typed — the type is just inferred, not removed.
Chapter 28 — Java 11 Features
- Java 11 is an LTS version — trusted by companies for long-term support.
- New String methods: isBlank(), strip(), repeat(), lines().
- var is allowed in lambda parameters (mainly for annotations).
- java Hello.java compiles and runs a single file in one command.
- HttpClient is now standard for calling web APIs.
- Old Java EE modules were removed to make the platform lighter.
Chapter 29 — Java 12 Features
- Java 12 introduced switch expressions as a preview — no break, arrows, returns a value.
- indent(n) adds/removes leading spaces on every line.
- transform() chains String operations in one line.
- Collectors.teeing() runs two collectors at once and merges results.
- CompactNumberFormat shows big numbers as 1.2K, 3.5M.
- Preview features are experiments that become final later.
Chapter 30 — Java 13 Features
- Text blocks (""" ... """) give clean multi-line Strings for HTML, SQL, JSON.
- Switch expressions got yield for block-style cases.
- formatted() formats a text block's placeholders.
- Text blocks became final in Java 15; switch expressions in Java 14.
- Preview iterations show how Java matures features carefully.
Chapter 31 — Java 14 Features
- Switch expressions became FINAL in Java 14.
- Records create data classes with automatic constructor, getters, toString, equals, hashCode.
- Pattern matching for instanceof combines check and cast into one step.
- Helpful NPE messages tell you exactly which value was null.
- Text blocks got a second preview before becoming final in Java 15.
- After Java 14: Java 15-24 added text blocks, records, sealed classes, virtual threads.
Chapter 32 — Modern Java — Java 15 to Java 24 (Bonus Update)
- Modern Java is released every 6 months; LTS versions are 8, 11, 17, 21.
- Text blocks and records make code shorter and cleaner.
- Sealed classes control exactly who can extend a class.
- Pattern matching for switch works on types and null.
- Virtual threads (Java 21) let servers handle millions of tasks.
- Previews (templates, structured concurrency) are the future — learn the finalized features first.
- Java 8 concepts remain the everyday foundation in every job.
📝 Key Takeaways
- One section per chapter, built from the chapter summaries
- Each point is the exam-ready one-liner for that topic
- Open the matching lesson for the full explanation and code