The browser is enough for the core course. A local JDK lets you keep source files, run the same checks outside the learning site, and later add capabilities the playground does not implement. Begin by reproducing the known behavior before introducing a build tool, network service or database.
Download and compile
Download expense-ledger.zip and extract it. Open a terminal in the expense-ledger folder containing Main.java and LedgerTest.java. The README lists the source files and contracts. Install a JDK 25 if needed; the official getting-started guide explains the tools. Check that both commands use the same major version:
Shell
java --versionjavac --version
A JDK includes the compiler javac and the launcher java. PATH is the operating system's search list for executable commands. If a command is missing, fix the installation or PATH before changing application code. The browser examples are checked against JDK 25, so use that version for a direct comparison.
From the source directory, run:
Shell
javac *.javajava Mainjava LedgerTest
The first command compiles the source set to .class files. The second launches the application demo; the third runs its tests. Use the class name without .class after java. Recompile after edits so tests do not accidentally execute old bytecode. LedgerTest prints All ledger checks passed only after every called test succeeds; no -ea flag or external test library is required.
Keep the core independent
The source files use the unnamed package so the same flat file set works in the browser. Larger local projects commonly introduce named packages, Maven or Gradle, and a framework such as JUnit for tests. Those are useful next tools, but adopting them should preserve the behavior of this core. Start by moving the same assertions into the chosen test runner rather than redesigning the ledger and build system simultaneously.
An optional file adapter should read text, call importText and decide how to display Accepted or Rejected. It must handle IOException separately from invalid records, choose an explicit character encoding such as UTF-8, and enforce a byte limit before loading an untrusted file fully into memory. The core's character limit cannot undo memory already spent reading a file. Real file I/O belongs in that local adapter; the browser's string reader does not demonstrate disk access.
What this course does not execute
The installed playground implements a Java subset rather than a JVM. Threads, concurrent collections, virtual-thread executors, HTTP clients and database transactions are separate local study topics. The version-check lesson demonstrates a decision rule sequentially; it does not demonstrate actual concurrent interleavings. Copying a map and assigning a field does not make Ledger safe for simultaneous callers.
For a concurrency extension, first specify the invariant: two conflicting updates must not both commit. The version comparison and state replacement must be protected together, using a synchronization strategy or a transactional store. A test should coordinate competing callers with explicit synchronization rather than hoping a sleep creates a race. Learn those APIs in a focused local exercise before changing this project. Similarly, browser timings cannot establish JVM throughput; JVM warm-up, allocation and measurement design matter.
Exercise
Verify the same project
Run the supplied LedgerTest locally or in the browser below. Change the candidate map construction to alias entries, run again and record the named rollback failure. Restore the copy and confirm success. Save your changed files outside the browser before leaving.
Hint 1: the idea
A late conflict must leave the ledger as it was before the batch. Aliasing makes earlier candidate insertions visible too soon.
Hint 2: a first step
Find the candidate initialization near the beginning of importText, then read testAtomicityAndReplay. Change only the copy operation.
Show one solution
With candidate and entries referring to the same map, staging B changes the real ledger before A conflicts. The late conflict rollback assertion fails. Restore a new LinkedHashMap constructed from entries. Recompile locally and run LedgerTest again; in the browser, Run recompiles the current file set. A compilation failure from a typo is not the requested behavioral failure.
Run the complete project
Run the ledger checksJavapublic record Accepted(int inserted, int replayed) implements ImportOutcome {
public Accepted {
if (inserted < 0 || replayed < 0) {
throw new IllegalArgumentException("negative count");
}
}
}
public enum Category {
FOOD,
TRAVEL,
OTHER
}
import java.math.BigDecimal;
import java.math.RoundingMode;
/** One currency; immutable, normalized values make exact replay comparison meaningful. */
public record Expense(String id, Category category, BigDecimal amount) {
public Expense {
if (id == null || id.trim().isEmpty()) {
throw new IllegalArgumentException("id required");
}
id = id.trim();
if (id.length() > 24 || id.contains(";") || id.contains("\n") || id.contains("\r")) {
throw new IllegalArgumentException("invalid id");
}
if (category == null || amount == null) {
throw new IllegalArgumentException("category and amount required");
}
if (amount.signum() <= 0 || amount.compareTo(new BigDecimal("1000000.00")) > 0) {
throw new IllegalArgumentException("amount outside 0.01..1000000.00");
}
try {
amount = amount.setScale(2, RoundingMode.UNNECESSARY);
} catch (ArithmeticException error) {
throw new IllegalArgumentException("amount needs at most two decimal places", error);
}
}
}
import java.math.BigDecimal;
/** Small unquoted format: id;category;amount. Categories are case-sensitive. */
public final class ExpenseParser {
public Expense parse(String line) {
if (line == null || line.length() > 120) {
throw new IllegalArgumentException("line missing or longer than 120 characters");
}
String[] fields = line.split(";", -1);
if (fields.length != 3) {
throw new IllegalArgumentException("expected id;category;amount");
}
String decimal = fields[2].trim();
// Reject exponents and unbounded scale before BigDecimal construction.
if (!decimal.matches("[0-9]{1,7}(\\.[0-9]{1,2})?")) {
throw new IllegalArgumentException("amount needs digits and up to two decimal places");
}
Category category;
try {
category = Category.valueOf(fields[1].trim());
} catch (IllegalArgumentException error) {
throw new IllegalArgumentException("category must be FOOD, TRAVEL or OTHER", error);
}
return new Expense(fields[0], category, new BigDecimal(decimal));
}
}
public sealed interface ImportOutcome permits Accepted, Rejected {}
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/** Single-threaded, in-memory atomic imports; no persistence or concurrent guarantee. */
public final class Ledger {
private Map<String, Expense> entries = new LinkedHashMap<>();
private final ExpenseParser parser;
public Ledger(ExpenseParser parser) {
if (parser == null) {
throw new IllegalArgumentException("parser required");
}
this.parser = parser;
}
public ImportOutcome importText(String text) {
if (text == null || text.length() > 12000) {
return new Rejected(List.of(new Problem(0, "input missing or longer than 12000 characters")));
}
Map<String, Expense> candidate = new LinkedHashMap<>(entries);
List<Problem> problems = new ArrayList<>();
int inserted = 0;
int replayed = 0;
int lineNumber = 0;
try (BufferedReader reader = new BufferedReader(new StringReader(text))) {
String line = reader.readLine();
while (line != null) {
lineNumber++;
if (lineNumber > 100) {
problems.add(new Problem(lineNumber, "more than 100 physical lines"));
break;
}
// Even whitespace-only lines must obey the per-line size limit.
if (line.length() > 120) {
problems.add(new Problem(lineNumber, "line longer than 120 characters"));
} else if (!line.trim().isEmpty()) {
try {
Expense incoming = parser.parse(line);
Expense old = candidate.get(incoming.id());
if (old == null) {
candidate.put(incoming.id(), incoming);
inserted++;
} else if (old.equals(incoming)) {
replayed++;
} else {
problems.add(new Problem(lineNumber, "conflicting id: " + incoming.id()));
}
} catch (IllegalArgumentException error) {
problems.add(new Problem(lineNumber, error.getMessage()));
}
}
line = reader.readLine();
}
} catch (IOException error) {
throw new IllegalStateException("in-memory read failed", error);
}
if (candidate.size() > 100) {
problems.add(new Problem(0, "ledger capacity is 100 expenses"));
}
if (!problems.isEmpty()) {
return new Rejected(problems);
}
// This assignment is the only commit point.
entries = candidate;
return new Accepted(inserted, replayed);
}
public Optional<Expense> find(String id) {
return Optional.ofNullable(entries.get(id));
}
public List<Expense> snapshot() {
return List.copyOf(entries.values());
}
public BigDecimal total() {
return entries.values().stream()
.map(Expense::amount)
.reduce(new BigDecimal("0.00"), BigDecimal::add);
}
public List<Expense> largestFirst() {
Comparator<Expense> byAmount = Comparator.comparing(Expense::amount);
return entries.values().stream()
.sorted(byAmount.reversed().thenComparing(Expense::id))
.toList();
}
public String exportText() {
List<Expense> ordered = new ArrayList<>(entries.values());
ordered.sort(Comparator.comparing(Expense::id));
StringBuilder result = new StringBuilder();
for (Expense expense : ordered) {
result.append(expense.id()).append(';')
.append(expense.category()).append(';')
.append(expense.amount().toPlainString()).append('\n');
}
return result.toString();
}
}
public class Main {
public static void main(String[] args) {
Ledger ledger = new Ledger(new ExpenseParser());
String text = "B;TRAVEL;12.50\nA;FOOD;3.25\n";
System.out.println(describe(ledger.importText(text)));
System.out.println(describe(ledger.importText(text)));
System.out.println(describe(ledger.importText("C;OTHER;2.00\nA;FOOD;9.00")));
System.out.println("Total: " + ledger.total().toPlainString());
System.out.print(ledger.exportText());
}
static String describe(ImportOutcome outcome) {
return switch (outcome) {
case Accepted accepted -> "Inserted: " + accepted.inserted() + ", replayed: " + accepted.replayed();
case Rejected rejected -> "Rejected: " + rejected.problems().size() + " problem(s)";
};
}
}
/** Line 0 means a whole-input limit or missing-input problem. */
public record Problem(int line, String message) {
public Problem {
if (line < 0 || message == null || message.isEmpty()) {
throw new IllegalArgumentException("valid problem required");
}
}
}
import java.util.List;
public record Rejected(List<Problem> problems) implements ImportOutcome {
public Rejected {
problems = List.copyOf(problems);
if (problems.isEmpty()) {
throw new IllegalArgumentException("rejection needs a problem");
}
}
}
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;
/** Named behavioral checks; run this entry after editing any project source. */
public class LedgerTest {
public static void main(String[] args) {
testParser();
testAtomicityAndReplay();
testReportsAndOwnership();
testLimits();
testRoundTrip();
testCapacity();
System.out.println("All ledger checks passed");
}
static Ledger fresh() {
return new Ledger(new ExpenseParser());
}
static void testParser() {
ExpenseParser parser = new ExpenseParser();
Expense expense = parser.parse(" A ; FOOD ; 2.0 ");
check("normalized value", expense.equals(new Expense("A", Category.FOOD, new BigDecimal("2.00"))));
check("maximum amount", parser.parse("MAX;OTHER;1000000.00").amount().compareTo(new BigDecimal("1000000")) == 0);
for (String invalid : new String[] {
"A;FOOD;0", "A;FOOD;-1", "A;FOOD;1.001", "A;FOOD;1e3",
"A;FOOD;1000000.01", "A;food;1", "A;FOOD;", ";FOOD;1", "A;FOOD;1;extra", null
}) {
try {
parser.parse(invalid);
throw new AssertionError("parser accepted " + invalid);
} catch (IllegalArgumentException expected) {
// Only documented input rejection counts.
}
}
}
static void testAtomicityAndReplay() {
Ledger ledger = fresh();
check("first insertion", ledger.importText("A;FOOD;2.00").equals(new Accepted(1, 0)));
check("normalized replay", ledger.importText(" A ; FOOD ; 2.0 ").equals(new Accepted(0, 1)));
String before = ledger.exportText();
ImportOutcome conflict = ledger.importText("B;OTHER;3.00\nA;FOOD;9.00");
check("conflict rejects", conflict instanceof Rejected);
check("late conflict rollback", ledger.exportText().equals(before));
check("no partial B", ledger.find("B").isEmpty());
check("late malformed rollback", ledger.importText("C;OTHER;1.00\nbad") instanceof Rejected);
check("malformed preserved state", ledger.exportText().equals(before));
check("within batch replay", ledger.importText("D;OTHER;1.00\nD;OTHER;1.00").equals(new Accepted(1, 1)));
before = ledger.exportText();
check("within batch conflict", ledger.importText("E;OTHER;1.00\nE;OTHER;2.00") instanceof Rejected);
check("within batch rollback", ledger.exportText().equals(before));
ImportOutcome error = ledger.importText("\nbad");
if (error instanceof Rejected rejected) {
check("physical line", rejected.problems().get(0).line() == 2);
try {
rejected.problems().clear();
throw new AssertionError("mutable problems");
} catch (UnsupportedOperationException expected) {
// Error results are snapshots too.
}
} else {
throw new AssertionError("bad line accepted");
}
}
static void testReportsAndOwnership() {
Ledger ledger = fresh();
ledger.importText("B;FOOD;2.00\nA;OTHER;2.00\nC;TRAVEL;1.00");
check("exact total", ledger.total().equals(new BigDecimal("5.00")));
check("amount order", ledger.largestFirst().get(2).id().equals("C"));
check("id tie breaker", ledger.largestFirst().get(0).id().equals("A"));
check("canonical export", ledger.exportText().equals("A;OTHER;2.00\nB;FOOD;2.00\nC;TRAVEL;1.00\n"));
List<Expense> before = ledger.snapshot();
try {
before.clear();
throw new AssertionError("mutable snapshot");
} catch (UnsupportedOperationException expected) {
check("store retained", ledger.snapshot().size() == 3);
}
ledger.importText("D;OTHER;0.01");
check("old snapshot stable", before.size() == 3);
check("new snapshot updated", ledger.snapshot().size() == 4);
check("missing lookup", ledger.find("missing").isEmpty());
}
static void testLimits() {
Ledger ledger = fresh();
check("empty accepted", ledger.importText("").equals(new Accepted(0, 0)));
check("blank accepted", ledger.importText(" \n").equals(new Accepted(0, 0)));
check("empty total", ledger.total().equals(new BigDecimal("0.00")));
check("null rejected", ledger.importText(null) instanceof Rejected);
check("total character limit", ledger.importText(" ".repeat(12001)) instanceof Rejected);
check("line limit", ledger.importText(" ".repeat(121)) instanceof Rejected);
check("100 physical lines", ledger.importText("\n".repeat(100)) instanceof Accepted);
check("101 physical lines", ledger.importText("\n".repeat(101)) instanceof Rejected);
check("limits unchanged", ledger.snapshot().isEmpty());
}
static void testRoundTrip() {
Ledger original = fresh();
Random random = new Random(29);
for (int index = 0; index < 20; index++) {
int amount = random.nextInt(100) + 1;
check("generated insertion " + index, original.importText("X" + index + ";OTHER;" + amount) instanceof Accepted);
}
Ledger restored = fresh();
check("export accepted", restored.importText(original.exportText()) instanceof Accepted);
check("round trip", restored.exportText().equals(original.exportText()));
check("total round trip", restored.total().equals(original.total()));
}
static void testCapacity() {
Ledger ledger = fresh();
for (int index = 0; index < 100; index++) {
check("capacity insertion", ledger.importText("C" + index + ";OTHER;1") instanceof Accepted);
}
String before = ledger.exportText();
check("capacity rejection", ledger.importText("EXTRA;OTHER;1") instanceof Rejected);
check("capacity unchanged", ledger.exportText().equals(before));
check("replay at capacity", ledger.importText("C0;OTHER;1").equals(new Accepted(0, 1)));
Ledger restored = fresh();
check("full export accepted", restored.importText(before) instanceof Accepted);
check("full round trip", restored.exportText().equals(before));
}
static void check(String name, boolean condition) {
if (!condition) {
throw new AssertionError(name);
}
}
}
Check your prediction
Text
All ledger checks passed
The marked entry is LedgerTest.java. Every source tab belongs to this workspace, but only that entry's main method starts execution. Each editor has its own independent source set. To test an edit, make it in the workspace whose entry is LedgerTest.java; edits in the application editor do not carry over automatically. Download expense-ledger.zip to keep both entries and your changes together locally.
Completion is saved in this browser only. It does not measure mastery.