BackendBench
Coffee

Unravel › Java concepts

Learn

Java concepts, explained

The 267 ideas that real Java code leans on, each with a mental model, how it works, the usual mistakes and what happens inside. These are the same pages Unravel shows when it finds the concept in your code.

0 of 267
concepts learned

Popular right now

Learning map: 6 sections, 25 topics

Java language

Language basics

11

Program structure, control flow, var, text blocks, static members and the system class.

OOP and types

22

Classes, inheritance, interfaces, records, enums, sealed types, annotations and reflection.

RecordsA record is a compact class for plain data: you list the fields once and Java generates the constructor, getters, equals, hashCode and toStringInterfaces, inheritance and polymorphismAn interface is a contract of methods that classes can promise to provideEnumsAn enum is a fixed set of named constants, such as order statusesLombok annotationsLombok writes boilerplate for you at compile timeequals() and hashCode()equals says when two objects count as the same; hashCode gives a number used to file objects into hash tablesClasses, objects and constructorsA class is a blueprint; an object is one thing built from it with newInheritance, extends and superclass Dog extends Animal makes Dog a specialised Animal: it inherits the fields and methods and may replace (override) some of themAbstract classesAn abstract class is an unfinished class: it can hold shared code and state, and declares abstract methods that every concrete subclass must fill inNested and inner classesA class declared inside another classAnonymous classesAn anonymous class creates and defines a one-off subclass or implementation right where it is used: new Runnable() { public void run() { ..Sealed classes and interfacessealed restricts who may extend or implement a type: sealed interface Shape permits Circle, SquarePattern matching with instanceofif (o instanceof String s) tests the type and gives you a ready-cast variable s in one stepComparable and ComparatorSorting needs a rule for "which comes first"The Object class: toString, getClass, hashCodeEvery class extends Object and inherits toString, equals, hashCode and getClassCopying objects: clone and copy constructorsAssigning an object (b = a) copies the reference, not the objectCustom annotationsAn annotation is a label you attach to code (@Deprecated, @Test)ReflectionReflection lets code look at classes, methods and fields by name at run time, and call or change them, without knowing them at compile timeDynamic proxiesProxy.newProxyInstance builds an object at run time that implements an interface and sends every call to one InvocationHandlerDefault and static interface methodsAn interface method marked default has a body, so implementing classes get it for free and may override itImmutability and final classesAn immutable object never changes after constructionJavaBeans, POJOs and BeanUtilsA JavaBean (or POJO) is a plain class with a no-argument constructor, private fields and public getX/setX methodsEnums with fields and behaviourA Java enum is a full class with a fixed set of instances

Generics and functional

5

Generics, wildcards, lambdas, method references and Optional.

Strings and text

5

String basics, builders, formatting, regular expressions and Unicode.

Numbers and math

7

Floating point, overflow, boxing, BigDecimal, Math, random numbers and bit tricks.

Time and dates

4

java.time, time zones, formatting and the legacy Date classes.

Core library

Collections and streams

17

Lists, maps, sets, queues, iterators, streams and collectors.

StreamsA stream is a pipeline over a sequence of values: start from a source, chain steps such as filter and map, and finish with a terminal step such as collectCollections: List, Set, MapCollections hold groups of objectsArrays and the Arrays utilitiesAn array is a fixed-size row of values of one type, indexed from 0: int[] a = new int[5]ArrayList vs LinkedListArrayList keeps its elements in a resizable array: fast to read by position, slow to insert in the middleHow HashMap worksA HashMap stores each entry in a bucket chosen by the key's hashCode()Map idioms: merge, compute, entrySetA handful of Map methods replace the clumsy "check, get, put" dance: merge for counting, computeIfAbsent for grouping, getOrDefault for lookups with a default, and entrySet for looping over keys and values togetherSets: HashSet, LinkedHashSet, EnumSetA Set holds each element at most onceTreeMap, TreeSet and sorted collectionsTreeMap and TreeSet keep their elements sorted all the time and can answer range questions: the first key, the nearest key below or above a value, everything between two keysQueue, Deque and StackA queue is first-in-first-out (a line at the shop), a stack is last-in-first-out (a pile of plates)PriorityQueue and heapsA PriorityQueue always hands out the smallest element first (or the largest with a reversed comparator), whatever order you added them inIterator and IterableAn Iterator walks through a collection one element at a time (hasNext, next, remove)ConcurrentModificationExceptionThis exception means a collection was changed while a loop was going through itThe Collections utility classCollections has static helpers for lists and sets: sort, reverse, shuffle, max, min, frequency, swap, plus wrappers that make a collection read-only, synchronized or emptyCollectors: groupingBy, toMap, joiningA Collector decides what a stream becomes at the end: a list, a map, a group per key, a count, a joined stringStream operations in depthIntermediate steps (filter, map, flatMap, sorted, distinct, limit) shape the data; terminal steps (reduce, collect, count, anyMatch, findFirst) produce the answerParallel streamslist.parallelStream() splits the work across several threads of the common fork-join poolLegacy collections: Vector, Hashtable, EnumerationVector, Hashtable, Stack, Enumeration and StringTokenizer date from Java 1.0

I/O and files

13

Files, streams, NIO, serialization, sockets, XML, JSON and spreadsheets.

Files and I/OJava reads and writes files with Path and Files (modern) or stream classes (older)File upload and downloadUploads arrive as multipart form data and downloads are streams with a Content-Disposition headerJava serialization and its risksJava can turn an object graph into bytes (Serializable) and backCSV and Excel file processingBusiness systems constantly import and export CSV and Excel filesSFTP and file transfer clientsMany partners still exchange files over SFTP or FTPProperties files, Locale and resource bundlesProperties loads key=value text files into a mapByte streams, readers and writersJava has two families for moving data: byte streams (InputStream, OutputStream) for raw bytes, and character readers and writers (Reader, Writer) that decode bytes to text with a charsetNIO.2: Path and Files in practicePath describes a location and Files does the work: read, write, copy, move, list and deleteJava serializationSerialization turns an object graph into bytes (ObjectOutputStream) and back (ObjectInputStream)Sockets, URLs and networkingA Socket is one end of a TCP connection: you write bytes in and read bytes outXML parsing: DOM, SAX, StAXJava reads XML three ways: DOM loads the whole document into a tree you can query, SAX and StAX stream through it event by event, and JAXB or Jackson XML map elements onto classesGson and other JSON APIsGson, org.json and JSON-B are other ways to turn JSON into Java objects and backZIP and GZIP compressionGZIPOutputStream compresses a single stream; ZipOutputStream bundles many named entries into one archive

Errors and logging

8

Exceptions, try-with-resources, custom errors, assertions and logging.

Testing

13

JUnit, Mockito, AssertJ, Spring slices, containers and fake services.

JUnit testsA JUnit test is a method annotated with @Test that sets something up, runs the code under test and asserts the expected resultMockito mocksMockito creates fake versions of a class's collaborators so a test can control what they return and check how they were used, without a real database or networkTesting Kafka codeKafka code is tested at three levels: unit tests with mock producers and consumers, topology tests for Kafka Streams without a broker, and integration tests against a real broker started by the test (embedded or in a container)Spring Boot test slices and test configurationA full @SpringBootTest starts the whole application, which is slowTesting HTTP endpoints (MockMvc, WebTestClient, REST Assured)These tools call your endpoints from a test and check status, headers and JSON bodyTestcontainers (real databases and brokers in tests)Testcontainers starts real services (PostgreSQL, Kafka, Redis, Elasticsearch) in Docker for the duration of a testFaking remote services (WireMock, MockWebServer, Pact)To test code that calls another service, you stand up a fake HTTP server that returns the answers you script: successes, errors, slow responses and broken connectionsAdvanced JUnit 5 and async assertionsBeyond simple @Test methods, JUnit 5 supports parameterised tests, nested test groups, temporary directories, conditional execution and custom extensionsAdvanced Mockito (matchers, captors, static mocks)Mockito does more than when(...).thenReturn(...)AssertJ fluent assertionsAssertJ makes test assertions read like sentences: assertThat(orders).hasSize(2).extracting(Order::id).containsExactly(1, 2)JUnit 5: parameterized tests and lifecycleA @ParameterizedTest runs one test method many times with different inputs from @ValueSource, @CsvSource or @MethodSourceMockito: matchers, verification, spiesBeyond when(...).thenReturn(...): argument matchers (any(), eq()), verification modes (times(2), never()), inOrder, captured arguments, spies (real objects with some methods replaced) and doReturn().when(spy)JUnit 4 and HamcrestJUnit 4 is the older test framework still found in many projects: @Before/@After, @RunWith, @Rule, @Test(expected = ...) and org.junit.Assert

Runtime and design

Concurrency

18

Threads, locks, executors, futures, virtual threads and the memory model.

Threads and shared stateA thread is an independent path of executionsynchronized and lockssynchronized lets only one thread at a time run a block of code on a given lock object, protecting shared data from interleaved accessReentrantLock and ReadWriteLockThe java.util.concurrent.locks classes are explicit versions of synchronized with extras: try without waiting, time out, separate read and write access, and more than one conditionvolatile and atomic classesAtomic classes update a single value as one indivisible step without a lockExecutors and thread poolsAn executor runs tasks on a reusable pool of threadsCompletableFutureCompletableFuture represents a result that will arrive laterConcurrent collectionsConcurrent collections are safe to share between threadsDistributed locks and job locking (ShedLock)When several copies of an application run at once, an ordinary synchronized or ReentrantLock only protects one copyRunnable, Callable and FutureA Runnable is a task that returns nothing; a Callable<V> returns a value and may throwInterruption and InterruptedExceptioninterrupt() is a polite request: "please stop what you are doing"Latches, barriers and semaphoresThese classes coordinate threads: CountDownLatch waits until N things have happened, CyclicBarrier makes threads wait for each other, Semaphore limits how many threads may enter at onceProducer-consumer with blocking queuesOne group of threads produces work, another consumes it, and a BlockingQueue sits between them: put waits when the queue is full, take waits when it is emptyThreadLocal and scoped valuesA ThreadLocal<T> gives every thread its own private copy of a variableVirtual threadsA virtual thread is a very cheap thread managed by the JVM instead of the operating systemFork/Join and divide and conquerFork/Join splits a big job into smaller pieces recursively, runs the pieces on a pool of threads, and joins the resultsTimers and scheduled executorsScheduledExecutorService runs a task after a delay or repeatedlyVisibility and the Java Memory ModelWithout synchronisation one thread may never see another thread's writes, or may see them in a surprising orderRace conditions and deadlocksA race condition is a bug where the result depends on the timing of threads (two threads both do "check, then act")

JVM and performance

7

Memory, garbage collection, class loading, leaks and benchmarking.

Design patterns and architecture

16

Classic patterns, SOLID, layering and distributed-system patterns.

Transactional outbox patternSaving to the database and publishing a message are two separate actions, and a crash between them loses or invents eventsSagas and distributed transactionsA business process that spans several services cannot use one database transactionIdempotency and duplicate handlingNetworks and message brokers repeat things: a client retries, a broker redeliversCQRS and event sourcingCQRS separates writing (commands that change state) from reading (queries over a shape built for the screen)DTOs and object mapping (MapStruct, ModelMapper)A DTO (data transfer object) is a plain class that carries data across a boundary (API, message) and is shaped for that boundaryLayered and hexagonal architectureEnterprise code is usually split into layers (controller, service, repository) so that each class has one jobSingleton patternA singleton guarantees one shared instance of a class: a private constructor plus a static accessorBuilder patternA builder creates a complex object step by step with readable, named steps (Pizza.builder().size(12).cheese(true).build()), instead of one constructor with many positional parametersFactory patternA factory creates objects for you, hiding which concrete class is chosen: PaymentFactory.create("card") returns a CardPayment behind a Payment interfaceStrategy patternThe strategy pattern puts interchangeable behaviours behind one interface and lets the caller pick one: a PricingStrategy for regular customers and another for membersObserver and event listenersIn the observer pattern an object (the subject) keeps a list of listeners and tells all of them when something happensDecorator and wrapper classesA decorator wraps an object of the same interface and adds behaviour before or after delegating: new BufferedReader(new FileReader(f)) adds buffering to a plain readerVisitor patternThe visitor pattern lets you add new operations to a family of classes without changing them: each element has an accept(visitor) method that calls back visitor.visit(this), and the visitor decides what to do for each typeTemplate method patternA base class defines the fixed skeleton of an algorithm in a final method and leaves some steps as abstract or overridable hooks that subclasses fill inDAO and repository patternA DAO (data access object) or repository hides how data is stored behind a small interface such as OrderRepository.findById(id)SOLID principlesSOLID is five guidelines for classes that are easy to change: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion

Algorithms and data structures

11

Big-O, recursion, searching, sorting, dynamic programming, trees and graphs.

Spring and frameworks

Spring and Boot

13

Beans, proxies, configuration, auto-configuration, events, async and validation.

Spring beans and dependency injectionSpring creates your objects (beans) and hands each one the other objects it needs, so classes declare their dependencies and never build them with newSpring proxies (how annotations work)Annotations like @Transactional, @Async and @Cacheable work through a proxy: Spring wraps your bean in a stand-in object that adds behaviour before and after your method@Transactional@Transactional makes a method run inside a database transaction: all its database changes commit together if it finishes normally and are rolled back together if it throws@Async@Async makes a call return immediately while the method body runs on another thread from a poolSpring application eventsEvents let one bean announce "something happened" without knowing who caresSpring configuration propertiesSpring reads settings from application.yml, environment variables and command-line flags, and injects them into beans with @Value or @ConfigurationProperties, so behaviour changes per environment without rebuildingBean validation (@Valid)Bean validation lets you declare rules on fields (@NotBlank, @Size(max = 50), @Email) and have the framework check themSpring caching@Cacheable stores a method's result under a key built from its argumentsSpring Boot auto-configuration and startersSpring Boot looks at the libraries on your classpath and your properties, and configures sensible beans for you (a web server, a data source, a JSON mapper) unless you define your own@Configuration, @Bean and bean wiringA @Configuration class is a recipe for creating beans in plain JavaBean lifecycle and startup hooksSpring runs code at fixed moments in a bean life: right after it is built and wired, when the application is ready, and just before it is thrown awayWriting aspects (@Aspect, pointcuts, advice)An aspect is code that you attach to many methods at once (timing, audit logging, permission checks) without editing themTransaction propagation and isolationPropagation decides what happens when a transactional method calls another transactional method (join the current transaction or start a new one)

Scheduling and batch

4

Scheduled jobs, cron, Quartz, batch processing.

Jakarta and other frameworks

5

CDI, EJB, Quarkus, Micronaut and Vert.x.

Data and messaging

Persistence and JPA

13

Entities, relationships, lazy loading, queries, locking and migrations.

Spring Data repositoriesA Spring Data repository is an interface onlyJPA entitiesAn entity is a Java class mapped to a database table: each instance is a row, each field a columnLazy loading and the N+1 query problemRelations between entities are often loaded lazily, one extra query on first accessReactive data access (R2DBC and reactive repositories)Reactive repositories return Mono and Flux instead of blocking until the database answers, so a few threads can serve many concurrent requests while the database is workingDynamic queries (Specifications, Example, Querydsl)When search filters are optional (name, status, date range), you cannot write one fixed query methodJPA relationships, cascade and orphan removalRelationship mappings tell JPA how tables are linkedOptimistic and pessimistic lockingTwo users editing the same record at the same time is the lost-update problemJPA inheritance mappingObject models have inheritance (a Payment is a CardPayment or a BankTransfer) but tables do notPersistence context, flush and dirty checkingInside a transaction, JPA keeps every entity it has loaded in a first-level cache and watches it for changesJPQL, native queries and the Criteria APIJPQL is SQL written against your entity classes and fields instead of tables and columnsAuditing, lifecycle callbacks and soft deleteMany tables need "who and when": created and modified timestamps, the user who did it, and sometimes a flag instead of real deletionDatabase migrations (Flyway, Liquibase)A migration tool applies numbered SQL scripts to the database in order and remembers which ones ran, so every environment, from a laptop to production, ends up with exactly the same schemaConnection pools (HikariCP)Opening a database connection is slow, so applications keep a small pool of open connections and lend them out

JDBC and SQL mappers

6

Prepared statements, connections, result sets, batching and jOOQ or MyBatis.

NoSQL and caches

6

Redis, MongoDB, Elasticsearch, Cassandra, DynamoDB and local caches.

Messaging and Kafka

19

Topics, consumers, offsets, streams, plus RabbitMQ, JMS and cloud queues.

Kafka topics, partitions and eventsKafka is a durable log of eventsKafka producerA producer sends events to a topicKafka consumer and the poll loopA consumer reads events from a topic in a loopConsumer groupsA consumer group is a set of consumers that share one jobOffsets and commitsAn offset is a record's position in a partitionRebalancingA rebalance is Kafka reshuffling which consumer owns which partition, triggered by a member joining, leaving, crashing or being too slowSerializers and deserializersKafka stores only bytesSpring Kafka @KafkaListenerSpring Kafka runs the poll loop for youRetries and dead-letter topicsWhen a record cannot be processed, a Kafka consumer must not block forever and must not silently drop itSpring Integration (channels and flows)Spring Integration implements classic enterprise integration patterns in-process: messages travel over channels, and small components filter, transform, route, split and aggregate themKafka StreamsKafka Streams is a library for processing topics as continuous streams inside your own application: filter, transform, join and aggregate events, with state kept locally and backed up to KafkaKafka idempotent producer and transactionsTwo features make Kafka writes safer: the idempotent producer removes duplicates caused by retries, and transactions write to several partitions and commit consumer offsets all-or-nothingSchema Registry, Avro and ProtobufA schema registry stores the structure of messages (Avro, Protobuf or JSON Schema) and checks that producers and consumers change it compatiblyKafka Connect connectorsKafka Connect moves data between Kafka and other systems (databases, search, object storage) using ready-made connectors that you configure instead of coding consumers and producersRabbitMQ and AMQP messagingRabbitMQ is a message brokerJMS and ActiveMQ messagingJMS is the standard Java API for message brokers (ActiveMQ, IBM MQ, Artemis)AWS SQS and SNS messagingSQS is a managed queue and SNS is a managed publish-subscribe topicAzure Service Bus, Event Hubs and Google Pub/SubAzure and Google offer managed brokers (Service Bus and Event Hubs; Pub/Sub)Apache Camel integration routesApache Camel connects systems with routes: take a message from one endpoint (file, queue, HTTP, database), transform and route it, and deliver it to another

APIs, security and cloud

APIs and web

19

REST, JSON, OpenAPI, GraphQL, gRPC, WebSockets, filters and HTTP clients.

Spring REST controllersA controller maps HTTP requests to Java methodsJackson JSONJackson converts between Java objects and JSONHTTP clientsAn HTTP client calls another service over the networkCentral error handling and ProblemDetailInstead of try/catch in every controller, one advice class maps each exception type to an HTTP status and a consistent error body, so clients always get the same shape of errorServlets, filters and interceptorsEvery Java web request passes through the servlet layerDeclarative HTTP clients (Feign, HTTP interfaces)You write a Java interface describing a remote REST API with annotations, and the framework generates the HTTP client behind itReactive programming (Reactor Mono and Flux)Reactive code describes a pipeline for data that arrives over timeStreaming responses and Server-Sent EventsInstead of answering once, a streaming endpoint keeps the HTTP connection open and sends several pieces over time: progress updates, live events, or a big file written as it is generatedWebSockets and STOMP messagingA WebSocket is a long-lived two-way connection between browser and server, so either side can send at any timeRate limiting and throttlingA rate limiter caps how many requests a client or operation may make per time windowOpenAPI and Swagger documentationOpenAPI is a machine-readable description of a REST APIgRPC services and clientsgRPC is a fast, typed way for services to call each otherGraphQL serversGraphQL lets the client ask for exactly the fields it needs in one requestJAX-RS (Jakarta REST) resourcesJAX-RS, now Jakarta REST, is the standard annotation model for REST in Java EE and Jakarta EE servers and in QuarkusCustom Jackson serialization and modulesWhen default JSON mapping is not enough (dates in a special format, money as a string, hiding fields per audience, circular references), Jackson can be tuned with annotations, features and custom serializers registered in modulesXML, YAML, Gson and ProtobufEnterprise systems exchange data in many formats besides JSON: XML (SOAP, legacy and government feeds), YAML configuration, Gson in older code, and Protobuf for compact internal messagesSending email (JavaMail, Spring Mail)Applications send email for receipts, resets and alerts through an SMTP serverSOAP and JAX-WS web servicesSOAP is an older, XML-based way for systems to call each other, still common in banking, insurance and governmentThe built-in HTTP servercom.sun.net.httpserver.HttpServer is a tiny web server inside the JDK

Security

11

Spring Security, tokens, OAuth2, CORS, passwords, hashing, encryption and TLS.

Cloud and operations

11

Cloud SDKs, containers, secrets, tracing, metrics, health and resilience.

Libraries and tooling

3

Guava, Apache Commons and MapStruct.