Q127. What is the var keyword (Java 10)?
Enables local variable type inference — the compiler infers the type from the initializer expression. var list = new ArrayList<String>(); — still statically typed (not dynamic typing); improves readability for verbose generic types, but should be avoided when it reduces clarity.
Q128. What are records (Java 16)?
A concise syntax for immutable data-carrier classes. The compiler automatically generates a canonical constructor, private final fields, accessors, equals(), hashCode(), and toString():
public record Point(int x, int y) {}
Records can implement interfaces and have additional methods/static members, but cannot extend other classes (implicitly extend Record) and cannot add instance fields beyond the declared components.
Q129. What are sealed classes/interfaces (Java 17)?
Restrict which classes/interfaces can extend or implement them, explicitly listed via permits:
public sealed interface Shape permits Circle, Square, Triangle {}
Enables exhaustive pattern matching (the compiler knows all possible subtypes) and more controlled, intentional class hierarchies.
Q130. What is pattern matching for switch (Java 21)?
Extends switch to match on type patterns (and later record deconstruction patterns), with exhaustiveness checking for sealed types:
String describe(Object obj) {
return switch (obj) {
case Integer i when i > 0 -> "positive int";
case Integer i -> "non-positive int";
case String s -> "string: " + s;
default -> "unknown";
};
}
Q131. What are text blocks (Java 15)?
Multi-line string literals using triple quotes ("""), preserving formatting without needing escape characters/concatenation for embedded newlines/quotes — useful for embedded SQL, JSON, or HTML.
String json = """
{
"name": "Java"
}
""";
Q132. What are virtual threads (Java 21, Project Loom)?
Lightweight threads managed by the JVM (not the OS) that make blocking code scale to massive concurrency (millions of threads) without the memory/context-switch overhead of platform (OS) threads. Ideal for high-throughput I/O-bound server applications, allowing simple blocking-style code to achieve reactive-style scalability. Created via Thread.ofVirtual() or Executors.newVirtualThreadPerTaskExecutor().
Q133. What is the difference between local classes, anonymous classes, and lambdas?
- Local class: a named class defined inside a method body.
- Anonymous class: an unnamed class defined and instantiated inline, typically implementing an interface or extending a class with an inline body — creates a real
.classfile andthisrefers to the anonymous instance. - Lambda: a concise syntax specifically for implementing functional interfaces; doesn't create a separate class in the same way (compiled via
invokedynamic), andthisrefers to the enclosing instance (lexical scoping).