Interview question01 / 100
Practice session
Core Java
One hundred in-depth interview questions from JVM fundamentals through collections, concurrency, NIO, the memory model, and modern Java — beginner to expert.
100 curated questions10 coding exercisesQuestions tab: swipe cards or keyboard
Practice for Core Java
Progress
1 / 100
Arrow keys to move · Space or Enter to revealOn touch: swipe the card right or left
Hands-on
Coding exercises
Read the scenario, sketch your solution in the editor, reveal hints only when you need them, then compare against our reference implementation. Exercises run from beginner through mid-level.
In this track
10
scenarios
Line items with an ArrayList
Scenario
Model a shopping cart as a list of line items. Each `LineItem` has a non-null `String id`, `String name`, `BigDecimal unitPrice`, and `int quantity` (must be positive when added).
Implement a `CartService` (or static helpers) with:
• `addLine(List<LineItem> cart, LineItem newLine)` — return a **new** `ArrayList` copy: if an item with the same `id` exists, increase its quantity by `newLine.getQuantity()`; otherwise append a new line (copy fields as needed). Do not mutate the input list.
• `removeLine(List<LineItem> cart, String id)` — return a new list without that id.
• `total(List<LineItem> cart)` — return `BigDecimal` sum of `unitPrice.multiply(BigDecimal.valueOf(qty))` for each line.
Use `BigDecimal` for money, never `double`, for the total.
- Java 17+; you may use records for LineItem.
- Treat input lists as immutable from the caller’s perspective.
Simple bank account
Scenario
Implement a class `BankAccount` with:
• A constructor `BankAccount(String accountId, BigDecimal openingBalance)` — reject null id or negative opening balance by throwing `IllegalArgumentException`.
• `void deposit(BigDecimal amount)` — add to balance; reject null or non-positive amounts.
• `boolean withdraw(BigDecimal amount)` — subtract if balance is sufficient; return `true` on success, `false` if insufficient funds (do not change balance). Reject null or non-positive amounts.
• `BigDecimal getBalance()` — return current balance.
Keep balance non-negative at all times.
- Use BigDecimal for all monetary values.
- Use compareTo for comparisons, not ==.
Letter frequency map
Scenario
Write `Map<Character, Integer> letterFrequency(String text)` that counts how often each **letter** appears. Treat input case-insensitively and count only Unicode letters (`Character.isLetter`); ignore spaces, digits, and punctuation.
If `text` is null, return an empty `HashMap`. For an empty string, return an empty map as well.
- Use java.util.HashMap or LinkedHashMap.
- Normalize each letter to lowercase (or uppercase) before using it as the map key.
Score to letter grade
Scenario
Implement `String toLetterGrade(int scorePercent)` where `scorePercent` is 0–100 inclusive. Use this scale:
• 90–100 → `"A"`
• 80–89 → `"B"`
• 70–79 → `"C"`
• 60–69 → `"D"`
• below 60 → `"F"`
If `scorePercent` is outside 0–100, throw `IllegalArgumentException`.
- Use only one public method for the conversion.
- Bounds checks should be explicit (no silent clamping).
Sum a rectangular matrix
Scenario
Implement `long sumMatrix(int[][] matrix)` that returns the sum of all elements.
• If `matrix` is `null` or has zero rows, return `0`.
• Rows may be `null` or ragged (different lengths); skip `null` rows and treat missing rows as empty.
Do not assume the matrix is non-empty or rectangular beyond what is described.
- Use nested loops or streams; avoid third-party libraries.
- Watch for overflow: use `long` accumulator.
Sort students by GPA then name
Scenario
You have `record Student(String name, double gpa)`. Sort a `List<Student>` **in place** so that:
• Higher GPA comes first (descending).
• If two students have the same GPA, order by `name` ascending (lexicographic `String` order).
Implement `void sortStudents(List<Student> students)` using `Comparator` and `List.sort` (or `Collections.sort`). Do not assume the list is mutable beyond standard `List` contract—use `sort` on the list reference passed in.
- Do not create a new list; reorder the given list.
- Use Comparator.comparing(...) and .thenComparing(...) or equivalent.
Streams: filter and average salary
Scenario
Given `record Employee(String name, String department, long salaryAnnual)` and a `List<Employee>`, implement:
`double averageSalaryInDepartment(List<Employee> employees, String department)`
Return the **average** of `salaryAnnual` for employees whose `department` equals the argument (use `Objects.equals`). If there are no employees in that department, return `0.0`.
Use the Stream API (`stream()`, `filter`, `mapToLong`, `average`, `OptionalDouble`).
- Handle empty result without dividing by zero.
- Use primitive streams for salaries to avoid boxing in the average step.
Optional chaining for nested email
Scenario
Model:
`record Address(String email)`
`record User(String name, Address address)`
Implement `Optional<String> findEmail(Optional<User> userOpt)` that:
• Returns `Optional.empty()` if `userOpt` is empty or null **or** if the user’s address is `null` **or** the address email is `null` or blank (after `String.trim()`).
Use `Optional`’s `flatMap` / `map` / `filter` style—avoid `if` ladders if you can.
- Method signature must use Optional as given.
- Blank means string is empty or only whitespace.
Generic maximum in a list
Scenario
Implement a generic method:
`public static <T extends Comparable<T>> T max(List<T> values)`
Return the **largest** element according to natural ordering (`Comparable`). If the list is `null` or empty, throw `IllegalArgumentException`. If any element is `null`, throw `NullPointerException` (or use `Objects.requireNonNull` per element).
Assume the list has at least one non-null element when non-empty.
- Single pass O(n); do not sort the whole list.
- Use compareTo for ordering.
Custom exception for invalid product code
Scenario
Define a **checked** exception `InvalidProductCodeException extends Exception` with a constructor taking `String message` and `String code`, plus getters. You may implement it as a `public static` nested class inside your validator type so a single `.java` file stays valid.
Implement `void validateProductCode(String code)` that throws `InvalidProductCodeException` when:
• `code` is `null` or blank after trim, or
• `code` does not match the pattern: exactly three uppercase letters followed by four digits (e.g. `ABC1234`).
Use `String.matches` with a regex, or `Pattern` if you prefer.
Implement `public static void main` only if you want a demo—it is optional for the answer file.
- Use a checked exception (not RuntimeException).
- Message should explain why validation failed.