173 terms across 10 categories
An abstract class is a class you cannot instantiate. It holds shared fields and methods, and it can leave some methods unimplemented for subclasses to fill in.
Abstraction hides how a type works and shows only what a caller may do. In Java that surface is usually an interface or an abstract class.
An anonymous class is a one-off class declared at the new expression. It has no name. You use it to implement an interface or subclass a type in a single place.
A class is a named blueprint for objects. It declares the data each object holds and the operations allowed on that data. In Java it is also the smallest unit of code: every field and method lives inside one.
Inheritance says a type is another type and reuses its implementation. Composition says a type has another object and delegates work to it. Prefer composition unless you truly have an "is a" relationship.
Constructor chaining is calling one constructor from another so setup logic lives in a single place. In Java that call is this(...) in the same class or super(...) to the parent.
A constructor is the method-like block that runs when you write new. It sets the new object's fields to a valid starting state before any caller can use the instance.
A covariant return lets an override return a more specific type than the parent method. Animal copy() can become Dog copy() in a subclass.
A default method is an interface method that already has a body. Implementors inherit it, and they may override it. Java added them so published interfaces can grow without breaking every class.
Encapsulation keeps an object's data hidden and lets callers change it only through methods that enforce rules. Fields stay private; the public surface is the contract.
Inheritance lets a class reuse and extend another class. The subclass gets the parent's fields and methods, then adds or replaces what it needs.
An inner class is a non-static class declared inside another class. Each instance holds a hidden reference to an enclosing instance and can use its fields directly.
An interface is a type that names a set of methods a class must provide. It describes what an object can do, not how the object is built.
Overriding replaces a parent instance method with a subclass method of the same signature. Overloading adds a method with the same name and different parameters. Override is chosen at runtime; overload is chosen at compile time.
An object is a living instance of a class. It holds its own field values on the heap and answers method calls using that state.
Polymorphism means the same call can run different code depending on the object's real type. You write against a general type; the JVM picks the matching implementation.
A record is a compact class for immutable data. You list the components; the compiler supplies the fields, constructor, accessors, equals, hashCode, and toString.
A sealed class or interface restricts which types may extend or implement it. You list the permitted subtypes. The compiler then knows the full set.
SOLID is five design rules for objects: one job per type, open to extension, substitutable subtypes, small interfaces, and dependencies on abstractions. In Java they show up as class and package boundaries.
this is the current object. super is the inherited part of that object. You use them to pick a field, call a method, or chain a constructor when names collide or the parent must run first.
An abstract factory is an interface that creates a whole family of related objects, with one implementation of that interface per family. It exists to stop you accidentally mixing pieces from two different families.
An adapter sits in front of a type you cannot change and presents the interface your code already uses. It translates calls and data so two incompatible APIs can work together.
A builder is an object that collects construction steps and then creates the product. It replaces a constructor with ten parameters and makes optional fields obvious.
Chain of responsibility passes a request along a list of handlers. Each handler decides to handle it, pass it on, or both. The sender does not know which handler will run.
A command is an object that stands for a request: receiver plus action plus arguments. You queue it, log it, undo it, or run it later without the caller knowing the receiver.
A decorator implements the same interface as the object it wraps and adds behaviour before or after forwarding. You stack decorators instead of growing subclasses.
Dependency injection means an object receives its collaborators from outside instead of constructing them. You pass a Mailer into SignupService. Tests pass a fake. Production passes the real one.
A facade is a simple front for a messy subsystem. Callers use one type and a handful of methods. The facade talks to the many classes behind it.
A factory is code that creates objects on your behalf and returns them as an interface or base type, so the caller never names a concrete class. It replaces new at the call site with a method you control.
Observer lets objects subscribe to events. The subject notifies all observers when its state changes. Publishers do not hard-code the listeners.
The prototype pattern creates new objects by copying an existing instance. You use it when constructing from scratch is expensive or when the new object should start as a variant of one you already have.
A proxy implements the same interface as a real object and controls access to it. It may create the real object lazily, enforce security, cache, or send the call across the network.
A singleton is a class that allows exactly one instance to exist for the lifetime of the program, and hands that instance out on request. In Java the safest way to write one is a single-constant enum.
Strategy puts a family of algorithms behind one interface and lets the client pick which one to run. You swap behaviour without a growing if/else on type flags.
A template method is a method in a superclass that fixes the order of steps and calls overridable hooks for the parts that vary. Subclasses fill in the hooks, not the skeleton.
Access modifiers decide which code can see a class, field, or method. Java has public, protected, package-private (no keyword), and private.
An annotation is a label you attach to code that carries information about it without changing what it does. Tools, compilers, and frameworks read those labels and act on them.
An array is a fixed-length sequence of slots of one type. You pick the length when you create it. Indexes start at 0. length is a field, not a method.
Autoboxing is the compiler automatically converting a primitive such as int into its wrapper object Integer, and unboxing is the reverse. It hides a real allocation behind ordinary-looking code.
Bytecode is the compact instruction set that javac produces and the JVM executes. It is stored in .class files and is portable across every machine that has a JVM.
Checked exceptions must be caught or declared in throws. Unchecked exceptions (RuntimeException and Error) do not. The compiler enforces only the first group.
The classpath is the list of places the JVM searches to find class files and resources. If a class is not on the classpath, the program fails at runtime even though it compiled.
Conditionals choose which statements run. if, else if, and else test a boolean and take one branch. The other branches are skipped.
java.time is the modern date and time API. It uses immutable types: Instant for a moment on the timeline, LocalDate/LocalDateTime for civil dates, and ZonedDateTime when a time zone matters.
An enum is a class whose set of instances is fixed at compile time and listed by name. It is how Java models a value that can only be one of a small, known group, such as an order status.
equals decides whether two objects mean the same thing. hashCode maps an object to an int for hash tables. If you override one, you override both, and they must agree.
An exception is an object describing something that went wrong, thrown at the point of failure and caught somewhere up the call stack. It separates the code that detects a problem from the code that decides what to do about it.
The final keyword fixes a binding after it is set once. It stops a variable being reassigned, a method being overridden, or a class being extended, depending on where you put it.
A functional interface is an interface with exactly one abstract method. Lambdas and method references implement that method. @FunctionalInterface asks the compiler to keep it that way.
Generics let a class or method be written once and used with many types, while the compiler still checks that you used the right one. A list of users and a list of orders share the same code but not the same type.
I/O streams are sequential sources and sinks of bytes or characters. InputStream/OutputStream move bytes. Reader/Writer move characters. Close them with try-with-resources.
The JDK is the kit you develop with: a compiler, tools, and a runtime. The JRE is only the runtime, enough to execute an already-compiled program but not to build one.
The Java Platform Module System, added in Java 9, groups packages into modules that declare what they export and what they require. It makes public stop meaning "visible to everyone".
The Java Virtual Machine is the program that actually runs your compiled Java code. It loads class files, checks them for safety, executes them, and manages memory for you.
A lambda is a short, nameless function. You write it where a functional interface is expected, and the compiler turns it into an implementation of that interface.
A loop repeats a block while a condition holds, or once for each element of a collection. Java has while, do-while, for, and the enhanced for.
A method reference is a lambda that only calls an existing method. You write Class::method or instance::method instead of x -> Class.method(x).
A method is a named block of code you call with arguments. It may return a value. In Java every method belongs to a class or interface.
NIO is the java.nio package: buffers, channels, selectors, and the java.nio.file API. It is the modern way to work with paths, files, and non-blocking sockets.
Operators are the built-in symbols that combine values into expressions: arithmetic like +, comparison like <, logic like &&, and bit manipulation like <<.
Optional is a box that may hold a value or be empty. Return it from a method that might not find a result, instead of returning null or throwing.
A package is a named namespace for classes. It maps to a directory on disk and controls who can see package-private members. package com.shop.orders; is the first line of the file.
Java has eight built-in types that hold a raw value rather than a reference to an object: byte, short, int, long, float, double, char, and boolean.
A reference type variable holds the address of an object on the heap, not the object itself. Classes, interfaces, arrays, enums, and records are all reference types.
Reflection lets a running program inspect and call types, fields, and methods by name. Frameworks use it to wire beans and read annotations. Application code should use it rarely.
Java serialization turns an object graph into a byte stream and back. A class opts in with implements Serializable. Prefer explicit formats (JSON, protobuf) for new work.
static attaches a field or method to the class, not to an instance. There is one copy per class loader, and you call it without an object.
A stream is a pipeline of operations over a sequence of values. You describe map, filter, and reduce steps. The source is traversed when a terminal operation runs.
StringBuilder is a mutable buffer of characters. You append pieces, then call toString() once. Use it when you would otherwise concatenate in a loop.
A String is an immutable sequence of characters. Once created, its contents never change. Methods that look like edits return a new String.
A switch expression picks a value by matching a selector against labels. It must cover every case, it yields a result, and it does not fall through.
toString returns a text picture of an object. System.out.println, string concatenation, and most loggers call it. The default is the class name and a hash.
try-with-resources opens one or more AutoCloseable values in a try (...) header and closes them when the block ends, even if the block throws.
Type erasure is how Java implements generics: the compiler checks your type arguments, then removes them, so the running program sees plain Object with casts inserted. A list of strings and a list of integers are the same class at runtime.
var lets you declare a local variable without writing its type, leaving the compiler to infer it from the initialiser. The variable is still statically typed and its type never changes.
Varargs let a method accept zero or more arguments of one type. You declare the last parameter as Type... name. The compiler packs the arguments into an array.
A variable is a named, typed storage slot holding either a primitive value or a reference to an object. Java requires you to declare its type before you use it.
A wildcard is the question mark in a generic type, as in a list of some unknown subtype of Number. It lets a method accept a family of related generic types instead of exactly one.
ArrayDeque is a resizable ring buffer that works as a queue or a stack. Adds and removes at both ends are amortized O(1). It forbids null.
ArrayList is the default resizable list in Java. It keeps elements in an array behind the scenes, so reading by position is instant, while inserting in the middle has to shift everything after it.
A BlockingQueue is a thread-safe queue whose put waits when the queue is full and whose take waits when the queue is empty. It is the standard hand-off between producer and consumer threads.
The collection hierarchy is the family of related interfaces in the java.util package that describe how groups of objects behave. Lists, sets, queues and maps each have an interface, and several concrete classes implement each one.
Comparable is the type's own natural order: this.compareTo(other). A Comparator is a separate object that ranks two values. Sorting and sorted maps use one or the other.
ConcurrentHashMap is a thread-safe hash map. Readers and writers can overlap. It does not allow null keys or values. Compound updates belong in compute, merge, or putIfAbsent, not in a home-grown get plus put.
CopyOnWriteArrayList is a thread-safe list that copies its array on every write. Iterators see a snapshot and never throw ConcurrentModificationException. Writes are expensive. Reads are cheap.
HashMap stores key-value pairs in buckets chosen by hashCode. Average get and put are O(1). Keys must have a correct equals/hashCode pair, and the map is not thread-safe.
HashSet is a set backed by a HashMap. It stores unique elements with average O(1) add, remove, and contains. Equality is equals, and there is no order.
An Iterator walks a collection one element at a time. hasNext and next move forward. remove deletes the last element returned, safely, during iteration.
LinkedHashMap is a HashMap that also keeps a doubly linked list of entries. Iteration follows insertion order, or access order if you turn that mode on.
LinkedList is a doubly linked list that implements List and Deque. Each element sits in a node with pointers to its neighbours. Adding at the ends is cheap. Getting by index is not.
A ListIterator is an iterator that can move both ways on a List. It also knows the next index and can add or set at the cursor.
PriorityQueue is a binary heap. offer and poll are O(log n). The head is the smallest element by natural order or by a comparator, not the first one you inserted.
Queue is a collection designed for holding elements before processing, usually FIFO. Deque is a queue that lets you add and remove at both ends. Both are interfaces; ArrayDeque is the common implementation.
A stack is last-in, first-out storage: push adds to the top, pop removes the top. In Java, use ArrayDeque as a stack. The java.util.Stack class is a leftover synchronized Vector.
TreeMap is a map whose keys stay sorted. It is a red-black tree. get, put, and remove are O(log n). It implements NavigableMap for range queries.
TreeSet is a set backed by a TreeMap. Elements stay sorted. Add, remove, and contains are O(log n). It offers range views like headSet and ceiling.
WeakHashMap is a map whose keys are weak references. When nothing else refers to a key, the garbage collector can reclaim it and the entry disappears. Values are ordinary strong references.
An assertion is the line in a test that states what the result should be. If reality disagrees, the assertion throws and the test fails with a message explaining the difference.
An integration test runs several real parts together: your code plus a database, a web layer, or a message broker. It checks the wiring that unit tests stub away.
JUnit is the standard testing library for Java. It gives you annotations to mark test methods, assertions to check results, and a runner that build tools and IDEs know how to launch.
The JUnit 5 lifecycle is the fixed order in which JUnit creates your test class and runs its setup, test, and teardown methods. By default JUnit builds a fresh instance of the class for every single test method.
Mockito is a library that builds test doubles for Java interfaces and classes. You stub return values, verify calls, and keep the class under test away from the network and the database.
A parameterized test is one test method that JUnit runs many times, once per set of input values. You write the check once and supply a table of cases instead of copying the method.
A test double is a stand-in for a collaborator in a test. Dummies, stubs, spies, mocks, and fakes are different jobs. The word "mock" is often used for all of them, which hides those jobs.
Atomic classes (AtomicInteger, AtomicLong, AtomicReference, and the rest) expose single-variable updates that are thread-safe without a lock. incrementAndGet and compareAndSet are the usual operations.
Callable is a task that returns a value or throws an exception. ExecutorService.submit runs it and gives you a Future. It is Runnable with a result.
CompletableFuture is a result that may complete later. You can chain thenApply, thenCompose, and whenComplete, combine several futures, and complete it by hand. It is the composable successor to Future.
A CountDownLatch starts at a count. Threads call countDown when they finish a step. Other threads call await and park until the count reaches zero. The latch cannot be reset.
A CyclicBarrier waits until a fixed number of threads have called await, then releases them all and can be used again. An optional barrier action runs once per generation, by the last thread to arrive.
A deadlock is a standstill where each thread waits for a lock another thread holds. Nobody can move. The JVM does not break it for you.
An ExecutorService is a managed group of worker threads that you hand tasks to. You describe the work, and the service decides which thread runs it and when.
ForkJoinPool is a thread pool for divide-and-conquer tasks. Workers steal work from each other. Parallel streams and CompletableFuture default async stages use the common pool.
A Future is a receipt for a result that does not exist yet. You get it the moment you submit a task, and later you use it to wait for the value, check whether the task finished, or cancel it.
Happens-before is the Java Memory Model's rule for visibility and order. If A happens-before B, then B sees A's writes. Without that edge, a read may see a stale value or none of the writes you "already did".
A livelock is a failure where threads keep running but make no progress. They react to each other forever: yield, retry, back off, collide again. CPU is busy. The work never finishes.
A race condition is a bug whose result depends on the unpredictable timing of threads. Two threads read and write the same data without a happens-before edge or an atomic operation, and the answer is wrong only sometimes.
A ReadWriteLock is a pair of locks: many threads may hold the read lock together, but the write lock is exclusive. Use it when reads dominate and the critical section is large enough that the extra bookkeeping pays off.
ReentrantLock is an explicit lock in java.util.concurrent. The same thread may acquire it more than once. Unlike synchronized, you can try to lock, lock with a timeout, lock interruptibly, and create multiple condition queues.
Runnable is the standard way to describe a piece of work that takes no input and returns no result. You hand one to a thread or an executor, and it decides where and when to run it.
A semaphore holds a count of permits. acquire takes a permit and waits if none are left. release returns one. Use it to limit how many threads enter a section at once.
synchronized is Java's built-in lock. A thread that enters a synchronized block holds the monitor of an object. Other threads that need the same monitor wait. Exit releases it and publishes writes.
A thread is one flow of execution inside your program. Every Java program starts with a single thread, and you create more when you want two pieces of work to make progress at the same time.
A thread pool is a fixed set of worker threads that stay alive and take tasks from a shared queue. Reusing threads avoids the cost of creating one per unit of work, and capping their number stops the machine being flooded.
ThreadLocal stores a value per thread. get and set see only the current thread's copy. It is a hidden method argument. Clean it up, or a thread pool will leak the value into the next task.
A virtual thread is a lightweight thread scheduled by the JVM onto a small pool of platform threads. You can create millions of them. Blocking a virtual thread does not consume an OS thread for the whole wait (in the usual I/O cases).
volatile makes reads and writes of a field visible across threads and prevents some reorderings. It does not make count++ atomic. Use it for simple flags and for safe publication of a well-formed object.
wait parks the current thread and releases the monitor it holds. notify/notifyAll wakes waiters on that same monitor. You must call them inside synchronized and you must loop on the condition.
Backtracking builds a solution one choice at a time and undoes a choice when it cannot lead to a valid answer. It is depth-first search on an implicit tree of partial answers.
Breadth-first search explores a graph level by level. A queue holds the next nodes. The first time you reach a node in an unweighted graph is a shortest path.
Binary search finds a value in a sorted sequence by repeatedly halving the range it could be in. It takes O(log n) comparisons instead of the O(n) a linear scan needs.
Collections.sort orders the elements of a list in place. It uses TimSort, which is stable and runs in O(n log n) in the worst case.
Depth-first search explores as far as possible along one branch before it backtracks. You implement it with recursion or an explicit stack. It finds cycles, components, and paths; it does not find unweighted shortest paths.
Dijkstra's algorithm finds shortest paths from a source on a graph with non-negative edge weights. A min-heap always expands the closest unsettled node. Negative weights make it incorrect.
Dynamic programming solves a problem by combining answers to overlapping smaller problems. You store each sub-answer so you compute it once. Recursion plus a table, or a bottom-up loop, are the two styles.
A greedy algorithm builds an answer by taking the locally best choice at each step and never revising it. It is fast when a proof says those choices stay optimal. It is wrong when they do not.
Hashing for lookup means using a HashMap or HashSet so a value you have seen can be found in expected O(1) time. It turns nested scans into one pass plus a table.
A prefix sum array stores the sum of every prefix of the input. The sum of a range [left, right] then becomes one subtraction: prefix[right + 1] - prefix[left].
Recursion is when a method solves a problem by calling itself on a smaller version of the same problem. Every recursive method needs a base case that stops the chain.
A sliding window maintains a contiguous segment of an array or string. You grow or shrink the segment as you scan, so each element enters and leaves at most once.
Space complexity describes how much extra memory an algorithm needs as its input grows. In Java that memory includes the call stack, not only the objects you allocate.
Time complexity describes how the amount of work an algorithm does grows as its input grows. It is a shape, not a stopwatch reading.
A topological sort orders the nodes of a directed acyclic graph so every edge goes from earlier to later. If the graph has a cycle, no such order exists.
Two pointers is a technique that walks a sequence with two indexes. They move toward each other, or in the same direction at different speeds, so you finish in one pass instead of nested loops.
Union-find (disjoint-set) keeps a partition of elements into groups. find returns a group's representative. union merges two groups. With path compression and union by rank, both operations are nearly O(1).
A connection pool keeps a set of open database connections and lends them out. Creating a TCP connection and authenticating on every request is too slow. HikariCP is the usual pool in Spring Boot.
Hibernate is an ORM that implements JPA and adds its own APIs. A Session (or EntityManager) tracks entities, generates SQL, and flushes changes on commit.
Isolation levels decide what one transaction can see of another's uncommitted or committed work. JDBC names four: read uncommitted, read committed, repeatable read, and serializable. Higher isolation means fewer anomalies and more waiting.
JDBC is the JDK API for talking to relational databases. A driver implements Connection, Statement, and ResultSet. You write SQL, bind parameters, and read rows.
JPA is the Jakarta persistence API: annotations and interfaces for mapping classes to tables. An EntityManager loads and saves entities. Hibernate is the usual implementation.
The N+1 problem is one query that loads N parent rows, then one query per parent for a child collection. You meant one or two queries. You got 1 + N.
A PreparedStatement is a SQL template with ? placeholders. You bind values with setString, setInt, and the rest. The driver sends data separately from SQL, which stops injection and can reuse a plan.
SQL injection is when untrusted text becomes part of a SQL command. The database then runs the attacker's SQL. Bind parameters. Do not concatenate user strings into queries.
A transaction groups SQL statements so they all commit or all roll back. You start one, work, then commit or rollback. Autocommit mode is one statement per transaction.
CORS is a browser rule that controls which front-end origins may read a response from your API. The server sends Access-Control-Allow-Origin and related headers. It is not an authentication system.
A servlet filter wraps a request before it reaches a servlet and the response on the way out. You use filters for auth, logging, CORS, and wrapping streams. They are a chain of responsibility on HTTP.
HTTP is the request-and-response protocol the web runs on. A client sends a request made of a method, a path, some headers and an optional body, and the server sends back a status code, headers and a body.
JSON is a text format for objects, arrays, and scalars. In Java you map it to records and classes with Jackson, Gson, or Jakarta JSON Binding. HTTP APIs almost always speak JSON.
REST is a style for designing web APIs where the URL names a thing and the HTTP method says what to do with it. GET /orders/42 reads an order, DELETE /orders/42 removes it.
A servlet is a Java class the container calls for an HTTP request. You override doGet or doPost, read the request, write the response. Spring MVC sits on this model even when you never write a servlet yourself.
Spring Boot is an opinionated way to build a Spring application. It auto-configures a web server, JSON, and data sources from the classpath and application.properties, so you start with a runnable jar.
Spring MVC is the web layer that maps HTTP to Java methods. A DispatcherServlet picks a handler, binds parameters, runs interceptors, and writes the body. @RestController is the JSON-facing form.
A status code is the three-digit number at the start of every HTTP response that tells the client what happened. 200 means it worked, 404 means the thing does not exist, 500 means the server broke.
Escape analysis is a JIT optimization that asks whether an object can be seen outside the current compiled method. If it cannot escape, HotSpot may allocate it on the stack or explode it into registers and skip the heap object.
Garbage collection reclaims Java objects that are no longer reachable. You allocate with new. You do not free. The collector finds live objects and recycles the rest.
A GC algorithm is a strategy for finding live objects and reclaiming the rest. HotSpot ships several: Serial, Parallel, G1, ZGC, Shenandoah. They trade pause time, throughput, and memory overhead.
Generational GC splits the heap by object age. Most objects die young, so the collector spends most of its time on a small young generation and promotes only survivors to the old generation.
Interning stores one shared copy of a value and returns that copy for every equal value. In Java, String.intern() is the built-in intern for strings. You can intern other types with a map.
A Java memory leak is an object you no longer need that is still reachable, so the collector cannot free it. The heap grows until the process dies or a cache evicts.
Every Java object carries a small block of bookkeeping data before its fields, called the object header. On a normal 64-bit JVM it is 12 bytes, which is why even an empty object costs 16 bytes after padding.
OutOfMemoryError is thrown when the JVM cannot allocate more memory of a requested kind. The heap is full of reachable objects, or Metaspace, or native memory, depending on the message.
Every Java thread has its own stack holding method calls and local variables. All objects live in one shared heap that the garbage collector manages. Locals hold references; the things they point at are on the heap.
The string pool is a JVM table of unique String instances. Literals and interned strings go there so equal character sequences can share one object.
SoftReference, WeakReference, and PhantomReference point at an object without being ordinary strong references. The collector can reclaim the referent under different rules. You use them for caches, canonical maps, and cleanup hooks.