Backend practice series: 1. Requirements and data design · 2. APIs and overbooking · 3. Interview review · 4. Recursion and sorting · 5. SQL exercises · 6. SQL on the E-Learning database
After the pet project in part 1 and part 2, this post reviews the fundamentals as interview questions: Java Core, Spring Boot and the web, plus the places where the original answers are wrong. Afterwards you can answer each question briefly and pitch your project with a six-point template. The algorithms review is in part 4, the database review in part 5.
1. Java Core review
Key idea: most Java Core questions can be answered in one sentence. The bonus points come from knowing where the popular answers go wrong: equals, return types when overriding, pass-by-value.
More detail in Java basics, Object-oriented programming and Data structures.
JDK vs JRE vs JVM
They nest like boxes inside boxes.
flowchart LR
subgraph JDK[JDK]
direction LR
T[javac, jar, jshell,<br/>jdb, jcmd, jlink...]
subgraph JRE[JRE]
L[Standard library<br/>java.base, java.sql...]
subgraph JVM[JVM]
C[Class loader → bytecode verifier →<br/>interpreter + JIT → GC]
end
end
end
- JVM (Java Virtual Machine): runs bytecode (the intermediate code in
.classfiles). It loads classes, verifies bytecode, interprets it, JIT-compiles it (turns hot code into machine code at runtime), and manages memory and GC (cleaning up unused objects). - Each OS has its own JVM, but the bytecode is the same: “write once, run anywhere”.
- JRE (Java Runtime Environment): the JVM plus the standard library, enough to run programs.
- JDK (Java Development Kit): the JRE plus development tools (
javac,jar,jshell,jcmd…), enough to write and build them.
What is OOP? The four pillars
OOP organises a program into objects. Each object bundles data (state) with the behaviour (methods) that operates on it; objects interact through methods.
| Pillar | Core idea | In Java |
|---|---|---|
| Encapsulation | Hide internal state; only allow changes through controlled behaviour | private fields, public methods that preserve invariants (conditions that must always hold) |
| Inheritance | A subclass reuses and extends its superclass | extends; exactly one superclass |
| Abstraction | Use something through “what it can do”, not “how it does it” | interface, abstract class |
| Polymorphism | The same call behaves differently depending on the actual object | Overriding (dynamic dispatch: the method is picked at runtime); overloading is compile-time polymorphism |
Two points that score: a getter and setter for every field is not encapsulation, and “favour composition over inheritance”.
A senior’s take: real encapsulation (the Wallet example) and composition over inheritance
A getter and setter for every field is just a public field with extra steps. Real encapsulation means the object protects its own invariants:
public class Wallet {
private BigDecimal balance = BigDecimal.ZERO;
public void withdraw(BigDecimal amount) {
if (amount.signum() <= 0) throw new IllegalArgumentException("amount must be positive");
if (balance.compareTo(amount) < 0) throw new InsufficientFundsException(balance, amount);
balance = balance.subtract(amount);
}
public BigDecimal balance() { return balance; } // no setBalance()
}
On inheritance: it couples a subclass tightly to its parent’s implementation details (the fragile base class problem: changing the parent breaks the child). Use it only for genuine “is-a” relationships and parents designed to be extended. Otherwise, let one object hold another and call it (composition).
== vs equals()
==compares values for primitives; for references it asks whether both variables point to the same object.equals()is a method onObject. By default it is exactly==. It only compares content when a class overrides it.
String a = new String("hi"), b = new String("hi");
System.out.println(a == b); // false: two different objects
System.out.println(a.equals(b)); // true: String overrides equals
Integer x = 127, y = 127, p = 128, q = 128;
System.out.println(x == y); // true: Integer caches -128..127
System.out.println(p == q); // false: outside the cache, two objects. Always use equals with wrappers!
record Point(int x, int y) {} // records generate equals/hashCode from their components
System.out.println(new Point(1, 2).equals(new Point(1, 2))); // true
Access modifiers
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
private |
✓ | |||
| (default / package-private) | ✓ | ✓ | ||
protected |
✓ | ✓ | ✓ (through inheritance) | |
public |
✓ | ✓ | ✓ | ✓ |
Since Java 9 there’s one more layer: modules (module-info.java). A public class in a package that isn’t exports-ed is still invisible to other modules.
final
finalvariable: assigned exactly once. For references, the reference can’t change but the object can (final List<String> lstill allowsl.add(...)).finalmethod: subclasses can’t override it.finalclass: can’t be extended (String, the wrappers; records are implicitly final).- Java 17 added
sealed, which restricts which classes may extend a type: more flexible thanfinal.
final and threads: the Java Memory Model guarantee
Static vs instance methods
| Static | Instance | |
|---|---|---|
| Belongs to | The class | Each object |
| Called as | Math.max(a, b) |
order.total() |
Can use this and instance fields |
No | Yes |
| Overriding | No (only method hiding) | Yes, dispatched on the runtime type |
| Use for | Pure utility functions, factory methods (List.of) |
Behaviour that depends on object state |
Overusing static (mutable static state, static calls everywhere) makes code hard to test because you can’t mock it. That’s one reason Spring uses beans and DI.
Overloading vs overriding
- Overloading: several methods with the same name but different parameter lists (count, types, order). A different return type alone is not enough. The compiler picks the method at compile time, from the declared types of the arguments.
- Overriding: a subclass redefines a superclass method with the same name and parameter list. The JVM picks the method at runtime, from the object’s actual type.
class Shape { Shape copy() { return new Shape(); } }
class Circle extends Shape {
@Override Circle copy() { return new Circle(); } // valid: covariant return type
}
static void print(Object o) { System.out.println("Object"); }
static void print(String s) { System.out.println("String"); }
Object o = "hello";
print(o); // prints "Object": overloads are chosen by the DECLARED type at compile time
Why doesn’t Java allow multiple class inheritance?
To avoid the diamond problem: if C extends A, B and both A and B define hello() (or the same field), which one does C get? Inheriting state from several parents also complicates initialisation and memory layout. Java’s choice: one superclass, many interfaces.
The diamond of behaviour still exists: interface default methods
Since Java 8, interfaces can have default methods, so a diamond of behaviour can still happen. Java makes you resolve it explicitly:
interface Flyer { default String move() { return "fly"; } }
interface Swimmer { default String move() { return "swim"; } }
class Duck implements Flyer, Swimmer {
@Override public String move() { // mandatory, otherwise it won't compile
return Flyer.super.move() + " & " + Swimmer.super.move();
}
}
Abstract class or interface?
| Abstract class | Interface | |
|---|---|---|
| State (instance fields) | Yes | No (only static final constants) |
| Constructors | Yes | No |
| Methods with bodies | Yes | default, static, private (Java 8/9+) |
| How many per class | One | Many |
| Meaning | “is a”: a shared skeleton for a family of closely related classes | “can do”: a capability or contract |
Is Java pass-by-value or pass-by-reference?
Always pass-by-value. For reference types, what gets copied is the value of the reference (the object’s address). A method can modify the object through that copy, but it can’t make the caller’s variable point to a different object.
It’s like handing someone a photocopy of your home address: they can go and repaint the house, but writing a new address on the copy doesn’t change your original.
static void rename(Person p) { p.setName("B"); } // mutates the shared object -> caller sees it
static void replace(Person p) { p = new Person("C"); } // only changes the local copy of the reference -> caller doesn't
Person me = new Person("A");
rename(me); System.out.println(me.getName()); // B
replace(me); System.out.println(me.getName()); // still B
The reason given in the slides (“Java has no pointers”) isn’t accurate. Java references essentially are pointers (hence NullPointerException); there’s just no pointer arithmetic. The real reason is the method-call semantics: parameters always receive a copy.
Common data structures; arrays vs linked lists; stacks vs queues
- Array /
ArrayList: O(1) access by index, contiguous memory; adding/removing at the front or middle is O(n) because elements shift. - Linked list /
LinkedList: O(n) access by index; adding/removing is O(1) if you already hold the node, but finding it is still O(n). - A stack is LIFO (last in, first out): call stacks, undo, DFS, bracket matching.
- A queue is FIFO (first in, first out): task queues, BFS, buffers between producers and consumers.
Full tables: common collections, and array vs linked list complexity
| Interface | Common implementations | Notes |
|---|---|---|
List |
ArrayList, LinkedList |
Ordered, duplicates allowed |
Set |
HashSet, LinkedHashSet, TreeSet |
No duplicates; Tree keeps order |
Map |
HashMap, LinkedHashMap, TreeMap, ConcurrentHashMap |
Key → value |
Queue / Deque |
ArrayDeque, PriorityQueue, LinkedList |
FIFO, double-ended, priority |
| Stack | ArrayDeque (push/pop) |
Avoid the legacy Stack class (synchronised, extends Vector) |
| Operation | Array / ArrayList |
Linked list / LinkedList |
|---|---|---|
| Access by index | O(1) | O(n) |
| Add/remove at the end | O(1) amortised (averaged over many appends) | O(1) |
| Add/remove at the front or middle | O(n) (shift elements) | O(1) if you already hold the node; finding it is still O(n) |
| Memory | Contiguous, CPU-cache friendly | Two pointers + an object header per node, scattered |
2. Spring Boot review
Key idea: Spring creates and wires objects for you (IoC); dependencies are supplied from outside (DI), preferably through the constructor. Path variables identify a resource, query params filter.
More in IoC and Dependency Injection.
Inversion of Control (IoC): your code doesn’t create and wire objects itself (new OrderService(new OrderRepository(...))); it hands that job to the framework. The Spring container reads the configuration (annotations), creates beans (objects managed by Spring), manages their lifecycle and wires them together.
Dependency Injection (DI) is how IoC is implemented: dependencies are “injected” from outside, in three ways:
@Service
class OrderService {
private final OrderRepository repo; // 1. Constructor injection: preferred
OrderService(OrderRepository repo) { this.repo = repo; }
}
@Service
class ReportService {
private Mailer mailer;
@Autowired void setMailer(Mailer mailer) { this.mailer = mailer; } // 2. Setter: for optional dependencies
}
@Service
class LegacyService {
@Autowired private AuditLog auditLog; // 3. Field injection: discouraged
}
Why constructor injection:
- Fields can be
final(immutable), and the object is always in a valid state. - Required dependencies are explicit; you can test with a plain
new, without Spring. - Too many constructor parameters is a signal the class does too much.
- With a single constructor you don’t even need
@Autowired.
Layers (covered in depth in part 2): Controller (HTTP) → Service (business logic, transactions) → Repository (data). Supporting pieces: DTOs (objects that carry data across the API), entities, mappers, exception handlers, config.
Reading parameters from the URL:
// GET /users?page=1&size=20
@GetMapping("/users")
List<UserDto> list(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) { ... }
// GET /users/1
@GetMapping("/users/{id}")
UserDto get(@PathVariable long id) { ... }
// Many query params -> bind them into one object (a record) via data binding
record UserFilter(String city, Integer minAge) {}
@GetMapping("/users/search")
List<UserDto> search(UserFilter filter) { ... }
The convention: path variables identify a resource (/users/1), query params filter, sort and paginate (?city=hanoi&page=2). There’s also @RequestBody (the JSON body), @RequestHeader and @CookieValue. REST details are in Web and REST APIs.
3. Web review
Key idea: remember which HTTP methods are safe (don’t change data) and idempotent (calling them many times gives the same result). HTTPS is HTTP over TLS: confidentiality, integrity, server authentication.
Common HTTP methods:
- Safe and idempotent: GET, HEAD, OPTIONS.
- Idempotent but not safe: PUT (replace the whole resource), DELETE.
- Not idempotent: POST (create, perform an action). PATCH (partial update) is not guaranteed to be.
HTTP vs HTTPS: HTTPS is HTTP over TLS, like a sealed, tamper-evident envelope delivered to a verified recipient.
- Confidentiality: a man in the middle can’t read the traffic.
- Integrity: packets can’t be altered undetected.
- Server authentication: a certificate signed by a CA (certificate authority) proves you’re really talking to
example.com.
Default ports are 80 and 443. Today HTTPS is mandatory.
Full HTTP method table and how the TLS handshake works (TLS 1.3, HSTS)
| Method | Used for | Safe | Idempotent |
|---|---|---|---|
| GET | Read a resource | ✓ | ✓ |
| POST | Create / perform an action | ||
| PUT | Replace a whole resource | ✓ | |
| PATCH | Partial update | Not guaranteed | |
| DELETE | Delete | ✓ | |
| HEAD / OPTIONS | Fetch headers / ask about capabilities (CORS preflight) | ✓ | ✓ |
- During the handshake, both sides use asymmetric cryptography (ECDHE key exchange plus a certificate signature) to agree on a session key.
- Then the data is encrypted symmetrically (AES-GCM, ChaCha20) because it’s much faster.
- TLS 1.3 cuts the handshake to one round trip.
- Browsers only speak HTTP/2 over TLS. The HSTS header tells browsers to always use HTTPS for that domain.
Remember
- Explain why
equalsdefaults to==, and why it goes together withhashCode. - Predict what
print(o)prints whenObject o = "hello", and explain it with “compile time vs runtime”. - Prove Java is pass-by-value with the
renameandreplaceexample. - Know when to pick an abstract class over an interface, and
ArrayDequeoverArrayList. - Pitch your project in 60 seconds with the six-point template, and explain how every number on your CV was measured.
Interview questions
Junior
When you override equals(), what else must you do, and why?
Override hashCode() so that objects that are equals have the same hash code.
HashMap/HashSet find the bucket by hashCode first and only then compare with equals. If two equal objects have different hashes, the map treats them as different keys. Records and Lombok’s @EqualsAndHashCode generate both for you.
When do you use @PathVariable vs @RequestParam?
PathVariable for the part of the path that identifies a resource (/users/1); RequestParam for the query string.
The query string is usually for filtering, sorting and pagination, optionally with defaults (?page=2&size=20).
Is Java pass-by-value or pass-by-reference?
Always pass-by-value. For objects, the value being copied is the reference.
So a method can modify the object’s contents, but reassigning the parameter to a new object isn’t visible to the caller.
Mid
Why prefer constructor injection?
Because dependencies can be final and the object is never missing a dependency.
Required dependencies are visible in the signature, you can test with new without a container, and dependency cycles are detected at startup. A very long constructor is a sign the class breaks single responsibility.
Abstract class or interface after Java 8: how do you choose?
Default to an interface; pick an abstract class when you need shared state, constructors or a common algorithm skeleton.
Interfaces are contracts and capabilities: a class can implement many, and default methods let an API evolve without breaking existing implementations. Abstract classes suit a family of closely related classes sharing a template method. Java 17 adds sealed interfaces to restrict the set of implementations.
ArrayList or LinkedList?
Almost always ArrayList.
ArrayList has O(1) access, contiguous memory that’s friendly to the CPU cache, and amortised O(1) appends. LinkedList only has a theoretical edge when inserting or removing in the middle while already holding an iterator at that spot, but it uses much more memory and iterates slowly. For a double-ended queue, use ArrayDeque.
What does HTTPS protect, and what doesn’t it protect?
It protects data in transit (confidentiality, integrity) and authenticates the server through its certificate; it protects nothing outside the wire.
It doesn’t protect data once it reaches the server (storage, logs), bugs in the application itself (SQL injection, broken authorisation), or metadata such as IP addresses and the domain name (SNI is still visible unless ECH is used).
Useful phrases for interviews
- “Java is strictly pass-by-value; for objects, what gets copied is the reference.”
- “By default, equals is just reference equality, unless the class overrides it.”
- “I go with constructor injection so dependencies are explicit and can be final.”
- “Encapsulation isn’t about getters and setters; it’s about the object protecting its own invariants.”
- “Overloading is resolved at compile time from the declared types; overriding is resolved at runtime from the actual object.”
- “I default to an interface for the contract and reach for an abstract class only when subclasses genuinely share state.”
- “ArrayList beats LinkedList almost every time because of cache locality; for a double-ended queue I use ArrayDeque.”
- “HTTPS protects data in transit and authenticates the server, but it does nothing for SQL injection or broken authorization.”
Appendix: describing a project on your CV and in interviews
Key idea: tell the project in six points and put your effort into point 5 (the problem and the fix) and point 6 (a measured result). Only list numbers you measured yourself and can explain.
“Tell me about a project you worked on” comes up in almost every interview, and for a junior the pet project is that project. The examples use this series’ own hotel booking pet project.
The six-point template
- Project name.
- Role: which part you owned.
- Team size: solo or coordinating with others.
- Main function and users: the business problem, not just the tech.
- Problem you hit and how you solved it: where real skill shows.
- Result, as a measurable number: turns “done” into “done well”.
A CV version of 3–4 lines is enough. The spoken version takes about 60 seconds, follows the six points in order, one or two sentences each, and pauses after points 5 and 6 so the interviewer can choose where to dig.
The numbers in this appendix’s examples are illustrative, not real measurements.
The six points filled in with the hotel pet project, a sample CV entry and where the tech stack fits
| # | Point | Example (hotel pet project) | Why the interviewer needs it |
|---|---|---|---|
| 1 | Project name | Hotel Booking System | Easy to refer back to and dig into |
| 2 | Role | Backend Developer | Shows what you owned; follow-ups will target it |
| 3 | Team size | 4 people (2 backend, 1 frontend, 1 tester), or “solo” | Shows scope: did you do everything, or coordinate, review and split work |
| 4 | Main function and users | Hotel staff manage rooms; travellers search and book rooms | Shows the business problem, not just the tech stack |
| 5 | Problem you hit and how you solved it | Two guests booking the same room at once caused overbooking; solved with a MySQL transaction plus a conditional update, see preventing overbooking | This is where real skill shows; the interviewer will dig here |
| 6 | Result, as a measurable number | Booking API p95 < 200 ms at 100 concurrent users (measured with k6), zero double bookings in a 1,000-parallel-request test | A number turns “done” into “done well”, and gives the interviewer something to probe |
The CV version:
Hotel Booking System · Backend Developer · team of 4 · Java 21, Spring Boot, MySQL A system for hotel staff to manage rooms and for guests to search and book them. Prevented double booking under concurrent requests with a transaction and a conditional update; wrote integration tests with Testcontainers. Booking API p95 < 200 ms at 100 concurrent users; zero overbookings in a 1,000-parallel-request load test.
Prepare for the follow-up questions
Every number and every keyword on your CV is an invitation to ask more. Have answers ready for at least these:
- “Which isolation level did you use, and why? What happens if you leave the default?” (review transactions, isolation levels and locking).
- “How did you measure 200 ms: average or p95/p99? How many users, how much data, which tool, what hardware?” (p95: 95% of requests are faster than this).
- “If traffic grew 10x, what would break first?” (the connection pool, row locks on the room, a search query missing an index).
- “Which parts did you build yourself, and which were someone else’s?” and “What would you do differently?”
Tell me about a project you worked on.
Follow the six-point template in about a minute, then let the interviewer pick where to dig.
The six points: project name; role (Backend Developer); team size and which part you owned; what the system does and for whom; the hardest problem and how you solved it; the result with a number.
For example: “Hotel Booking System. I was the backend developer in a team of four. Guests book rooms and staff manage them. The hardest part was two people booking the same room at the same moment; I used a transaction with a conditional update so only one booking succeeds. The booking API’s p95 is under 200 ms at 100 concurrent users.”
Your CV says “API p95 < 200 ms”. How did you measure that?
Give the full measurement setup: tool, scenario, data, environment, and make clear the metric is a percentile, not an average.
- Tool: k6, JMeter, Gatling.
- Scenario: how many concurrent users, for how long, read/write mix.
- Data: how many rows in the tables. Environment: local machine or staging, and its specs.
- Metric: p95/p99, because averages hide slow requests.
Add the bottleneck you found and what you changed (say, an index or a bigger connection pool). If you only measured on your laptop, say so; being honest about the limits of a measurement earns more credit than a pretty number.
Notes based on the Fundamentals of Backend course (Ronin Engineer), rewritten in my own words.