skip to content

Modern / Recent Platform Additions

The recent platform additions that do not belong to any older topic: JShell, the standard HTTP client, single-file execution, helpful NullPointerExceptions, sequenced collections, and the foreign-memory and vector APIs. Interviewers use them to gauge whether you have kept up past Java 8.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

page 1 of 2

What are the three core types in java.net.http, and how do they fit together to make an HTTP call?

level: juniorimportance: must knowfreq 70%

answer

  1. HttpClient = reusable engine + connection pool
  2. HttpRequest = one immutable call (uri/method/headers/body)
  3. HttpResponse<T> = statusCode/headers/body
  4. BodyPublisher sends body, BodyHandler shapes the reply
  5. newHttpClient() / newBuilder() / send()

basics

~10 s

You build an HttpClient once, create an HttpRequest describing the URL/method/headers, then call client.send(request, handler). The result is an HttpResponse holding the status code, headers, and body.

solid answer

~40 s

The API revolves around three immutable types. HttpClient is the long-lived, reusable, thread-safe object that holds configuration (HTTP version, redirect policy, connection pool, executor) — you build one and share it. HttpRequest describes a single call: URI, method, headers, and an optional body supplied by a BodyPublisher. HttpResponse<T> is the result, exposing statusCode(), headers(), and body() where T is whatever a BodyHandler produced (a String, byte[], Path, Stream<String>, etc.). The typical flow: HttpClient.newHttpClient(), then HttpRequest.newBuilder(uri).GET().build(), then client.send(request, BodyHandlers.ofString()). Builders make requests/clients immutable and safe to reuse. The handler is what turns raw response bytes into the typed body, so the same request can yield a String or be streamed to a file just by swapping the handler.

go deeper

for a junior

Can name the three types and write the basic GET-to-String flow, knowing the status code lives on the response.

for a middle

Explains immutability, the BodyPublisher vs BodyHandler split, and why the client is shared/thread-safe.

for a senior

Discusses connection pooling, HTTP/2 default, and that non-2xx is not an exception; reasons about handler choice (ofString vs ofFile vs streaming) for memory.

for a principal

Frames the API as a clean separation of configuration (client), intent (request), and delivery (handler), and weighs it against alternatives (OkHttp, WebClient) for a platform standard.

## What is HTTP and why this API exists HTTP (HyperText Transfer Protocol) is the request/response protocol the web runs on: a *client* sends a request (a method like GET, a URL, headers, optionally a body) to a *server*, which returns a *response* (a numeric status code such as 200, response headers, and a body). Before Java 11, the standard way to do this from Java was `HttpURLConnection`, a clunky 1990s API. `java.net.http` (incubated in Java 9, standardized in Java 11) is the modern replacement. ## The three core types **1. `HttpClient`** — the *engine*. It is configured once and reused for many requests. It holds: - the HTTP protocol version to prefer (HTTP/2 by default, falling back to HTTP/1.1), - a **connection pool** (reusable TCP/TLS connections so you don't pay handshake cost every call), - redirect policy, proxy, authenticator, and an `Executor` (thread pool) for async work. You create it with `HttpClient.newHttpClient()` (defaults) or `HttpClient.newBuilder()....build()`. It is **immutable and thread-safe**, so one instance should be shared across your application — creating a new client per request wastes the connection pool and threads. **2. `HttpRequest`** — a *value object* describing ONE call. Built via `HttpRequest.newBuilder()`: - `.uri(URI.create("https://..."))` — where to send it, - the method: `.GET()`, `.POST(bodyPublisher)`, `.PUT(...)`, `.DELETE()`, or `.method(name, publisher)`, - `.header(name, value)` / `.headers(...)` — request headers, - `.timeout(Duration)` — per-request timeout. A **`BodyPublisher`** supplies the request body for methods that have one (e.g. `BodyPublishers.ofString(json)`). `HttpRequest` is immutable once built. **3. `HttpResponse<T>`** — the *result*. Its type parameter `T` is the shape of the body you asked for. Key methods: - `statusCode()` → an `int` (200, 404, 500…), - `headers()` → an `HttpHeaders`, - `body()` → the typed body `T`, - `uri()` (final URI after redirects), `version()`. The `T` is decided by a **`BodyHandler<T>`** you pass to `send`. `BodyHandlers.ofString()` gives `HttpResponse<String>`; `BodyHandlers.ofByteArray()` gives `byte[]`; `BodyHandlers.ofFile(path)` streams straight to disk and gives `Path`. The handler decouples *what request you make* from *how you want the body delivered*. ## Putting it together ```java HttpClient client = HttpClient.newHttpClient(); // reuse this HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); int code = response.statusCode(); // e.g. 200 String body = response.body(); // the response text ``` ## Mental model Think of `HttpClient` as a *telephone* (set up once, dial many times), `HttpRequest` as the *message you want to send*, the `BodyHandler` as *how you want the reply written down*, and `HttpResponse` as *the reply itself*. The builder pattern and immutability mean each piece is safe to reuse and free of hidden mutable state.

  • Why is HttpClient meant to be shared rather than created per call?
    It owns a connection pool and an executor; reusing it lets TCP/TLS connections be kept alive and reused, avoiding repeated handshakes, and avoids spinning up redundant thread pools.
  • Does a 404 or 500 response cause send() to throw?
    No. Those are valid HTTP responses; send() returns normally and you inspect statusCode(). Exceptions are thrown for I/O failures, timeouts, or interruption — not for non-2xx statuses.

saying these in an interview costs you the question

  • Creating a new HttpClient per request (wastes the connection pool and threads)
  • Thinking HttpResponse exposes the body type without a BodyHandler
  • Confusing BodyPublisher (request body) with BodyHandler (response body)
  • Believing the client throws on a 404/500 — non-2xx statuses are normal responses, not exceptions

context

open as a page

What are Sequenced Collections (JEP 431, Java 21), and what problem do they solve?

level: juniorimportance: must knowfreq 62%

basics

~20 s

They are new interfaces (SequencedCollection, SequencedSet, SequencedMap) added in Java 21 that give collections with a defined order a uniform way to access and add elements at the front and back, plus a reversed() view.

open as a page

Explain MemorySegment and Arena, and how an Arena gives off-heap memory a safe, deterministic lifetime.

level: middleimportance: must knowfreq 55%

basics

~20 s

A MemorySegment is a sized region of memory you can read and write. An Arena decides when that memory is freed: you allocate from the arena, and when you close the arena (usually with try-with-resources) all its memory is released at once and the segments become unusable.

open as a page

What is the difference between HttpClient.send() and sendAsync(), and when would you use each?

level: middleimportance: must knowfreq 68%

basics

~10 s

send() is synchronous: it blocks the calling thread until the response arrives and returns the HttpResponse directly. sendAsync() is non-blocking: it returns immediately with a CompletableFuture that completes later with the response.

open as a page

What is the difference between String.strip() and String.trim() in Java, and why was strip() added?

level: middleimportance: must knowfreq 70%

basics

~10 s

Both remove leading and trailing whitespace. trim() (old) only removes characters up to and including space (U+0020). strip() (Java 11) is Unicode-aware, so it also removes Unicode whitespace like non-breaking-aware spaces and ideographic spaces.

open as a page

What is the Foreign Function & Memory API in Java, and why was it added?

level: juniorimportance: should knowfreq 45%

basics

~20 s

It's a standard Java API (in java.lang.foreign, final in Java 22) that lets Java safely use memory outside the normal Java heap and call functions written in other languages like C, without writing extra C glue code.

open as a page

What is a Helpful NullPointerException in Java, and what does it add over a plain NullPointerException?

level: juniorimportance: should knowfreq 55%

basics

~10 s

It is an NPE whose message names exactly which variable or part of an expression was null, instead of just blaming the whole line. That makes the cause obvious at a glance.

open as a page

What is JShell, and why would you use it instead of writing a full class with a main method?

level: juniorimportance: should knowfreq 45%

basics

~20 s

JShell is Java's interactive shell (a REPL) added in Java 9. You type a line of Java, press Enter, and see the result immediately—no class, no main method, no compile-and-run cycle. It's great for quick experiments and learning.

open as a page

What does String.isBlank() do (Java 11), and how does it differ from isEmpty()?

level: juniorimportance: should knowfreq 55%

basics

~20 s

isEmpty() is true only when the string has length 0. isBlank() (Java 11) is true when the string is empty OR contains only whitespace characters. So " ".isBlank() is true but " ".isEmpty() is false.

open as a page

What is single-file source-code execution in Java, and how do you run a .java file without compiling it first?

level: juniorimportance: should knowfreq 55%

basics

~10 s

Since Java 11 you can run a single .java file directly with java MyApp.java. The launcher compiles it in memory and runs it immediately, so you don't need a separate javac step.

open as a page

How do you enable Helpful NullPointerExceptions, and in which Java versions are they available or on by default?

level: middleimportance: should knowfreq 48%

basics

~10 s

They arrived in Java 14, where you turn them on with the JVM flag -XX:+ShowCodeDetailsInExceptionMessages. From Java 15 onward they are on by default.

open as a page

Given a chained dereference that throws, how does a Helpful NullPointerException pinpoint the exact failing part, and what does the message look like for fields, methods, and array access?

level: middleimportance: should knowfreq 42%

basics

~10 s

The message names both the failed operation and the null sub-expression, e.g. 'Cannot read field x because y is null'. So on a long chain you instantly see which link was null.

open as a page

Explain BodyPublishers and BodyHandlers: what each is for, and give examples of common ones.

level: middleimportance: should knowfreq 55%

basics

~20 s

A BodyPublisher supplies the request body you send (e.g. a string or file). A BodyHandler decides how the response body is delivered to you (e.g. as a String, byte array, or written to a file). They are opposite ends: outgoing vs incoming body.

open as a page

What are JShell commands like /list, /vars, /edit, /save, /open, and how do you load or save scripts?

level: middleimportance: should knowfreq 35%

basics

~20 s

JShell commands start with a slash and control the session rather than running Java. For example /list shows your snippets, /vars lists variables, /edit opens an editor, /save file writes snippets to a file, and /open file runs a script of snippets.

open as a page

What kinds of snippets can JShell evaluate, and what are implicit/scratch result variables?

level: middleimportance: should knowfreq 40%

basics

~20 s

JShell accepts expressions, statements, and declarations (variables, methods, classes). When you type an expression with no name, JShell stores its value in an automatically named variable like $1 or $2 so you can reuse the result on the next line.

open as a page

What does String.lines() return, and why is it preferable to split("\n") for processing text line by line?

level: middleimportance: should knowfreq 50%

basics

~10 s

lines() (Java 11) returns a Stream<String> of the lines in the text, splitting on line terminators (\n, \r, \r\n) without keeping them. It is lazy and handles all line-ending styles, unlike split("\n").

open as a page

What methods does SequencedMap add, and what do putFirst/putLast do?

level: middleimportance: should knowfreq 38%

basics

~20 s

SequencedMap adds firstEntry/lastEntry and pollFirstEntry/pollLastEntry to read or remove the end entries, putFirst/putLast to insert at the front or back, reversed() for a reverse-order view, and sequencedKeySet/values/entrySet views. putFirst/putLast set a mapping and move that key to the chosen end (for insertion-ordered maps).

open as a page

Which existing collection types now implement the Sequenced interfaces, and which do not?

level: middleimportance: should knowfreq 48%

basics

~10 s

Types with a defined order implement them: List (so ArrayList, LinkedList), Deque (ArrayDeque, LinkedList), LinkedHashSet, SortedSet/NavigableSet (TreeSet) are SequencedCollection/SequencedSet; LinkedHashMap and SortedMap/NavigableMap (TreeMap) are SequencedMap. Unordered types like HashSet and HashMap do not.

open as a page

What are the limitations of single-file source-code execution, and when should you use a build tool instead?

level: middleimportance: should knowfreq 48%

basics

~20 s

It runs only one .java file — it can't compile several source files that depend on each other, and it writes no .class output. Use a real build tool (Maven/Gradle) once your project spans multiple files or needs dependencies and packaging.

open as a page

Explain VectorSpecies, lanes, and SPECIES_PREFERRED in the Vector API. How do you size a vector loop correctly?

level: middleimportance: should knowfreq 30%

basics

~20 s

A VectorSpecies says what element type and how many slots (lanes) a vector holds. SPECIES_PREFERRED picks the best size for the current CPU. You step the loop by species.length() and use a tail loop for leftover elements.

open as a page

What is the Java Vector API, and what problem does it solve compared to ordinary scalar arithmetic loops?

level: middleimportance: should knowfreq 35%

basics

~20 s

The Vector API lets you write a loop that processes several array elements at once instead of one at a time. It maps your code to special CPU instructions (SIMD) so number-heavy work runs much faster.

open as a page

How do you call a native C function from Java with the Linker (downcall), and what is an upcall?

level: seniorimportance: should knowfreq 42%

basics

~20 s

A downcall is Java calling into C: you get the Linker, look up the function's address, describe its signature with a FunctionDescriptor, and get a MethodHandle you can invoke. An upcall is the reverse — you wrap a Java method as a function pointer so C can call back into Java.

open as a page

How do MemoryLayout and VarHandle enable structured, type-safe access to native memory (e.g. reading a C struct)?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A MemoryLayout describes the shape of memory — the fields, their types, sizes, and offsets — like a blueprint of a C struct. From a layout you derive a VarHandle, a precomputed accessor that reads or writes one field at the right offset, so you don't compute byte offsets by hand.

open as a page

What out-of-the-box behaviors does the java.net.http client provide for HTTP/2, redirects, timeouts, and authentication?

level: seniorimportance: should knowfreq 48%

basics

~20 s

The client speaks HTTP/2 by default (falling back to HTTP/1.1), can follow redirects based on a configured policy, supports a connect timeout on the client and a per-request timeout, and can authenticate via a configured Authenticator or by adding an Authorization header yourself.

open as a page

What does reversed() return, and how does it behave with respect to the underlying collection?

level: seniorimportance: should knowfreq 40%

basics

~20 s

reversed() returns a view of the same collection in opposite order, not a copy. It is backed by the original, so reads reflect later changes, and supported writes on the view (like addFirst) modify the original.

open as a page

What are masks in the Vector API, and how do they let you handle loop tails and conditional (branchless) computation?

level: seniorimportance: should knowfreq 25%

basics

~20 s

A mask is a per-lane on/off switch. It tells an operation which lanes to actually apply to. You use it to safely process a partial final chunk of an array and to do if-style logic without branches by selecting values per lane.

open as a page

Why does the FFM API supersede JNI and sun.misc.Unsafe, and what trade-offs and risks should you weigh before adopting it?

level: principalimportance: should knowfreq 35%

basics

~20 s

FFM replaces JNI (which needed fragile handwritten C glue) and Unsafe (an internal, crash-prone API) with one safe, pure-Java, standard API. It adds bounds and lifetime safety, no separate C build step, and good performance — but it still crosses a native boundary, needs the right JDK and sometimes runtime flags, and native calls can still crash if signatures are wrong or memory is misused.

open as a page

What does String.repeat(int) do, and what are its edge cases and uses?

level: juniorimportance: nice to knowfreq 40%

basics

~10 s

repeat(n) (Java 11) returns a new string formed by concatenating this string n times. "ab".repeat(3) is "ababab". repeat(0) gives "", and a negative count throws IllegalArgumentException.

open as a page

How does single-file source execution compare with JShell, and when would you choose each?

level: middleimportance: nice to knowfreq 35%

basics

~20 s

JShell is an interactive prompt (REPL) where you type and evaluate code line by line. Single-file execution runs a whole small program from a .java file in one command. Use JShell to explore; use single-file mode to run a script.

open as a page

What are the limitations, costs, and security trade-offs of Helpful NullPointerExceptions in production?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

It only improves the message, never prevents the NPE. Building the message costs a little, but only when an NPE actually happens. The message can include variable names, so don't show it to untrusted users.

open as a page

showing 1–30 of 40