These are the notes for Low-Level Design (LLD) episode 5, the last of the four "Java for LLD" toolkit episodes. Real designs must handle failure, missing values and behaviour that changes from one call to the next, and they must protect their data. Each tool is invented as the fix for a bug in our food-delivery app: exceptions (stack traces, try / catch / finally, throw vs throws, checked vs unchecked, try-with-resources, custom exceptions), Optional, functional interfaces and lambda expressions (with Predicate, Function, Supplier, Consumer and method references), streams (filter, map, collect) and immutability (String immutability and unmodifiable collections). Every program was run with javac Main.java && java -cp . Main (Java 21), the same way the SyntaxPilot compiler runs it; all outputs and error messages are real.
1. Exceptions
The problem: one bad price kills the bill
Prices arrive as text, and Integer.parseInt turns text into an int. One restaurant typed a price in words.
public class Main {
public static void main(String[] args) {
String[] prices = {"250", "180", "two fifty", "400"};
int total = 0;
for (String p : prices) {
total += Integer.parseInt(p);
}
System.out.println("Bill total: Rs " + total);
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "two fifty"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at Main.main(Main.java:6)
The bill total is never printed.
- An exception is an object Java creates when something goes wrong while the program runs. It stops the normal flow; if nobody handles it, the program ends and prints it.
- The lines starting with
atare the stack trace: the chain of method calls that led to the problem, newest first. Find the first line that is your code (Main.main(Main.java:6)): that is where to look.
The fix: try and catch
Like a trapeze act: the risky jump goes in try, the safety net is catch, and cleaning the ring afterwards (always) is finally.
public class Main {
public static void main(String[] args) {
String[] prices = {"250", "180", "two fifty", "400"};
int total = 0;
for (String p : prices) {
try {
total += Integer.parseInt(p);
} catch (NumberFormatException e) {
System.out.println("Skipping bad price: " + e.getMessage());
}
}
System.out.println("Bill total: Rs " + total);
}
}
Skipping bad price: For input string: "two fifty"
Bill total: Rs 830
catch (NumberFormatException e)catches only that type of exception (and its subclasses).eis the exception object;e.getMessage()is its text.- You can have several
catchblocks, from most specific to most general.
finally and throw
A rider must be released whether the delivery works or fails.
public class Main {
static void deliver(String dish) {
System.out.println("Rider booked for [" + dish + "]");
try {
if (dish.isEmpty())
throw new IllegalArgumentException("No dish given");
System.out.println("Delivered " + dish);
return;
} finally {
System.out.println("Rider released");
}
}
public static void main(String[] args) {
deliver("Dosa");
try {
deliver("");
} catch (IllegalArgumentException e) {
System.out.println("Failed: " + e.getMessage());
}
}
}
Rider booked for [Dosa]
Delivered Dosa
Rider released
Rider booked for []
Rider released
Failed: No dish given
throwcreates and raises an exception right now:throw new IllegalArgumentException("No dish given").IllegalArgumentExceptionis Java's standard exception for a bad argument.finallyruns on every path: after a normal end, afterreturn(Dosa), and after an exception (the empty dish), before the exception travels on to the caller'scatch.
2. Checked vs unchecked exceptions, throw vs throws
The problem: reading a file does not compile
import java.nio.file.*;
public class Main {
static String loadMenu() {
return Files.readString(Path.of("menu.txt"));
}
public static void main(String[] args) {
System.out.println(loadMenu());
}
}
Main.java:5: error: unreported exception IOException; must be caught or declared to be thrown
return Files.readString(Path.of("menu.txt"));
^
1 error
Files.readString reads a whole file into a String. Why does the compiler insist here, when parseInt never needed a try?
| Checked exceptions | Unchecked exceptions | |
|---|---|---|
| Real-life example | Rain or a closed road: not your fault, plan for it | Writing the wrong address: your bug, fix it |
| Meaning | A problem outside your control (missing file, network down) | A bug in the code (bad format, null, bad index) |
| Classes | Exception and its subclasses, except RuntimeException (e.g. IOException) |
RuntimeException and its subclasses (e.g. NumberFormatException, NullPointerException, IllegalArgumentException) |
| Compiler | Forces you to catch it or declare it with throws |
Does not force anything |
(A third family, Error, such as OutOfMemoryError, is for serious JVM problems you normally don't catch.)
The fix: declare with throws, catch in the caller
import java.io.IOException;
import java.nio.file.*;
public class Main {
static String loadMenu() throws IOException {
return Files.readString(Path.of("menu.txt"));
}
public static void main(String[] args) {
try {
System.out.println(loadMenu());
} catch (IOException e) {
System.out.println("Menu missing: " + e);
}
}
}
Menu missing: java.nio.file.NoSuchFileException: menu.txt
throws IOExceptionin a method's signature (its first line) is a warning label: "I may fail this way; caller, you handle it."throw(no s) raises an exception now;throws(with s) declares that a method may raise one.
3. try-with-resources
A resource is anything you must open and later close: a file, a database connection, a network socket, our kitchen printer.
The problem: the printer is left on
class Printer {
Printer() { System.out.println("Printer ON"); }
void print(String bill) {
if (bill.isEmpty()) throw new IllegalStateException("Empty bill");
System.out.println("Printing: " + bill);
}
void close() { System.out.println("Printer OFF"); }
}
public class Main {
public static void main(String[] args) {
try {
Printer p = new Printer();
p.print("Dosa Rs 120");
p.print("");
p.close();
} catch (IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Printer ON
Printing: Dosa Rs 120
Error: Empty bill
The exception jumped to catch and skipped close(). That is a resource leak: something left open that nobody will close.
The fix: AutoCloseable + try-with-resources
class Printer implements AutoCloseable {
Printer() { System.out.println("Printer ON"); }
void print(String bill) {
if (bill.isEmpty()) throw new IllegalStateException("Empty bill");
System.out.println("Printing: " + bill);
}
public void close() { System.out.println("Printer OFF"); }
}
public class Main {
public static void main(String[] args) {
try (Printer p = new Printer()) {
p.print("Dosa Rs 120");
p.print("");
} catch (IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Printer ON
Printing: Dosa Rs 120
Printer OFF
Error: Empty bill
AutoCloseableis a Java interface with one method,close(). Any class that implements it can be used in try-with-resources.- try-with-resources: create the resource in brackets after
try. Java callsclose()automatically when the block ends, normally or by an exception, and before thecatchruns. Several resources can be separated with;; they are closed in reverse order. - Like an automatic switch-off timer: you can't forget.
4. Custom exceptions
"Something went wrong" is useless; "Paneer Tikka is out of stock" lets the app suggest another dish. A custom exception is your own exception class, named after a problem in your business, that can carry data.
class OutOfStockException extends Exception {
private final String dish;
OutOfStockException(String dish) {
super(dish + " is out of stock");
this.dish = dish;
}
String dish() { return dish; }
}
public class Main {
static void order(String dish, int left) throws OutOfStockException {
if (left == 0) throw new OutOfStockException(dish);
System.out.println("Ordered " + dish);
}
public static void main(String[] args) {
try {
order("Biryani", 3);
order("Paneer Tikka", 0);
} catch (OutOfStockException e) {
System.out.println(e.getMessage());
System.out.println("Suggest a dish instead of " + e.dish());
}
}
}
Ordered Biryani
Paneer Tikka is out of stock
Suggest a dish instead of Paneer Tikka
Without throws OutOfStockException on order, it doesn't compile, because it extends Exception (checked):
Main.java:11: error: unreported exception OutOfStockException; must be caught or declared to be thrown
if (left == 0) throw new OutOfStockException(dish);
^
Main.java:18: error: exception OutOfStockException is never thrown in body of corresponding try statement
} catch (OutOfStockException e) {
^
2 errors
super(message)passes the message to the parentException, sogetMessage()returns it.- Extend
Exception(checked) when callers can and should plan for the problem (out of stock, invalid coupon). ExtendRuntimeException(unchecked) when it signals a programming bug or a broken rule that callers can't fix.
5. Optional instead of null
The problem: null hides in the type
null means "no object at all". Map.get returns null for a missing key.
import java.util.*;
record Dish(String name, int price) { }
public class Main {
static Map<String, Dish> menu = Map.of(
"dosa", new Dish("Dosa", 120), "idli", new Dish("Idli", 60));
static Dish find(String name) { return menu.get(name); }
public static void main(String[] args) {
System.out.println(find("dosa").price());
System.out.println(find("pizza").price());
}
}
120
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Dish.price()" because the return value of "Main.find(String)" is null
at Main.main(Main.java:11)
The return type said Dish, so nothing warned the caller that it might get nothing. A NullPointerException (NPE) is thrown when you use a null as if it were an object.
The fix: Optional<Dish>
Optional<T> is a box that holds either one value or nothing. The empty box is Optional.empty(). Like a parcel box you must open before use, instead of a clerk handing you empty hands.
import java.util.*;
record Dish(String name, int price) { }
public class Main {
static Map<String, Dish> menu = Map.of(
"dosa", new Dish("Dosa", 120), "idli", new Dish("Idli", 60));
static Optional<Dish> find(String name) {
return Optional.ofNullable(menu.get(name));
}
public static void main(String[] args) {
System.out.println(find("pizza").price());
}
}
Main.java:12: error: cannot find symbol
System.out.println(find("pizza").price());
^
symbol: method price()
location: class Optional<Dish>
1 error
The run-time crash became a compile-time error: you can no longer forget the empty case.
import java.util.*;
record Dish(String name, int price) { }
public class Main {
static Map<String, Dish> menu = Map.of(
"dosa", new Dish("Dosa", 120), "idli", new Dish("Idli", 60));
static Optional<Dish> find(String name) {
return Optional.ofNullable(menu.get(name));
}
public static void main(String[] args) {
System.out.println(find("pizza"));
Optional<Dish> d = find("pizza");
if (d.isPresent()) System.out.println(d.get().price());
else System.out.println("Pizza is not on the menu");
Dish idli = find("idli").orElse(new Dish("None", 0));
System.out.println(idli.price());
}
}
Optional.empty
Pizza is not on the menu
60
| Method | Meaning |
|---|---|
Optional.of(x) |
A full box (x must not be null) |
Optional.ofNullable(x) |
Full if x is not null, else empty |
Optional.empty() |
The empty box |
isPresent() / isEmpty() |
Is there a value? |
get() |
The value; throws NoSuchElementException: No value present if empty |
orElse(backup) |
The value, or the backup |
map(f) |
Transform the value if present (find("idli").map(Dish::price)) |
ifPresent(action) |
Run code only when there is a value |
Use Optional as a return type for results that may be missing; don't use it for fields or method parameters.
6. Functional interfaces and lambda expressions
The problem: copy-pasted filter methods
import java.util.*;
record Dish(String name, int price, boolean veg) {
public String toString() { return name; }
}
public class Main {
static List<Dish> vegOnly(List<Dish> menu) {
List<Dish> out = new ArrayList<>();
for (Dish d : menu) if (d.veg()) out.add(d);
return out;
}
static List<Dish> under200(List<Dish> menu) {
List<Dish> out = new ArrayList<>();
for (Dish d : menu) if (d.price() < 200) out.add(d);
return out;
}
public static void main(String[] args) {
List<Dish> menu = List.of(new Dish("Dosa", 120, true),
new Dish("Biryani", 250, false), new Dish("Paneer", 220, true));
System.out.println(vegOnly(menu));
System.out.println(under200(menu));
}
}
[Dosa, Paneer]
[Dosa]
The two methods are identical except for one condition (line 9 vs line 14). Ten filters would mean ten copies of the loop.
The fix: pass the condition as an object
A helper walks through every tiffin (the loop, written once); you hand over a sticky note with one rule (the condition).
import java.util.*;
record Dish(String name, int price, boolean veg) {
public String toString() { return name; }
}
@FunctionalInterface
interface DishTest {
boolean test(Dish d);
}
public class Main {
static List<Dish> filter(List<Dish> menu, DishTest t) {
List<Dish> out = new ArrayList<>();
for (Dish d : menu) if (t.test(d)) out.add(d);
return out;
}
public static void main(String[] args) {
List<Dish> menu = List.of(new Dish("Dosa", 120, true),
new Dish("Biryani", 250, false), new Dish("Paneer", 220, true));
System.out.println(filter(menu, d -> d.veg()));
System.out.println(filter(menu, d -> d.price() < 200));
System.out.println(filter(menu, d -> !d.veg() && d.price() > 200));
}
}
[Dosa, Paneer]
[Dosa]
[Biryani]
- A functional interface is an interface with exactly one abstract method (
DishTest.test). Default and static methods don't count. @FunctionalInterfaceis an annotation (a label starting with@that gives the compiler extra information): it asks the compiler to check the "exactly one" rule.- A lambda expression is a short, nameless function that implements a functional interface:
parameters -> result.d -> d.veg()means "given a dish d, return d.veg()". With several statements use braces andreturn:d -> { int p = d.price(); return p < 200; }.
Before lambdas (Java 7 and earlier) you wrote an anonymous class, a class with no name created on the spot:
filter(menu, new DishTest() {
public boolean test(Dish d) { return d.veg(); }
});
Adding a second abstract method breaks it:
Main.java:6: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
DishTest is not a functional interface
multiple non-overriding abstract methods found in interface DishTest
Main.java:20: error: incompatible types: DishTest is not a functional interface
System.out.println(filter(menu, d -> d.veg()));
^
multiple non-overriding abstract methods found in interface DishTest
With two abstract methods, a lambda would not know which one it is implementing.
7. Predicate, Function, Supplier, Consumer
Java ships the common shapes in the package java.util.function, so you rarely write your own.
| Interface | Shape | Method | Real-life example |
|---|---|---|---|
Predicate<T> |
T -> boolean | test |
Quality check: is it fresh? |
Function<T, R> |
T -> R | apply |
Raw rice in, cooked rice out |
Supplier<T> |
() -> T | get |
Token machine: gives one, takes nothing |
Consumer<T> |
T -> nothing | accept |
The customer eats it |
import java.util.function.*;
public class Main {
public static void main(String[] args) {
Predicate<Integer> cheap = price -> price < 200;
Function<Integer, Integer> addPacking = price -> price + 10;
Supplier<String> newOrderId = () -> "ORD-" + 1042;
Consumer<String> sms = msg -> System.out.println("SMS: " + msg);
System.out.println(cheap.test(120));
System.out.println(addPacking.apply(200));
System.out.println(newOrderId.get());
sms.accept("Your dosa is on the way");
}
}
true
210
ORD-1042
SMS: Your dosa is on the way
Our DishTest is really a Predicate<Dish>.
Method references
When a lambda only calls one existing method, name the method with ::. This is a method reference.
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) {
Function<String, String> shout = s -> s.toUpperCase();
Function<String, String> shout2 = String::toUpperCase;
Consumer<String> show = System.out::println;
show.accept(shout.apply("dosa"));
show.accept(shout2.apply("idli"));
List.of("vada", "upma").forEach(System.out::println);
}
}
DOSA
IDLI
vada
upma
| Lambda | Method reference | Kind |
|---|---|---|
s -> s.toUpperCase() |
String::toUpperCase |
method of the input object |
x -> System.out.println(x) |
System.out::println |
method of a specific object |
s -> Integer.parseInt(s) |
Integer::parseInt |
static method |
() -> new ArrayList<>() |
ArrayList::new |
constructor |
forEach(action) runs a Consumer for every element of a collection.
8. Streams: filter, map, collect
The problem: the "what" buried in the "how"
import java.util.*;
record Dish(String name, int price, boolean veg) { }
public class Main {
public static void main(String[] args) {
List<Dish> menu = List.of(new Dish("Dosa", 120, true),
new Dish("Biryani", 250, false), new Dish("Paneer", 220, true),
new Dish("Thali", 300, true));
List<String> result = new ArrayList<>();
for (Dish d : menu) {
if (d.veg() && d.price() < 250) {
result.add(d.name().toUpperCase());
}
}
System.out.println(result);
}
}
[DOSA, PANEER]
The fix: a stream pipeline
A stream is a sequence of items flowing through steps, like dishes on a kitchen assembly line. menu.stream() puts the items on the belt; it never changes the source list.
import java.util.*;
import java.util.stream.*;
record Dish(String name, int price, boolean veg) { }
public class Main {
public static void main(String[] args) {
List<Dish> menu = List.of(new Dish("Dosa", 120, true),
new Dish("Biryani", 250, false), new Dish("Paneer", 220, true),
new Dish("Thali", 300, true));
List<String> result = menu.stream()
.filter(d -> d.veg())
.filter(d -> d.price() < 250)
.map(d -> d.name().toUpperCase())
.collect(Collectors.toList());
System.out.println(result);
System.out.println(menu.stream().filter(Dish::veg).count());
System.out.println(menu.size());
}
}
[DOSA, PANEER]
3
4
filter(predicate)keeps only items for which thePredicatereturns true.map(function)turns each item into something else with aFunction(a verb here, not theMapcollection).collect(Collectors.toList())gathers the results into a collection. Since Java 16,.toList()is a shorter way (it returns an unmodifiable list).filterandmapare intermediate operations (they return another stream and are lazy: nothing happens yet).collect,count,forEachare terminal operations: they start the flow and produce the result.- Other common operations:
sorted(),distinct(),limit(n),min(comparator),anyMatch(predicate),mapToInt(...).sum().
A stream is used once
import java.util.*;
import java.util.stream.*;
record Dish(String name, int price, boolean veg) { }
public class Main {
public static void main(String[] args) {
List<Dish> menu = List.of(new Dish("Dosa", 120, true),
new Dish("Biryani", 250, false), new Dish("Paneer", 220, true));
Stream<Dish> veg = menu.stream().filter(Dish::veg);
System.out.println(veg.count());
System.out.println(veg.map(Dish::name).toList());
}
}
2
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.base/java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203)
...
at Main.main(Main.java:12)
Once a terminal operation runs, the stream is finished. Call menu.stream() again.
9. Immutability
Immutable means "can never change after it is created". Mutable means it can.
String immutability
public class Main {
public static void main(String[] args) {
String dish = "masala dosa";
dish.toUpperCase();
System.out.println(dish);
String loud = dish.toUpperCase();
System.out.println(loud);
String saved = dish;
dish = dish + " with chutney";
System.out.println(saved);
System.out.println(dish);
}
}
masala dosa
MASALA DOSA
masala dosa
masala dosa with chutney
dish.toUpperCase()does not changedish; it returns a new String. Ignoring the result is a classic bug.dish = dish + " with chutney"makes a new String and points the variabledishat it;savedstill points to the old one.- Because Strings never change, they are safe to share and to use as
HashMapkeys, and Java can reuse equal string literals (the string pool).
The problem: handing out your own list
import java.util.*;
class Restaurant {
private final List<String> menu = new ArrayList<>();
Restaurant() { menu.add("Dosa"); menu.add("Idli"); }
List<String> getMenu() { return menu; }
}
public class Main {
public static void main(String[] args) {
Restaurant r = new Restaurant();
List<String> m = r.getMenu();
m.clear();
System.out.println("Menu now: " + r.getMenu());
}
}
Menu now: []
private didn't help: we returned the list itself. final only means the variable can't point to another list; the list's contents can still change. (Like a whiteboard menu anyone can wipe.)
The fix: unmodifiable collections
import java.util.*;
class Restaurant {
private final List<String> menu = new ArrayList<>();
Restaurant() { menu.add("Dosa"); menu.add("Idli"); }
List<String> getMenu() {
return Collections.unmodifiableList(menu);
}
}
public class Main {
public static void main(String[] args) {
Restaurant r = new Restaurant();
List<String> m = r.getMenu();
m.clear();
System.out.println("Menu now: " + r.getMenu());
}
}
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.Collections$UnmodifiableCollection.clear(Collections.java:1111)
at Main.main(Main.java:14)
View vs copy vs List.of
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> menu = new ArrayList<>(List.of("Dosa", "Idli"));
List<String> view = Collections.unmodifiableList(menu);
List<String> copy = List.copyOf(menu);
menu.add("Vada");
System.out.println("view: " + view);
System.out.println("copy: " + copy);
List<String> fixed = List.of("Tea", "Coffee");
fixed.add("Juice");
}
}
view: [Dosa, Idli, Vada]
copy: [Dosa, Idli]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)
at Main.main(Main.java:12)
| Can the caller change it? | Does it follow the original? | |
|---|---|---|
Collections.unmodifiableList(list) |
No | Yes: a live read-only view (a glass window) |
List.copyOf(list) |
No | No: a read-only snapshot |
List.of(...), Set.of, Map.of |
No | (no original) |
new ArrayList<>(list) |
Yes | No: a mutable copy |
Design rule: make objects immutable where you can (records, final fields, no setters), and never hand out your own mutable collection; return List.copyOf or an unmodifiable view.
Common mistakes
| Mistake | Exact message | Why | Fix |
|---|---|---|---|
| Parsing text that isn't a number | java.lang.NumberFormatException: For input string: "two fifty" |
Unchecked, crashes if not caught | try / catch (NumberFormatException e) |
| Calling a method that throws a checked exception | unreported exception IOException; must be caught or declared to be thrown |
IOException is checked |
catch it or add throws IOException |
Throwing a custom checked exception without throws |
unreported exception OutOfStockException; must be caught or declared to be thrown |
It extends Exception |
Add throws OutOfStockException |
Catching a checked exception the try can't throw |
exception OutOfStockException is never thrown in body of corresponding try statement |
Dead catch |
Remove it, or call the method that throws it |
Calling a method on null |
NullPointerException: Cannot invoke "Dish.price()" because the return value of "Main.find(String)" is null |
The type hid the empty case | Return Optional<Dish> |
Calling get() on an empty Optional |
java.util.NoSuchElementException: No value present |
The box is empty | isPresent(), orElse(...) |
| Using an Optional as if it were the value | cannot find symbol ... method price() ... location: class Optional<Dish> |
It's a box | map, orElse, get after checking |
Two abstract methods with @FunctionalInterface |
Unexpected @FunctionalInterface annotation ... DishTest is not a functional interface |
Needs exactly one | Keep one abstract method |
| Reusing a stream | IllegalStateException: stream has already been operated upon or closed |
Streams run once | Create a new stream |
| Ignoring a String method's result | No error: masala dosa still small |
Strings are immutable | dish = dish.toUpperCase(); |
Changing List.of(...) or an unmodifiable view |
java.lang.UnsupportedOperationException |
Read-only list | Copy into new ArrayList<>(...) |
| Forgetting to close a resource | No error: Printer OFF never printed |
Exception skipped close() |
try-with-resources |
Mini project
Build a Restaurant with: cheapestVegDish() returning Optional<Dish> (a stream with min), namesOver(limit) returning sorted names (stream), applyCoupon throwing a checked InvalidCouponException, an OrderLog resource used with try-with-resources, and getOrders() that can't be changed from outside.
Solution
import java.util.*;
import java.util.stream.*;
record Dish(String name, int price, boolean veg) { }
class InvalidCouponException extends Exception {
InvalidCouponException(String code) { super("Invalid coupon: " + code); }
}
class OrderLog implements AutoCloseable {
OrderLog() { System.out.println("[log opened]"); }
void write(String line) { System.out.println("[log] " + line); }
public void close() { System.out.println("[log closed]"); }
}
class Restaurant {
private final List<Dish> menu = new ArrayList<>();
private final List<String> orders = new ArrayList<>();
void add(Dish d) { menu.add(d); }
Optional<Dish> cheapestVegDish() {
return menu.stream()
.filter(Dish::veg)
.min(Comparator.comparingInt(Dish::price));
}
List<String> namesOver(int limit) {
return menu.stream()
.filter(d -> d.price() > limit)
.map(Dish::name)
.sorted()
.collect(Collectors.toList());
}
int applyCoupon(int amount, String code) throws InvalidCouponException {
if (!code.equals("SAVE50")) throw new InvalidCouponException(code);
return Math.max(0, amount - 50);
}
void placeOrder(String dish) { orders.add(dish); }
List<String> getOrders() { return List.copyOf(orders); }
}
public class Main {
public static void main(String[] args) {
Restaurant r = new Restaurant();
r.add(new Dish("Dosa", 120, true));
r.add(new Dish("Biryani", 250, false));
r.add(new Dish("Paneer", 220, true));
r.add(new Dish("Thali", 300, true));
System.out.println(r.cheapestVegDish().map(Dish::name).orElse("none"));
System.out.println(r.namesOver(200));
try (OrderLog log = new OrderLog()) {
log.write("Total: " + r.applyCoupon(300, "SAVE50"));
log.write("Total: " + r.applyCoupon(300, "FREEFOOD"));
} catch (InvalidCouponException e) {
System.out.println(e.getMessage());
}
r.placeOrder("Dosa");
List<String> orders = r.getOrders();
try {
orders.add("Free biryani");
} catch (UnsupportedOperationException e) {
System.out.println("Orders are read-only: " + r.getOrders());
}
}
}
Dosa
[Biryani, Paneer, Thali]
[log opened]
[log] Total: 250
[log closed]
Invalid coupon: FREEFOOD
Orders are read-only: [Dosa]
Comparator.comparingInt(Dish::price) (episode 4) compares dishes by price; min returns an Optional because the stream might be empty. Notice [log closed] prints before the catch.
Practice
- What does this print?
static int parse(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return -1;
} finally {
System.out.println("checked " + s);
}
}
// main: System.out.println(parse("42")); System.out.println(parse("x"));
Solution
checked 42
42
checked x
-1
finally runs before the method actually returns, so "checked" prints first each time.
- Checked or unchecked: (a) the payment gateway's server is down, (b) a negative quantity passed to
addItemby our own code, (c)ArrayIndexOutOfBoundsException?
Solution
(a) Checked (outside our control; callers should plan for it, e.g. retry). (b) Unchecked, e.g. IllegalArgumentException (a bug in the caller). (c) Unchecked: it is a RuntimeException; its message looks like Index 5 out of bounds for length 2.
- Write a stream that gives the lengths of the dishes containing the letter "d" in
List.of("idli", "dosa", "vada", "upma").
Solution
dishes.stream().filter(d -> d.contains("d")).map(String::length).collect(Collectors.toList())
[4, 4, 4]
String s = "chai"; s.concat(" latte"); System.out.println(s);prints?
Solution
chai. concat returns a new String, which was thrown away. Write s = s.concat(" latte");.
- What happens with
Optional<String> none = Optional.empty(); none.get();?
Solution
Exception in thread "main" java.util.NoSuchElementException: No value present. Use none.orElse("no tea"), which prints no tea.
- Which functional interface fits: (a) "generate a new coupon code", (b) "is this order above Rs 500?", (c) "print a receipt line", (d) "turn a Dish into its price"?
Solution
(a) Supplier<String>, (b) Predicate<Order>, (c) Consumer<String>, (d) Function<Dish, Integer>.
Quick quiz
List<Integer> prices = List.of(120, 250, 60);
long n = prices.stream()
.filter(p -> p < 200)
.count();
System.out.println(n + " " + prices.size());
- 2 2
- 2 3
- 3 3
- UnsupportedOperationException
Answer
2 3 (run for real). filter keeps 120 and 60, so the count is 2; a stream never changes its source, so the list still has 3 prices.
Interview questions
- Checked vs unchecked exceptions? Checked (
Exceptionbut notRuntimeException) must be caught or declared; they model recoverable problems outside the code's control. Unchecked (RuntimeException) model bugs; the compiler doesn't force handling. throwvsthrows?throwraises an exception object now;throwsin a signature declares exceptions a method may raise.- Does
finallyrun if thetryreturns? Yes (it runs before the method returns). It is skipped only if the JVM stops, e.g.System.exit. - What does try-with-resources need? The resource must implement
AutoCloseable;close()runs automatically, in reverse order of opening, even on exceptions. - Why use
Optional? It makes "may be missing" part of the return type, so callers must handle the empty case; avoid it for fields and parameters. - What is a functional interface? An interface with exactly one abstract method; lambdas and method references implement it. Examples:
Runnable,Comparator,Predicate. - Intermediate vs terminal stream operations? Intermediate (
filter,map,sorted) return a stream and are lazy; terminal (collect,count,forEach) run the pipeline. A stream can't be reused. - Why are Strings immutable in Java? Safety when shared (including across threads), safe as map keys, and the string pool can reuse literals.
Collections.unmodifiableListvsList.copyOf? The first is a live read-only view of the original; the second is an independent read-only snapshot.
Glossary
| Term | Meaning, with an example |
|---|---|
| Exception | An object describing a problem while the program runs; it stops normal flow. NumberFormatException |
| Stack trace | The list of method calls that led to an exception, newest first. at Main.main(Main.java:6) |
try |
The block of code that may fail |
catch |
A block that handles one type of exception. catch (NumberFormatException e) |
finally |
A block that always runs after try/catch, even after return or an exception |
throw |
Raises an exception now. throw new IllegalArgumentException("No dish given") |
throws |
Declares in a method signature that it may raise an exception. loadMenu() throws IOException |
| Method signature | A method's first line: name, parameters, return type, throws |
| Checked exception | An exception the compiler forces you to catch or declare; for problems outside your control. IOException |
| Unchecked exception | A RuntimeException (or subclass); usually a bug; not forced. NullPointerException |
RuntimeException |
The parent class of all unchecked exceptions |
IOException |
A checked exception for input/output problems such as a missing file |
NumberFormatException |
Thrown when text can't be turned into a number. Integer.parseInt("two fifty") |
IllegalArgumentException |
Standard unchecked exception for a bad argument |
IllegalStateException |
Unchecked exception: an object is in the wrong state for the call (a used stream) |
getMessage() |
The text of an exception |
| Resource | Something you open and must close: file, connection, printer |
| Resource leak | A resource left open because close() never ran |
AutoCloseable |
Interface with one method close(), needed for try-with-resources |
| try-with-resources | try (Printer p = new Printer()) { ... }: closes the resource automatically |
| Custom exception | Your own exception class for a business problem. class OutOfStockException extends Exception |
null |
"No object at all"; using it like an object throws NullPointerException |
NullPointerException |
Thrown when you call a method or read a field on null |
Optional<T> |
A box with one value or nothing. Optional<Dish> |
Optional.empty() |
The empty Optional; prints as Optional.empty |
Optional.ofNullable(x) |
Full box if x isn't null, else empty |
orElse(backup) |
The value, or the backup if empty |
isPresent() / get() |
Check for a value / take it (throws NoSuchElementException if empty) |
| Functional interface | An interface with exactly one abstract method. interface DishTest { boolean test(Dish d); } |
| Annotation | A label starting with @ that gives the compiler or tools extra information. @FunctionalInterface, @Override |
@FunctionalInterface |
Asks the compiler to check the one-abstract-method rule |
| Lambda expression | A short nameless function: d -> d.price() < 200 |
| Anonymous class | A class with no name, defined and created on the spot (the pre-lambda way) |
java.util.function |
The package with ready-made functional interfaces |
Predicate<T> |
T -> boolean, method test. price -> price < 200 |
Function<T, R> |
T -> R, method apply. price -> price + 10 |
Supplier<T> |
() -> T, method get. () -> "ORD-" + 1042 |
Consumer<T> |
T -> nothing, method accept. msg -> System.out.println(msg) |
| Method reference | Class::method, a lambda that just calls that method. String::toUpperCase |
forEach |
Runs a Consumer on every element. list.forEach(System.out::println) |
| Stream | A sequence of items flowing through steps; doesn't change its source. menu.stream() |
filter |
Stream step that keeps items matching a Predicate |
map (stream) |
Stream step that turns each item into another with a Function |
collect |
Terminal step that gathers results. collect(Collectors.toList()) |
Collectors.toList() |
A collector that builds a List |
| Intermediate operation | A lazy stream step returning a stream (filter, map, sorted) |
| Terminal operation | The step that runs the stream and produces a result (collect, count, forEach) |
| Pipeline | A chain of stream steps from source to result |
| Mutable | Can change after creation. ArrayList |
| Immutability / immutable | Can never change after creation. String, records, List.of(...) |
| String immutability | A String object never changes; methods like toUpperCase return a new String |
| String pool | Java's store of string literals, reused because Strings are immutable |
| Unmodifiable collection | A collection that rejects changes with UnsupportedOperationException |
Collections.unmodifiableList |
A live read-only view of a list |
List.copyOf |
A read-only snapshot copy of a list |
List.of |
A fixed, read-only list. List.of("Tea", "Coffee") |
UnsupportedOperationException |
Thrown when you try to change an unmodifiable collection |
| View | An object that shows another object's data live, without copying it |
Summary
- An exception is a problem object; read the stack trace from your own line.
try/catchhandles it,finallyalways runs,throwraises,throwsdeclares. - Checked exceptions (outside your control) must be caught or declared; unchecked ones (
RuntimeException) are bugs to fix. - try-with-resources +
AutoCloseablecloses resources automatically; custom exceptions name business problems and carry data. Optionalmakes missing values visible in the type and turns NPE crashes into compile errors.- A functional interface has one abstract method; lambdas and method references implement it. Java gives
Predicate,Function,Supplier,Consumer. - Streams (
filter,map,collect) express what you want; they never change the source and run once. - Immutable objects are safe to share: Strings never change; hand out
List.copyOfor unmodifiable views, never your own list.
Next episode: OOP 1: encapsulation and information hiding.