Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Project

Expense Tracker (CLI)

Start after Part 7

Stage 1

Goal: Build a real command-line app that records your daily spending, saves it to a text file, and prints tables and summaries. Time: ~6–7 hours · Uses: Parts 2–7 only (no classes of your own except one custom exception, no third-party packages, no build tool)

Project brief

Asha wants to know where her salary goes every month — rent, groceries, petrol, the odd food delivery. In this project you build a small terminal tool that answers that from the command line. This demo runs in a scratch folder on a copy of the 7 sample expenses (see ▶️ How to run below), so the new expense gets id #8:

$ java ExpenseTracker add 120 petrol 2026-11-20 "Bike top-up for Asha"
Added expense #8: ₹120.00 on petrol (2026-11-20)

$ java ExpenseTracker summary 2026-11
Summary for 2026-11
===================
Category            Amount   Share
----------------------------------
rent            ₹15,000.00   91.0%
...

Files

File What it is
README.md This brief and the step-by-step build guide
ExpenseTracker.java Complete reference solution (try building your own first!)
ExpenseException.java The one custom exception, raised for every "the user can fix this" error
sample_expenses.txt 7 sample expenses to test with
tests_manual.md Commands to try, with the exact expected output

How to run

Open a terminal in this folder (JDK 21, see ../../TOOLING.md). No build tool — just javac and java:

javac ExpenseTracker.java ExpenseException.java
java ExpenseTracker help
java ExpenseTracker add 250 food 2026-11-21 "Dinner delivery"
java ExpenseTracker list

java ExpenseTracker reads and writes expenses.txt in the current directory (there is no stdlib-only equivalent of Python's Path(__file__).parent without a build tool, so this program keeps it simple: wherever you run the command from is where the data file lives). The file is created on the first add.

To test safely, work in a separate scratch folder on a copy of the sample data, so your real expenses.txt is never touched:

mkdir -p /tmp/expense-test && cp sample_expenses.txt /tmp/expense-test/expenses.txt
cd /tmp/expense-test
java -cp /tmp/out ExpenseTracker list                 # /tmp/out = where you compiled to, e.g. javac -d /tmp/out ...

Features

Command What it does Example
add <amount> <category> [date] [note] Add an expense. date is YYYY-MM-DD or the word today (default: today). note needs quotes if it has spaces. add 1200 petrol 2026-10-12 "Full tank"
list [month|all] [category] Show expenses in a table with a total. Say all for the month slot to filter by category only. list 2026-11 rent
summary [month|all] Total, per-category totals with % share, biggest expense summary 2026-10
delete <id> Delete one expense by its id delete 3
help Show the command list help

Error handling: bad input prints a clear Error: ... line to stderr and the program exits with code 1. No command at all exits with code 2 (usage error), matching the convention 0 = OK, 1 = your mistake, 2 = how you called the program.

Bad input Message
add -50 food 2026-11-20 Error: Amount must be at least ₹0.01, got -50.
add abc food 2026-11-20 Error: Amount must be a number, got 'abc'.
add 100 food 2026-02-30 Error: Date must be a real date in YYYY-MM-DD format, got '2026-02-30'.
delete 99 Error: No expense with id 99.

Which Parts each feature uses

Feature Skills Part
double amounts, int ids, printf/String.format tables, ₹%,.2f primitives, casting, formatted output Part 2
Filters, loops, switch on the command if/else, for, continue, arrow switch Part 3
Five parallel ArrayLists (ids, dates, amounts, categories, notes) — one expense is index i across all five ArrayList<Integer>, ArrayList<String>, ArrayList<Double>, autoboxing Part 4
One job per static method, a Comparator lambda for sorting static methods, parameters/return, lambdas Part 5
ExpenseException, try/catch, exit codes checked exceptions, your own exception class, throws Part 6
expenses.txt load/save, Files.readAllLines/Files.write java.nio.file.Files, java.nio.file.Path, UTF_8 Part 7
add, list, summary, delete dispatch, raw String[] args reading main(String[] args) by hand (no library — Java has no stdlib argparse) New here

💡 The only class in this solution besides ExpenseTracker itself is ExpenseException, the custom checked exception from Part 6. Full OOP — a real Expense class or record — comes in Stage 2, Part 8.

Small new tools you will meet

Tool What it does Example
Files.exists(path) true if the file is there — a missing file just means "no expenses yet" Step 2
Files.readAllLines(path, UTF_8) read a whole text file as a List<String>, one element per line Step 2
Files.write(path, lines, UTF_8) write a List<String> back as a text file, one line each Step 2
`line.split("\ ", -1)` split a line on |, keeping empty trailing fields (-1)
String.format(Locale.US, "₹%,.2f", x) format a number with commas and 2 decimals, locale-independent Step 2/4
Double.isFinite(x) false for NaN/Infinity — Double.parseDouble("NaN") works but is not a real amount Step 3
Math.round(x * 100) / 100.0 round to paise (2 decimals) before validating Step 3
LocalDate.of(year, month, day) throws DateTimeException for a date that doesn't exist, like Feb 30 Step 3
list.sort((a, b) -> ...) sort with a comparator lambda, like Python's sorted(key=...) Step 4
map.merge(key, value, Double::sum) add to a running total in a Map, or start it if the key is new Step 5
arrow switch (case "add" -> handleAdd(...)) one line per case, no break needed Step 8

Build it step by step

Build in small steps. Compile and run after every step. Do not open ExpenseTracker.java until you have tried each step yourself.

Step 1: Decide the data format (Part 4)

What and why: Java has no dict/record yet (that's Part 8). So instead of "a list of expense objects," this project keeps five parallel lists, one per field, all lined up by index:

List<Integer> ids = new ArrayList<>();
List<String> dates = new ArrayList<>();
List<Double> amounts = new ArrayList<>();
List<String> categories = new ArrayList<>();
List<String> notes = new ArrayList<>();

Expense number 3 (say) is ids.get(3), dates.get(3), amounts.get(3), categories.get(3), notes.get(3) — five lists, one shared index. This is the honest "no classes yet" way to model a table of records.

Field Type Why
ids ArrayList<Integer> so you can delete one expense by id
dates ArrayList<String> YYYY-MM-DD sorts correctly as text; date.substring(0, 7) filters by month
amounts ArrayList<Double> rupees and paise
categories ArrayList<String> (lowercase) Petrol and petrol become the same category
notes ArrayList<String> optional description

Open sample_expenses.txt. Each line is one expense, fields separated by \|: id\|date\|amount\|category\|note.

🔍 Going deeper: why not one List<Expense> of some record type? Because record and class are Part 8, Stage 2. Parallel lists are genuinely how C and early Java code modeled tables before structs/objects were convenient — five ArrayLists that must always stay the same length is the honest cost of "no custom types yet." Rebuilding this with a record Expense(...) is the first thing Part 8 will ask you to do.

Step 2: Load and save the text file (Part 7)

What and why: your lists live only while the program runs. Saving them lets you add an expense today and see it tomorrow.

private static void loadExpenses(Path path, List<Integer> ids, List<String> dates,
        List<Double> amounts, List<String> categories, List<String> notes)
        throws IOException, ExpenseException {
    if (!Files.exists(path)) {
        return;                                   // no expenses yet
    }
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
    for (String line : lines) {
        String[] fields = line.split("\\|", -1);
        // ... validate and add to the five lists (see Step 9 for the checks)
    }
}

private static void saveExpenses(Path path, List<Integer> ids, List<String> dates,
        List<Double> amounts, List<String> categories, List<String> notes) throws IOException {
    List<String> lines = new ArrayList<>();
    for (int i = 0; i < ids.size(); i++) {
        lines.add(ids.get(i) + "|" + dates.get(i) + "|"
                + String.format(Locale.US, "%.2f", amounts.get(i)) + "|"
                + categories.get(i) + "|" + notes.get(i));
    }
    Files.write(path, lines, StandardCharsets.UTF_8);   // overwrites the whole file
}

✅ Test: loadExpenses(Path.of("sample_expenses.txt"), ...) then print ids.size() → 7.

🔍 Going deeper: Files.write with the default options truncates and rewrites the whole file every time — simple, and fine for a personal file with a few hundred lines. A real database never rewrites everything; it appends. Python's version in this course writes to a .tmp file and swaps it in with replace() (an atomic save) so a crash mid-write can't corrupt the file — that's a good stretch goal here too (Files.move with ATOMIC_MOVE), skipped in this solution to keep Step 2 to one idea.

Why \| and not a comma? Notes are free text and might contain commas ("Full tank, scooter"); | is rare enough in English sentences that a flat split works. This is a real limitation: a note containing | would break parsing. (Python's version sidesteps this entirely by saving JSON, which the JDK doesn't ship a parser for — see ../../DESIGN-NOTES.md.)

Step 3: Add an expense (Parts 2, 5, 6)

What and why: this is the main job of the app. Clean the user's text first, so the saved data is always neat.

  • New id = biggest id + 1 (loop and track a running max — no max() shortcut with a default like Python's, so write the loop yourself).
  • Amount: Double.parseDouble inside try/catch NumberFormatException. Round to paise first with Math.round(amount * 100) / 100.0, then check <= 0, so 0.001 (which rounds to 0.0) is refused.
  • Date: split on -, build three ints, call LocalDate.of(year, month, day) inside try/catch DateTimeException — that call throws for 2026-02-30 because February never has a 30th.
  • Category: text.strip().toLowerCase(). Raise ExpenseException if it is empty.
  • Append to all five lists at once, then save.

✅ Test: add one expense to a copy of the sample file and open expenses.txt. You should see id 8 on the last line.

🔍 Going deeper: why round before comparing to zero? 0.001 rounds to 0.00, which should be refused with a clear message, not silently saved as ₹0.00. Checking <= 0 before rounding would let 0.001 through as "positive," then save a useless 0.00 expense. Order matters with floating-point money — this is the same float-precision gotcha Python's version calls out, and the same reason real banks store paise as long, not double.

Step 4: List with filters (Parts 3, 4, 5)

What and why: you rarely want to see everything. Filters answer "What did I spend in November?"

  • Loop over every index 0..ids.size()-1. Use continue to skip ones that don't match month or category.
  • Month filter: dates.get(i).substring(0, 7).equals(month) — the first 7 characters of "2026-11-03" are "2026-11".
  • Collect the matching indexes into a List<Integer>, then sort that list with a comparator lambda: indexes.sort((a, b) -> ...), comparing dates.get(a) then, if equal, ids.get(a).
  • Print a table with String.format/printf: %-10s left-pads, %12s right-pads, matching Python's f-string alignment.
String line = String.format("%3d  %-10s  %-12s  %12s  %s",
        ids.get(i), dates.get(i), categories.get(i), formatMoney(amounts.get(i)), notes.get(i));

✅ Test: list 2026-11 shows 3 rows and Total ₹16,355.00.

Step 5: Summary (Parts 4, 5)

What and why: a list shows every rupee; a summary shows the big picture: which category eats most of the month.

  • Total: add up amounts.get(i) for every matching index.
  • Per category: a Map<String, Double>, totals.merge(category, amount, Double::sum) — adds to the running total, or starts it at amount if the category is new.
  • Sort the map's entries by value, descending, with another comparator lambda.
  • Biggest expense: loop and track the index with the largest amounts.get(i) (no max(key=...) shortcut — write the loop).

✅ Test: summary 2026-10 shows rent 73.6% and total ₹20,390.50.

Step 6: Delete by id (Parts 3, 6)

What and why: everyone types a wrong amount sometimes. Delete lets you fix it (then add it again).

  • Loop to find the index where ids.get(i) == id (autoboxed Integer unboxes fine against a primitive int with == — Part 4's autoboxing note).
  • If found: read out the values you need for the confirmation message before removing, then remove(index) from all five lists, in the same order, so they stay the same length.
  • If the loop ends without a match, throw new ExpenseException("No expense with id " + id + ".").
  • Save after deleting.

✅ Test: delete 6 works once. Running it again gives Error: No expense with id 6.

🔍 Going deeper: removing from five separate ArrayLists at the same index, one call each, is exactly the kind of bookkeeping bug a real Expense class/record would remove (one list.remove(index) instead of five). Keep that itch — Part 8 scratches it.

Step 7: Reading args by hand (new — Part 2 arrays, Part 3 switch)

What and why: Java ships no argparse. main(String[] args) is just an array of the words typed after java ExpenseTracker, so you read it the same way you'd read any array: by index and length.

public static void main(String[] args) {
    if (args.length == 0) { /* usage error, exit 2 */ }
    switch (args[0]) {
        case "add" -> handleAdd(args, ...);
        case "list" -> handleList(args, ...);
        case "summary" -> handleSummary(args, ...);
        case "delete" -> handleDelete(args, ...);
        default -> throw new ExpenseException("Unknown command '" + args[0] + "'. ...");
    }
}

Each handleX checks args.length itself (e.g. add needs 3 to 5 words) and throws ExpenseException with a one-line "Usage: ..." message on a bad count. There's no --note "text" flag syntax — arguments are purely positional: add <amount> <category> [date] [note]. To skip the month filter while still filtering by category, type the word all in the month's place: list all groceries.

✅ Test: java ExpenseTracker help and java ExpenseTracker (no args) — compare their exit codes with echo $?.

🔍 Going deeper: this is more typing per command than Python's named --note "..." flags, because there is no flag-parsing library in the Stage 1 toolbox. Stage 3 Part 15 (build tools and packaging) is also where a real CLI-parsing library would normally enter a Java project — until then, positional args[] is the honest, zero-dependency way to read a command line.

Step 8: Error handling (Part 6)

What and why: users type mistakes. A beginner app crashes with a stack trace; a good app prints one clear line and stops.

  1. One custom checked exception: class ExpenseException extends Exception.
  2. Small validation methods throw it with a clear message (amount, date, month, id, category — see Step 3).
  3. Loading the file also throws it for a broken line (wrong field count, bad id/amount, bad date) — so a hand-edited expenses.txt fails loudly instead of corrupting silently.
  4. main() catches it in one place, prints to System.err, and exits 1. A separate catch (IOException e) handles real file problems (permission denied, folder missing) with exit 1 too. Anything else (a real bug) is not caught — it should still crash loudly with a stack trace so you can fix it.

✅ Test: run every error case in tests_manual.md. Each should print Error: ... to stderr and exit 1 (or 2 for no command at all).


Stretch goals

  • 🟢 categories command: print all categories used so far.
  • 🟢 list --sort amount-equivalent: sort by amount instead of date (add a 3rd positional mode).
  • 🟡 edit <id> to change an expense's amount/category/note/date.
  • 🟡 Monthly budget: a budget.txt with one limit per category; summary warns when a category goes over.
  • 🟡 Atomic save: write to expenses.txt.tmp then Files.move(..., ATOMIC_MOVE, REPLACE_EXISTING) (see Step 2's "Going deeper").
  • 🟡 A --file <path> global option, parsed by hand before dispatching on the command.
  • 🔴 Pack the two .java files into a package (com.example.expensetracker) per Part 7's packaging lesson, and compile with -d.
  • 🔴 Indian number format: ₹1,50,000.00 instead of ₹150,000.00 (write your own grouping function — String.format can't do this directly).

Checklist

  • I can model a table of records as several parallel ArrayLists kept in sync by index.
  • I can read and write a plain text file with java.nio.file.Files and Path.
  • I can filter and sort data with loops and a comparator lambda.
  • I can group totals by category with a Map and merge.
  • I can print an aligned table with String.format/printf.
  • I can validate a date with LocalDate.of(...) and catch DateTimeException.
  • I can define my own checked exception and catch it in one place in main().
  • I can read args[] by hand and dispatch on it with an arrow switch.
  • All commands in tests_manual.md give the expected output and exit code.

Next

🎉 Stage 1 done! Go back to the roadmap and start Stage 2, Part 8: Object-oriented Java. Good idea: rebuild this tracker there with a real Expense class or record instead of five parallel lists.

Search the guide