Explain it simply
Explain it simply
Practice Set 1 was like learning to drive in an empty car park; Practice Set 2 is the first drive on a real road. You know collections, inheritance and exceptions one at a time, but only using them together shows whether you really understand them.
The four tasks are a shopping list, a shop's stock list, the areas of different shapes, and handling a division by zero. Before each task, skim the matching lesson again, write your own version first, and look at the reference answer last.
Problem → Why → Solution
The problem: collections that do not behave as you assumed
In the attempt below, the learner wants to remove the value 10 from an Integer list and writes quantities.remove(10). Java reads that as "remove the element at index 10" and throws an IndexOutOfBoundsException. The second loop calls cart.remove() while a for-each is walking the same list, which throws a ConcurrentModificationException.
In Task 2, inventory.get("grapes") returns null because the key does not exist, and storing that in an int and adding to it would throw a NullPointerException. All three bugs come from guessing what a collection method does from its name.
List<Integer> quantities = new ArrayList<>(List.of(10, 20, 30));
quantities.remove(10); // index 10! IndexOutOfBoundsException
List<String> cart = new ArrayList<>(List.of("rice", "eggs", "milk", "tea"));
for (String item : cart) {
if (item.startsWith("e")) {
cart.remove(item); // ConcurrentModificationException
}
}
int grapes = inventory.get("grapes"); // null -> NullPointerExceptionWhy does this happen?
List has two overloads, remove(int index) and remove(Object o), and the int literal 10 matches remove(int) exactly, so the compiler picks that one. The iterator behind a for-each loop throws when it detects that the list was modified by something other than itself. A map returns null for a missing key instead of throwing, so checking is your job.
Core concept: the contract behind each task
Every collection and exception method has a contract: call it like this and that is what happens. Knowing the contract behind each task before you start prevents most of the bugs.
Task 1: the two removes on a list
shoppingList.remove("eggs") searches by value, removes the first match and returns a boolean. shoppingList.remove(0) removes whatever sits at index 0 and returns that element. With Strings the two are hard to confuse, but to remove a value from an Integer list you must write remove(Integer.valueOf(10)).
Task 2: five map methods
put() adds a new key or replaces the old value. get() returns null for a missing key, and containsKey() tells you whether it exists. remove() deletes an entry and entrySet() lets you loop over key-value pairs. A HashMap promises no iteration order, so the reference answer uses a LinkedHashMap: the same methods, but entries come back in insertion order.
Task 3: abstract methods and dynamic dispatch
An abstract class Shape cannot be created with new Shape(); only subclasses that fill in area() can. When the loop calls s.area() on each element of the Shape[] array, Java ignores the variable's type (Shape) and runs the version belonging to the real object, Circle or Rectangle, at runtime. This is called dynamic dispatch.
Task 4: what finally guarantees
When divide(10, 2) succeeds, finally runs after the try; when divide(7, 0) throws, finally runs after the catch. That is why "Operation complete" prints twice. Integer division by 0 already throws an ArithmeticException with the message "/ by zero", but checking b == 0 first and adding your own message makes the error clearer.
- Does it take an index or a value?
- Missing: null or an exception?
- Is any order guaranteed?
- On error, where does control jump?
Answer these four questions and most collection and exception bugs become visible before you run anything.
General pattern
list.remove(value); // by value (Object)
list.remove(index); // by position (int)
if (map.containsKey(key)) { int v = map.get(key); }
for (Map.Entry<K, V> e : map.entrySet()) { use(e.getKey(), e.getValue()); }
for (Base item : items) { item.behaviour(); } // subclass version runs
try { risky(); }
catch (SomeException e) { report(e.getMessage()); }
finally { cleanUp(); } // runs either wayChoose remove by value or by index, check the key before get(), loop over the base type and let subclass methods run, and rely on finally running either way.
Reference answer: all four tasks
The reference answer below solves all four tasks. Practice2, which holds main, sits at the top of the file, above Shape, Circle and Rectangle. java Practice2.java looks for main in the first class, so if Shape came first the run would fail looking for main in Shape. The inventory is a LinkedHashMap, so the output order is the same on every run.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Practice2 {
static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("cannot divide " + a + " by zero");
}
return a / b;
}
public static void main(String[] args) {
// Task 1: ArrayList shopping list
List<String> shoppingList = new ArrayList<>();
shoppingList.add("rice");
shoppingList.add("eggs");
shoppingList.add("milk");
shoppingList.add("tea");
shoppingList.remove("eggs"); // remove by value
shoppingList.remove(0); // remove by index: "rice"
System.out.print("Task 1: shopping list ->");
for (String item : shoppingList) {
System.out.print(" " + item);
}
System.out.println();
// Task 2: HashMap inventory (LinkedHashMap keeps insertion order)
Map<String, Integer> inventory = new LinkedHashMap<>();
inventory.put("apple", 40);
inventory.put("banana", 25);
inventory.put("mango", 10);
inventory.put("apple", 35); // same key: replaces 40
inventory.remove("banana");
System.out.println("Task 2: has banana? " + inventory.containsKey("banana")
+ ", apples = " + inventory.get("apple")
+ ", grapes = " + inventory.get("grapes"));
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
System.out.println(" " + entry.getKey() + " x " + entry.getValue());
}
// Task 3: polymorphism over a Shape[] array
Shape[] shapes = { new Circle(5), new Rectangle(4, 6) };
for (Shape s : shapes) {
String kind = s.getClass().getSimpleName();
System.out.printf("Task 3: %s area = %.2f%n", kind, s.area());
}
// Task 4: try-catch-finally
int[][] pairs = { {10, 2}, {7, 0} };
for (int[] p : pairs) {
try {
int result = divide(p[0], p[1]);
System.out.println("Task 4: " + p[0] + " / " + p[1] + " = " + result);
} catch (ArithmeticException e) {
System.out.println("Task 4: error - " + e.getMessage());
} finally {
System.out.println(" Operation complete");
}
}
}
}
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private final double width;
private final double height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}Code breakdown
- Remove by value, then by index
shoppingList.remove(0); // remove by index: "rice"After "eggs" is removed by value, the list is [rice, milk, tea]. remove(0) then removes rice at index 0, leaving milk and tea.
- put() on an existing key
inventory.put("apple", 35); // same key: replaces 40apple already exists, so no new entry appears; 40 is replaced by 35. Re-putting an existing key in a LinkedHashMap keeps its position, so apple stays first.
- get() on a missing key
+ ", grapes = " + inventory.get("grapes"));There is no grapes key, so get() returns null, which shows up as "null" in the string. Concatenation survives it; unboxing into an int would not.
- One loop, two behaviours
for (Shape s : shapes) {s is typed as Shape, yet s.area() runs πr² (78.54) for the Circle and width × height (24.00) for the Rectangle. getClass().getSimpleName() reports the real object's class name.
- finally after both outcomes
System.out.println(" Operation complete");This line is inside finally, so it runs after the successful 10 / 2 and after the failed 7 / 0, which is why it appears twice in the output.
Task 1: shopping list -> milk tea
Task 2: has banana? false, apples = 35, grapes = null
apple x 35
mango x 10
Task 3: Circle area = 78.54
Task 3: Rectangle area = 24.00
Task 4: 10 / 2 = 5
Operation complete
Task 4: error - cannot divide 7 by zero
Operation completeDividing by zero: int and double differ
Task 4 checks b == 0 itself, but even without that check, an int division such as 7 / 0 makes Java throw an ArithmeticException with the message "/ by zero". A double division such as 7.0 / 0 does not throw at all: it returns Infinity, and 0.0 / 0 returns NaN.
So if you rewrote divide() with doubles, the catch block would never run and Infinity would slip silently into every later calculation. Checking the divisor first is the safe habit for both types.
In real projects
In real projects
These four tasks are fragments of real applications. A shopping cart is a List, product stock is a Map, and payment methods such as card, wallet and cash on delivery are implementations of an abstract class or interface, so checkout code simply calls pay() instead of asking which kind of payment it has with an if-else chain.
In production, finally releases resources such as files, database connections and locks. For resources that implement AutoCloseable, though, modern Java prefers try-with-resources, which is shorter and never forgets close(). And when tests hard-code a map's printed order, a HashMap makes them fragile; choose a LinkedHashMap or TreeMap whenever order matters, and your tests will pass on every machine.
Common mistakes
Common mistakes
Expecting remove(10) to remove a value
On a List<Integer>, remove(10) removes index 10. To remove a value, write remove(Integer.valueOf(10)). If the list is shorter you get an IndexOutOfBoundsException; if it is longer, the wrong element quietly disappears.
Modifying a list inside its for-each loop
Calling remove() on the list you are looping over usually throws ConcurrentModificationException, and in some cases silently skips an element instead. Use list.removeIf(...) or Iterator.remove().
Relying on Map.of() or HashMap order
Java promises no iteration order for HashMap, and the immutable maps built by Map.of() and Map.copyOf() can iterate in a different order from one JVM run to the next. When output order matters, use a LinkedHashMap or a TreeMap.
Calling divide() outside the try block
If int r = divide(7, 0); runs above the try and the try only prints r, the exception fires before the try begins and the catch never sees it. The call that can throw must itself be inside the try.
Mini challenge
Three new tasks: word counts, stock and new shapes
Practise collections, exceptions and inheritance once more. (1) Count the words in a sentence with a TreeMap. (2) Give a Stock class a take() method that throws a custom checked OutOfStockException when stock runs short, and handle each order separately. (3) Add Square and Triangle subclasses and compute their total area.
- The word count ignores case and lists the keys in alphabetical order
- OutOfStockException extends Exception and its message says how many were wanted and how many exist
- One failed order must not stop the orders after it
- Show the stock snapshot in insertion order (do not use Map.copyOf())
import java.util.*;
public class Practice2b {
static Map<String, Integer> wordCounts(String text) {
// TODO: TreeMap; split on whitespace; merge(word, 1, Integer::sum)
return new TreeMap<>();
}
public static void main(String[] args) {
// TODO: count words; run four orders through a Stock, each in its own
// try-catch; sum the areas of a Square and a Triangle
}
}
class OutOfStockException extends Exception { /* TODO: message constructor */ }
class Stock {
private final Map<String, Integer> items = new LinkedHashMap<>();
void add(String item, int qty) { /* TODO */ }
void take(String item, int qty) throws OutOfStockException { /* TODO */ }
}
// TODO: abstract class Shape, plus Square(side) and Triangle(base, height)Expected: {and=2, bat=1, cat=1, hat=1, the=3}, two successful orders and two failed ones (notebook and stapler), left: {pen=0, notebook=3}, and total area = 19.0.
Show hint
counts.merge(word, 1, Integer::sum) inserts 1 for a new key and adds 1 otherwise. In take(), items.getOrDefault(item, 0) treats an unknown item as 0 in stock; throw when that is less than qty.
Show solution
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Practice2b {
static Map<String, Integer> wordCounts(String text) {
Map<String, Integer> counts = new TreeMap<>(); // sorted by key
for (String word : text.toLowerCase().split("\s+")) {
counts.merge(word, 1, Integer::sum);
}
return counts;
}
public static void main(String[] args) {
System.out.println(wordCounts("The cat and the hat and THE bat"));
Stock stock = new Stock();
stock.add("pen", 10);
stock.add("notebook", 3);
String[][] orders = {
{"pen", "4"}, {"notebook", "5"}, {"stapler", "1"}, {"pen", "6"},
};
for (String[] order : orders) {
try {
stock.take(order[0], Integer.parseInt(order[1]));
System.out.println("took " + order[1] + " " + order[0]);
} catch (OutOfStockException e) {
System.out.println("order failed: " + e.getMessage());
}
}
System.out.println("left: " + stock.snapshot());
List<Shape> shapes = List.of(new Square(3), new Triangle(4, 5));
double total = 0;
for (Shape s : shapes) {
total += s.area();
}
System.out.println("total area = " + total);
}
}
class OutOfStockException extends Exception {
OutOfStockException(String message) {
super(message);
}
}
class Stock {
private final Map<String, Integer> items = new LinkedHashMap<>();
void add(String item, int qty) {
items.merge(item, qty, Integer::sum);
}
void take(String item, int qty) throws OutOfStockException {
int have = items.getOrDefault(item, 0);
if (have < qty) {
throw new OutOfStockException(item + ": wanted " + qty + ", have " + have);
}
items.put(item, have - qty);
}
Map<String, Integer> snapshot() {
return new LinkedHashMap<>(items); // a copy, still in insertion order
}
}
abstract class Shape {
abstract double area();
}
class Square extends Shape {
private final double side;
Square(double side) { this.side = side; }
@Override double area() { return side * side; }
}
class Triangle extends Shape {
private final double base;
private final double height;
Triangle(double base, double height) { this.base = base; this.height = height; }
@Override double area() { return 0.5 * base * height; }
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- remove(Object) removes by value and remove(int) by index; beware on Integer lists
- A map's get() returns null for a missing key, so check containsKey() first
- When order matters, choose a LinkedHashMap or TreeMap over a HashMap
- Looping over a base type runs each subclass's method at runtime
- finally runs after both success and failure, after any catch