Skip to lesson

Mock Round: Java Backend Role

A Java backend round moves from your project into Spring, JPA, REST and SQL, then asks you to review code. The interviewer is checking whether you have really built and debugged something, not only read about it.

The 60-minute script and its rubric

A backend mock round is a timed rehearsal of a Java backend interview: a project walk-through, Spring, JPA, REST and SQL questions, a code review, one coding problem and sometimes a small design question.

Example 1 gives the minutes and weights of the 60-minute round. Use a friend as the interviewer, or record yourself answering from the script.

Example 1 · The 60-minute backend script

Text
00-10  PROJECT      "Walk me through your project." Architecture, one request                    end to end, your role, one challenge. Follow-ups on it.10-30  THEORY       Spring Boot and DI, JPA and transactions, REST and status                    codes, SQL and indexes, security and JWT. Each topic                    becomes a 2 to 3 question follow-up chain.30-40  CODE REVIEW  A short Spring controller or service: "What would you change?"40-55  CODING       One data-style problem with narration and complexity.55-60  DESIGN       Optional: "How would you design a URL shortener?"       + YOUR QUESTIONSWeights: project 20, theory 30, review 20, coding 20, design and questions 10
Timing
10 + 20 + 10 + 15 + 5 = 60 minutes, scored out of 100

What this code does

  • The project comes first because it decides where the theory questions go: everything you mention is fair game.
  • Theory carries the most weight, and most of it is in the follow-ups, not the first question.
  • If the design part is skipped, add its 10 points to theory when you score.

Score each part from 0 to 4 (4: correct and clear without help, 2: partly or with several hints, 0: wrong or missing) and weight it:

  • Project walk-through: 10 minutes, weight 20.
  • Spring, JPA, REST and SQL: 20 minutes, weight 30.
  • Code review 10 minutes, weight 20; coding problem 15 minutes, weight 20.
  • Optional design question and your questions: 5 minutes, weight 10.

Companies vary, and some split this across two rounds. Revise: Explaining your project's design choices (opens in a new tab).

Order of execution

Order the 60-minute backend round

Tap the parts in the order the round usually runs them.

Follow-up chains: how interviewers go deeper

A follow-up chain is a series of questions on one topic, each a level deeper than the last, until the interviewer reaches the edge of what you know. It shows your real depth quickly.

Example 2 lists five chains. Example 3 proves the last one: why string-built SQL is unsafe and a placeholder is safe.

Example 2 · Five follow-up chains

Text
DEPENDENCY INJECTION  What is DI? -> Constructor or field injection, and why? ->  Two beans implement the same interface: what happens, how do you fix it?TRANSACTIONS  What does @Transactional do? -> What is rolled back by default? ->  Why does calling a @Transactional method from the same class not start one?JPA  Lazy or eager loading? -> What is the N+1 problem? ->  How do you fix it, and what goes wrong with JOIN FETCH plus paging?REST  PUT or PATCH? -> Which status for "out of stock"? ->  How do you make POST /orders safe to retry?SQL AND SECURITY  How do you stop SQL injection? -> Why does PreparedStatement help? ->  Can you still be unsafe with JPA? (yes: string-built JPQL or native SQL)
Pattern
definition → how it works → what breaks, for each topic

What this code does

  • Each chain ends with a question about a failure, because that separates people who used a tool from people who only read about it.
  • Model answers for every step are in the Interview tab, in the same order.
  • Practise saying each chain aloud in under three minutes.

Example 3 · SQL injection chain: why placeholders help

InjectionChainDemo.javaJava
public class InjectionChainDemo {    static String concatenated(String email) {        return "SELECT * FROM customers WHERE email = '" + email + "'";    }
    public static void main(String[] args) {        String normal = "asha@example.com";        String attack = "x' OR '1'='1";        System.out.println("Built by +:  " + concatenated(normal));        System.out.println("Built by +:  " + concatenated(attack));        System.out.println("Prepared:    SELECT * FROM customers WHERE email = ?");        System.out.println("Bound value: " + attack + "  (sent as data, never as SQL)");    }}
Output
Built by +:  SELECT * FROM customers WHERE email = 'asha@example.com'
Built by +:  SELECT * FROM customers WHERE email = 'x' OR '1'='1'
Prepared:    SELECT * FROM customers WHERE email = ?
Bound value: x' OR '1'='1  (sent as data, never as SQL)

What this code does

  • With +, the attacker's quote ends the string and OR '1'='1' becomes part of the query, which is true for every row.
  • With a PreparedStatement, the SQL text is fixed and the value is sent separately, so quotes in it are just characters.
  • Spring Data JPA derived queries and :name parameters are bound the same way; building JPQL or native SQL with + brings the problem back.

Prepare each topic three levels down: level 1 what is it, level 2 how does it work, level 3 what breaks and how do you fix it.

  • Link answers to your project: "In ShopLite I used..."
  • If you do not know, say so, reason from what you know and name how you would check.

Revise: Spring Boot and DI questions (opens in a new tab) and JPA and Hibernate questions (opens in a new tab).

Predict the output

Predict the chain's proof

Work out what each snippet shows.

Round 1 of 2

A query is built with + from user input.

String email = "x' OR '1'='1";
String sql = "SELECT * FROM customers WHERE email = '" + email + "'";
System.out.println(sql);

Code-review snippet

A code-review question shows a short method or class and asks what you would change. List problems from most to least serious: correctness first, then safety, then design and style.

Read the snippet below once fully, then say the problems out loud. Examples 4 and 5 run a service with five problems and its reviewed version.

OrderController.javaJava
@RestControllerpublic class OrderController {    @Autowired    private OrderRepository orderRepository;
    @PostMapping("/orders")    public Order place(@RequestBody Order order) {        try {            order.setTotal(order.getPrice() * order.getQuantity());            return orderRepository.save(order);        } catch (Exception e) {            return null;        }    }}
  • Field injection → constructor injection with a final field.
  • Entity as request and response, no @Valid → request and response DTOs with validation.
  • double money and no stock check in the controller → BigDecimal and a @Transactional service.
  • catch (Exception e) { return null; } hides errors and returns 200 → let a @RestControllerAdvice map failures to 4xx or 5xx.

Example 4 · Review practice: a service with five problems

ReviewSnippetDemo.javaJava
import java.util.ArrayList;import java.util.List;
class Line {    final String sku;    final double price;    final int qty;
    Line(String sku, double price, int qty) {        this.sku = sku;        this.price = price;        this.qty = qty;    }}
class OrderDraft {    private final List<Line> lines = new ArrayList<>();    private String status = new String("PLACED");
    void add(Line line) {        lines.add(line);    }
    double total() {        double t = 0;        for (Line l : lines) {            t += l.price * l.qty;        }        return t;    }
    boolean canCancel() {        return status == "PLACED";    }
    List<Line> getLines() {        return lines;    }
    static int parseQty(String text) {        try {            return Integer.parseInt(text);        } catch (Exception e) {            return 0;        }    }}
public class ReviewSnippetDemo {    public static void main(String[] args) {        OrderDraft order = new OrderDraft();        order.add(new Line("PEN-01", 0.1, 1));        order.add(new Line("NB-02", 0.2, 1));        System.out.println("Total: " + order.total());        System.out.println("Can cancel a PLACED order: " + order.canCancel());        System.out.println("Quantity from \"two\": " + OrderDraft.parseQty("two"));        order.getLines().clear();        System.out.println("Lines after a caller clears the list: " + order.getLines().size());    }}
Output
Total: 0.30000000000000004
Can cancel a PLACED order: false
Quantity from "two": 0
Lines after a caller clears the list: 0

What this code does

  • Four visible bugs: double money gives 0.30000000000000004, == on Strings says a PLACED order cannot be cancelled, bad input silently becomes 0, and any caller can wipe the order's lines.
  • The fifth problem is design: status is a free-text String, so a typo such as "PLACD" compiles; an enum makes wrong values impossible.
  • In a review, say the problem, its effect and the fix in one breath: "== compares references, so cancel fails for statuses read from the database; use an enum or equals."

Example 5 · The reviewed version

ReviewedSnippetDemo.javaJava
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;
enum Status { PLACED, SHIPPED, DELIVERED, CANCELLED }
record Line(String sku, BigDecimal price, int qty) {}
class OrderDraft {    private final List<Line> lines = new ArrayList<>();    private Status status = Status.PLACED;
    void add(Line line) {        lines.add(line);    }
    BigDecimal total() {        BigDecimal t = BigDecimal.ZERO;        for (Line l : lines) {            t = t.add(l.price().multiply(BigDecimal.valueOf(l.qty())));        }        return t;    }
    boolean canCancel() {        return status == Status.PLACED;    }
    List<Line> getLines() {        return List.copyOf(lines);    }
    static int parseQty(String text) {        try {            return Integer.parseInt(text);        } catch (NumberFormatException e) {            throw new IllegalArgumentException("Quantity must be a number: " + text);        }    }}
public class ReviewedSnippetDemo {    public static void main(String[] args) {        OrderDraft order = new OrderDraft();        order.add(new Line("PEN-01", new BigDecimal("0.10"), 1));        order.add(new Line("NB-02", new BigDecimal("0.20"), 1));        System.out.println("Total: " + order.total());        System.out.println("Can cancel a PLACED order: " + order.canCancel());        try {            OrderDraft.parseQty("two");        } catch (IllegalArgumentException e) {            System.out.println("Rejected: " + e.getMessage());        }        try {            order.getLines().clear();        } catch (UnsupportedOperationException e) {            System.out.println("Callers cannot change the lines");        }    }}
Output
Total: 0.30
Can cancel a PLACED order: true
Rejected: Quantity must be a number: two
Callers cannot change the lines

What this code does

  • BigDecimal from strings gives an exact 0.30; comparing enums with == is correct, because each enum value exists exactly once.
  • Catching only NumberFormatException and throwing a clear IllegalArgumentException lets the API turn it into a 400 instead of silently ordering 0 items.
  • List.copyOf returns an unmodifiable copy, so the order's own list cannot be changed from outside.

Say each problem, its effect and the fix in one breath, for example: "The catch hides errors and returns 200 with no body; a @RestControllerAdvice should map failures to 4xx or 5xx." Revise: REST and HTTP questions (opens in a new tab).

Find the bug

Spot the review problem

Tap the line a reviewer should flag first.

A controller method saves an order.

Round 1 of 3

The coding problem: top products by revenue

The problem is Top Products by Revenue: given order lines (product, unit price, quantity), return the three products with the highest total revenue, highest first, ties by name. Example 6 is the full solution.

Example 6 · Coding problem: Top Products by Revenue

TopProductsDemo.javaJava
import java.math.BigDecimal;import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.Map;
record OrderLine(String product, BigDecimal price, int qty) {}
public class TopProductsDemo {    static List<Map.Entry<String, BigDecimal>> topByRevenue(List<OrderLine> lines, int k) {        Map<String, BigDecimal> revenue = new HashMap<>();        for (OrderLine l : lines) {            BigDecimal amount = l.price().multiply(BigDecimal.valueOf(l.qty()));            revenue.merge(l.product(), amount, BigDecimal::add);        }        return revenue.entrySet().stream()                .sorted(Map.Entry.<String, BigDecimal>comparingByValue(Comparator.reverseOrder())                        .thenComparing(Map.Entry.comparingByKey()))                .limit(k)                .toList();    }
    public static void main(String[] args) {        List<OrderLine> lines = List.of(                new OrderLine("Notebook", new BigDecimal("45.00"), 10),                new OrderLine("Pen", new BigDecimal("10.50"), 30),                new OrderLine("Bag", new BigDecimal("899.00"), 1),                new OrderLine("Notebook", new BigDecimal("45.00"), 4),                new OrderLine("Pen", new BigDecimal("10.50"), 10),                new OrderLine("Bottle", new BigDecimal("250.00"), 2));        int rank = 1;        for (Map.Entry<String, BigDecimal> e : topByRevenue(lines, 3)) {            System.out.println(rank++ + ". " + e.getKey() + " " + e.getValue());        }    }}
Output
1. Bag 899.00
2. Notebook 630.00
3. Bottle 500.00

What this code does

  • merge adds each line's amount to the product's running total: Notebook is 450.00 + 180.00 = 630.00, Pen is 315.00 + 105.00 = 420.00 and misses the top three.
  • The comparator sorts by revenue, highest first, then by name, so equal revenues always come out in the same order.
  • Cost: O(n) to build the map and O(k log k) to sort k distinct products; for a top three of many products, a size-3 heap would avoid the full sort.

Narrate the usual way: clarify (ties? money type? fewer than three products?), plan (sum per product in a map, sort the entries, take three), code, dry run, then cost: O(n) to sum plus O(k log k) to sort k products.

  • Money is BigDecimal, summed with merge(..., BigDecimal::add).
  • Sort by revenue descending, then by name, so ties have one fixed order.
  • Edge cases: no lines, fewer than three products, the same product on many lines.
  • Follow-up: "How would you do this in SQL?" GROUP BY product, SUM(price * quantity), ORDER BY, LIMIT 3.

Revise: Backend interview drill (opens in a new tab).

Fix the error

Fix the revenue code

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

The map holds BigDecimal revenue per product and starts a product at zero.

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
class Rev {
static void start(String product) {
Map<String, BigDecimal> revenue = new HashMap<>();
revenue.put(product, 0);
}
}

Error

Rev.java:8: error: incompatible types: int cannot be converted to BigDecimal
        revenue.put(product, 0);
                             ^

Optional design question: a URL shortener in five minutes

A basic design question asks you to sketch a small system aloud in a few minutes, such as a URL shortener. For a fresher the bar is a sensible structure, not a full system design.

Keep to the five-line outline below and stop when time is up: requirements, API, data, main flow and one scaling idea.

Text
Requirements  shorten a long URL; redirect a short code; count clicksAPI           POST /api/v1/links {url} -> 201 {code}              GET /{code} -> 302 Location: long URL (404 if unknown)Data          links(id, code UNIQUE, long_url, clicks, created_at)Flow          random base62 code (7 chars), retry if it already existsScale         reads >> writes: cache hot codes; index on code

Section 21, Backend Architecture & System Design Fundamentals, works through this exact question, and the Section 22 LinkLite project builds it. Practise under time: Mock Interview Mode (opens in a new tab) draws questions from all the interview banks, you answer aloud and rate yourself.

Order of execution

Order a five-minute design answer

Tap the parts in the order you would say them.

Next step

Check your understanding

12 quick questions