Java
Recruitment and knowledge question base. Filter, search and test your knowledge.
easyooppolymorphismjava+1
Answer
Polymorphism lets you treat different objects through the same interface or superclass. Calling an overridden method on a base reference uses dynamic dispatch to run the concrete implementation at runtime; overloading provides compile‑time polymorphism.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks
}
}mediumexceptionerror-handlingjava
Answer
Checked exceptions must be caught or declared in a method’s throws clause (e.g., IOException) and represent recoverable conditions. Unchecked exceptions extend RuntimeException (e.g., NullPointerException) and usually signal programming errors; handling them is optional.
mediumoopinterfaceabstract-class+2
Answer
An interface defines a contract; a class can implement many interfaces and interfaces can have default/static methods but no instance state. An abstract class can hold fields, constructors and partial implementation, but a class can extend only one. Use interfaces for capabilities and abstract classes for shared base behavior.
easystringimmutabilitymemory+1
Answer
String is immutable so it can be safely shared between threads, cached/interned in the String pool, and reliably used as a key in hash‑based collections (stable hashCode). It also improves security because values like class names or file paths can’t be modified after creation.
mediummemorystackheap+2
Answer
The stack is per‑thread memory holding call frames, local primitives and references; it’s allocated/deallocated on method entry/exit and is very fast. The heap is shared memory where all objects and arrays live; it’s managed by the garbage collector and objects usually outlive a single method call.
easyequalsreferencestring
Answer
`==` compares references for objects (same instance), while `.equals()` compares logical equality as defined by the class (e.g., `String` compares content). For primitives, `==` compares values.
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // trueeasyfinalinheritancejava-basics
Answer
A `final` variable can’t be reassigned, a `final` method can’t be overridden, and a `final` class can’t be extended. (It does not automatically make an object immutable.)
easystringstringbuilderperformance
Answer
`String` is immutable, so repeated concatenation creates many objects. `StringBuilder` is mutable and fast for building strings in a single thread; `StringBuffer` is similar but synchronized (rarely needed today).
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
sb.append(i).append(",");
}
System.out.println(sb.toString());mediumexceptionscheckedruntimeexception
Answer
Checked exceptions must be declared or handled at compile time (they extend `Exception` but not `RuntimeException`). Unchecked exceptions (`RuntimeException`) don’t require it and usually indicate programming errors or invalid state.
mediumautoboxingwrappernpe
Answer
Autoboxing converts primitives to wrappers (e.g., `int`→`Integer`) and unboxing does the reverse. Pitfalls: unboxing `null` causes NPE, `Integer` caching can confuse `==`, and extra allocations can hurt performance in hot code.
Integer x = null;
// int y = x; // NullPointerException due to unboxing
Integer a = 100;
Integer b = 100;
System.out.println(a == b); // true (Integer cache)
Integer c = 1000;
Integer d = 1000;
System.out.println(c == d); // falsemediumhashmapconcurrencyconcurrenthashmap
Answer
`HashMap` is not thread-safe; concurrent writes can corrupt it. `ConcurrentHashMap` supports safe concurrent access with good performance (and disallows null keys/values). Use it when multiple threads read/write without external locking.
hardequalshashcodehashmap
Answer
If two objects are equal according to `equals()`, they must have the same `hashCode()`. Hash-based collections (HashMap/HashSet) rely on it; breaking the contract leads to “missing” entries and hard-to-debug behavior.
final class User {
private final String email;
User(String email) {
this.email = email;
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
return email.equals(((User) o).email);
}
@Override public int hashCode() {
return email.hashCode();
}
}hardconcurrencyvolatilesynchronized
Answer
`volatile` guarantees visibility (and ordering) of a variable between threads, but doesn’t make compound operations atomic. `synchronized` provides mutual exclusion and also establishes happens-before (visibility) for the protected code.
class StopFlag {
private volatile boolean stop = false;
void requestStop() {
stop = true;
}
void runLoop() {
while (!stop) {
// do work
}
}
}Answer
The heap is typically split into young/old generations: most objects die young, so collecting the young gen is cheap and frequent (minor GC). Surviving objects are promoted; old gen collections are rarer and usually more expensive.
hardcompletablefutureasyncconcurrency
Answer
It represents an async computation that you can compose (`thenApply/thenCompose`) without blocking. A common pitfall is calling `get()/join()` too early (turning it back into blocking code) or forgetting to handle exceptions (`exceptionally/handle`).
CompletableFuture<Integer> result = CompletableFuture
.supplyAsync(() -> 40)
.thenApply(x -> x + 2)
.exceptionally(e -> 0);
System.out.println(result.join());easystaticclassoop
Answer
`static` means it belongs to the class, not to a specific instance. A static field is shared by all objects, and a static method can be called without creating an instance (but it can’t access instance fields directly).
mediumsethashsettreeset+2
Answer
HashSet is usually faster for add/contains (average O(1)) because it’s hash-based. TreeSet keeps elements sorted (balanced tree), so operations are O(log n) but you get ordering and range queries.
mediumoptionalnull-safetyapi
Answer
`Optional` represents a value that may be present or absent and forces the caller to handle the empty case. A common misuse is using it as a field in entities/DTOs everywhere; it’s mainly intended for return values, not for serialization or persistence fields.
Optional<User> user = repo.findById(id);
String name = user.map(User::getName).orElse("unknown");hardmemory-leakgcreferences+1
Answer
GC frees only objects that are unreachable. If you keep references by mistake (e.g., a static list/map that grows, caches without eviction, listeners not removed), objects stay reachable and memory usage grows.
hardconcurrencyarraylistthread-safety+1
Answer
`ArrayList` has no synchronization, so concurrent writes can corrupt its internal state or cause inconsistent reads. Options: external locking, `Collections.synchronizedList`, `CopyOnWriteArrayList` for mostly-reads, or using concurrent queues depending on the use case.
easyinterfaceabstract-classoop
Answer
An interface defines a contract (what methods exist) and supports multiple inheritance of type. An abstract class can share state and implementation, but you can extend only one class. Use interface for capability, abstract class for shared base behavior.
mediumhashmaplinkedhashmapcollections
Answer
HashMap doesn’t guarantee iteration order. LinkedHashMap maintains insertion order (or access order if configured), which is useful for predictable iteration and for building LRU-like caches.
mediumtry-with-resourcesautocloseableio
Answer
It automatically closes resources that implement `AutoCloseable` (files, streams, JDBC) even when exceptions happen. It prevents leaks and keeps cleanup logic reliable and simple.
try (var in = Files.newInputStream(path)) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}hardjmmhappens-beforeconcurrency+1
Answer
Happens-before is a rule that guarantees visibility and ordering between threads. If A happens-before B, then B must see the effects of A (e.g., via `synchronized`, `volatile`, or thread start/join).
hardweakreferenceweakhashmapgc+1
Answer
A weak reference doesn’t prevent GC: if an object is only weakly referenced, it can be collected. It’s useful for memory-sensitive caches (e.g., WeakHashMap) where you’d rather drop entries than leak memory.
easyjvmjrejdk+1
Answer
JVM runs Java bytecode. JRE is the runtime environment (JVM + standard libraries) needed to run apps. JDK is the development kit (JRE + compiler and tools) needed to build apps.
mediumrecordsdtoimmutability+1
Answer
A record is a concise syntax for an immutable data carrier. It generates final fields, a constructor, and `equals/hashCode/toString` automatically. Use it for DTOs, messages, and value-like objects—not for entities with complex mutable lifecycle.
mediumstreamscollectionsside-effects+1
Answer
A collection stores data; a stream describes a pipeline of operations (filter/map/reduce) to produce a result. Streams are typically single-use, and a common pitfall is side effects (mutating external state) inside `map/forEach`, which makes code harder to reason about.
List<String> activeNames = users.stream()
.filter(User::isActive)
.map(User::getName)
.toList();hardthreadlocalconcurrencythread-pool+1
Answer
`ThreadLocal` stores a separate value per thread (often used for request context). The common pitfall is thread pools: threads are reused, so values can “leak” between requests unless you clear them (`remove()` in a `finally`).
hardconcurrencylockssynchronized+1
Answer
`synchronized` is simpler and uses JVM monitors, giving mutual exclusion and a clear happens-before relationship. `ReentrantLock` is more flexible: `tryLock()`, timeouts, fairness options, and multiple `Condition`s—but you must always `unlock()` in `finally`.
easyclasspathjvmjar+1
Answer
The classpath is the list of places where the JVM looks for classes and resources (directories and JARs). If something is not on the classpath, you can get `ClassNotFoundException` / `NoClassDefFoundError`. You set it via build tools, IDE, or `-cp` when running Java.
mediumjavavartype-inference+1
Answer
`var` enables local variable type inference: the compiler infers the static type from the initializer. It does NOT make Java dynamically typed. You can use it only for local variables with an initializer (not for fields, method params, or without assignment).
mediumjavacollectionsimmutability+1
Answer
`List.of(...)` creates an unmodifiable (immutable) list. If you try to add/remove elements, you get `UnsupportedOperationException`. A common gotcha: it also does not allow null elements (it throws `NullPointerException` on creation).
List<String> xs = List.of("a", "b");
// xs.add("c"); // throws UnsupportedOperationExceptionhardjavastreamsparallel+2
Answer
Parallel streams can help for CPU-bound work on large collections when each element is independent and the work is heavy enough to amortize overhead. Pitfalls: they use `ForkJoinPool.commonPool` by default, they can be slower for small tasks, they are bad for blocking I/O, and side effects/shared mutable state can cause race conditions.
hardjavaclassloaderjvm+1
Answer
A ClassLoader loads classes/resources. In Java, a type is identified by (class name + defining ClassLoader). That means the “same” class name loaded by two different classloaders is treated as two different types, which can cause `ClassCastException` in plugin/app-server setups.
mediumjavagenericstype-erasure+1
Answer
Type erasure means generic type information is removed at runtime. As a result, you can’t do `new T()`, `T.class`, or `instanceof T`, and some generic checks are only compile‑time. The runtime sees raw types.
easyjavarecorddto+1
Answer
A `record` is a concise data carrier. It generates private final fields, a canonical constructor, accessors, `equals`, `hashCode`, and `toString`. It’s a good fit for DTOs/value objects where equality is based on data, but it doesn’t make contained objects immutable.
mediumjavasealedinheritance+1
Answer
Sealed classes restrict which classes can extend/implement them (`permits`). This makes class hierarchies explicit and enables exhaustive `switch` in newer Java versions. It’s useful for modeling closed sets of variants.
mediumjavaconcurrencylocks+1
Answer
`synchronized` uses intrinsic monitor locks with automatic release. `ReentrantLock` is an explicit lock with features like `tryLock`, fairness policies, and interruptible lock acquisition—but you must release it in `finally`. Both are reentrant.
easyjavaexceptionsresources+1
Answer
It requires resources that implement `AutoCloseable`. The resource is closed automatically (even on exceptions), which reduces boilerplate and prevents leaks. It’s safer than manual `finally` blocks.
try (var in = Files.newInputStream(path)) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}easyjavastringperformance+1
Answer
StringBuilder is not synchronized and is faster in single‑threaded code. StringBuffer is synchronized (thread‑safe), but usually slower. Both are mutable alternatives to `String`.
mediumjavacollectionsconcurrency+1
Answer
HashMap is not thread‑safe and is best for single‑threaded or externally synchronized use. ConcurrentHashMap supports safe concurrent reads/writes with better scalability; it disallows null keys/values. Use it when multiple threads access the map without external locking.
Answer
Most objects die young. The JVM exploits this by collecting the young generation frequently (fast minor GCs) and promoting long‑lived objects to the old generation, which is collected less often. This improves throughput and pause times.
mediumjavajitperformance+1
Answer
The JVM starts by interpreting bytecode, then JIT‑compiles “hot” methods to native code based on profiling. Early requests can be slower; after warm‑up, optimized machine code runs faster.
mediumjavanested-classinner-class+1
Answer
A static nested class does not hold an implicit reference to the outer instance; it can be created without an outer object. An inner class holds a reference to the outer instance, which can increase memory usage and lead to leaks if misused.