Skip to content
Java project #14Intermediate

Expense Tracker

Record expenses by date and category, set monthly budgets, get alerts, and analyse months, categories, top expenses and trends with streams and java.time.

Estimated time
~4 hours to build
Files
4 files · 347 lines
Technologies
Java 21, java.time (LocalDate, YearMonth), EnumMap, Streams / Collectors, Records

Introduction

Personal finance apps are mostly data analysis: group by month, sum by category, compare with a budget. This tracker does all of that with Collectors.groupingBy, EnumMap and YearMonth, and shows how much a few stream pipelines can replace.

Problem statement

Let the user add expenses (date, category, amount, note) and set monthly budgets per category. Warn when a category reaches 80% of its budget and when it goes over. Provide a monthly summary (totals per category against budgets, total, average per day using the real month length, biggest expense and its weekday), the top N expenses, totals and shares per category, and a month-by-month trend with percentage change. Reject invalid dates, unknown categories and non-positive amounts.

Objectives

  • Use YearMonth, LocalDate and DateTimeFormatter
  • Aggregate with groupingBy, summingLong and EnumMap
  • Implement threshold alerts
  • Present trends with bars and percentage changes

Features

  • Seven categories as an enum
  • Budgets with 80% and over-budget alerts
  • Monthly report, top N, category shares
  • Trend chart with month-on-month change

Concepts demonstrated

  • Aggregation
  • Date handling
  • Budget alerts
  • Data analysis with streams
  • Enum-keyed maps

System architecture

Expense is a record with a derived month(). Expenses live in a list and budgets in an EnumMap<Category, Long>. After each add, alertIfOverBudget sums that category's spending for the expense's month. month filters by YearMonth, groups by category into an EnumMap (preserving enum order) and uses lengthOfMonth() for the daily average. trend groups by month into a TreeMap so months print in order, and scales bars to the largest month.

Folder structure

TextProject tree
expense-tracker/
├── README.md
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

135 lines
Javasrc/Main.java
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* Expense Tracker — record expenses by date and category, set monthly budgets per category,
* and get monthly summaries, budget alerts, top expenses and spending trends, all computed
* with the Streams API and java.time.
*
* Commands:
* add YYYY-MM-DD CATEGORY AMOUNT NOTE... budget CATEGORY AMOUNT
* month YYYY-MM top N trend categories quit
*/
public class Main {
enum Category { FOOD, RENT, TRAVEL, BILLS, SHOPPING, HEALTH, OTHER }
record Expense(LocalDate date, Category category, long paise, String note) {
YearMonth month() { return YearMonth.from(date); }
}
static final List<Expense> expenses = new ArrayList<>();
static final Map<Category, Long> budgets = new EnumMap<>(Category.class);
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("=== Expense Tracker ===");
while (true) {
System.out.print("> ");
if (!in.hasNextLine()) break;
String line = in.nextLine().trim();
System.out.println();
String[] p = line.split("\\s+", 5);
try {
switch (p[0].toLowerCase()) {
case "add" -> {
LocalDate date = LocalDate.parse(p[1]);
if (date.isAfter(LocalDate.of(2026, 12, 31))) throw new IllegalArgumentException("date is in the future");
Expense e = new Expense(date, category(p[2]), paise(p[3]), p.length > 4 ? p[4] : "");
expenses.add(e);
System.out.printf("Added %s %s %s%n", e.date(), e.category(), rupees(e.paise()));
alertIfOverBudget(e.category(), e.month());
}
case "budget" -> {
Category c = category(p[1]);
budgets.put(c, paise(p[2]));
System.out.println("Monthly budget for " + c + ": " + rupees(budgets.get(c)));
}
case "month" -> month(YearMonth.parse(p[1]));
case "top" -> {
int n = Integer.parseInt(p[1]);
expenses.stream().sorted(Comparator.comparingLong(Expense::paise).reversed().thenComparing(Expense::date)).limit(n)
.forEach(e -> System.out.printf(" %s %-9s %12s %s%n", e.date(), e.category(), rupees(e.paise()), e.note()));
}
case "trend" -> trend();
case "categories" -> {
Map<Category, Long> totals = expenses.stream().collect(Collectors.groupingBy(Expense::category, () -> new EnumMap<>(Category.class), Collectors.summingLong(Expense::paise)));
long all = totals.values().stream().mapToLong(Long::longValue).sum();
totals.forEach((c, v) -> System.out.printf(" %-9s %12s %5.1f%%%n", c, rupees(v), 100.0 * v / all));
}
case "quit" -> { return; }
default -> System.out.println("Commands: add budget month top trend categories quit");
}
} catch (DateTimeParseException e) {
System.out.println("Error: dates are YYYY-MM-DD and months YYYY-MM");
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
System.out.println("Error: missing or invalid arguments");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
static Category category(String s) {
for (Category c : Category.values()) if (c.name().equalsIgnoreCase(s)) return c;
throw new IllegalArgumentException("unknown category '" + s + "'");
}
static long paise(String text) {
double v = Double.parseDouble(text);
if (v <= 0 || v > 10_000_000) throw new IllegalArgumentException("amount must be between 0 and 1 crore");
return Math.round(v * 100);
}
static String rupees(long p) { return String.format("Rs %,d.%02d", p / 100, p % 100); }
static long spent(Category c, YearMonth m) {
return expenses.stream().filter(e -> e.category() == c && e.month().equals(m)).mapToLong(Expense::paise).sum();
}
static void alertIfOverBudget(Category c, YearMonth m) {
Long budget = budgets.get(c);
if (budget == null) return;
long s = spent(c, m);
if (s > budget) System.out.printf(" !! %s is over budget for %s by %s%n", c, m, rupees(s - budget));
else if (s * 100 >= budget * 80) System.out.printf(" ! %s has used %d%% of its budget for %s%n", c, s * 100 / budget, m);
}
static void month(YearMonth m) {
List<Expense> list = expenses.stream().filter(e -> e.month().equals(m)).sorted(Comparator.comparing(Expense::date)).toList();
System.out.println(m.format(DateTimeFormatter.ofPattern("MMMM yyyy")).toUpperCase() + ": " + list.size() + " expense(s)");
if (list.isEmpty()) return;
Map<Category, Long> byCat = list.stream().collect(Collectors.groupingBy(Expense::category, () -> new EnumMap<>(Category.class), Collectors.summingLong(Expense::paise)));
for (var e : byCat.entrySet()) {
Long b = budgets.get(e.getKey());
String status = b == null ? "" : String.format(" budget %s %s", rupees(b), e.getValue() > b ? "OVER" : "ok");
System.out.printf(" %-9s %12s%s%n", e.getKey(), rupees(e.getValue()), status);
}
long total = list.stream().mapToLong(Expense::paise).sum();
int days = m.lengthOfMonth();
System.out.printf(" %-9s %12s (average %s per day over %d days)%n", "TOTAL", rupees(total), rupees(total / days), days);
Expense biggest = list.stream().max(Comparator.comparingLong(Expense::paise)).get();
System.out.println(" Biggest: " + biggest.note() + " on " + biggest.date() + " (" + biggest.date().getDayOfWeek() + ")");
}
static void trend() {
Map<YearMonth, Long> byMonth = expenses.stream().collect(Collectors.groupingBy(Expense::month, TreeMap::new, Collectors.summingLong(Expense::paise)));
long max = byMonth.values().stream().mapToLong(Long::longValue).max().orElse(1);
Long previous = null;
for (var e : byMonth.entrySet()) {
String change = previous == null ? "" : String.format(" %+.1f%%", 100.0 * (e.getValue() - previous) / previous);
System.out.printf(" %s %12s %-20s%s%n", e.getKey(), rupees(e.getValue()), "#".repeat((int) (20 * e.getValue() / max)), change);
previous = e.getValue();
}
}
}

What each file does

src/Main.java
The Category enum and Expense record, budget alerts, and the monthly, top, category and trend reports.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Expense Tracker ===
>
Monthly budget for FOOD: Rs 6,000.00
>
Monthly budget for SHOPPING: Rs 3,000.00
>
Added 2026-09-01 RENT Rs 15,000.00
>
Added 2026-09-03 FOOD Rs 1,250.50
>
Added 2026-09-12 TRAVEL Rs 640.00
>
Added 2026-09-20 FOOD Rs 2,100.00
>
Added 2026-09-28 BILLS Rs 1,830.00
>
Added 2026-10-01 RENT Rs 15,000.00
>
Added 2026-10-04 FOOD Rs 2,400.00
>
Added 2026-10-10 SHOPPING Rs 2,600.00
! SHOPPING has used 86% of its budget for 2026-10
>
Added 2026-10-15 FOOD Rs 2,600.00
! FOOD has used 83% of its budget for 2026-10
>
Added 2026-10-18 SHOPPING Rs 899.00
!! SHOPPING is over budget for 2026-10 by Rs 499.00
>
Added 2026-10-22 HEALTH Rs 750.00
>
Added 2026-10-25 FOOD Rs 1,300.00
!! FOOD is over budget for 2026-10 by Rs 300.00
>
Added 2026-11-02 RENT Rs 15,000.00
>
Added 2026-11-05 TRAVEL Rs 4,200.00
>
Error: dates are YYYY-MM-DD and months YYYY-MM
>
Error: unknown category 'fun'
>
Error: amount must be between 0 and 1 crore
>
OCTOBER 2026: 7 expense(s)
FOOD Rs 6,300.00 budget Rs 6,000.00 OVER
RENT Rs 15,000.00
SHOPPING Rs 3,499.00 budget Rs 3,000.00 OVER
HEALTH Rs 750.00
TOTAL Rs 25,549.00 (average Rs 824.16 per day over 31 days)
Biggest: October rent on 2026-10-01 (THURSDAY)
>
NOVEMBER 2026: 2 expense(s)
RENT Rs 15,000.00
TRAVEL Rs 4,200.00
TOTAL Rs 19,200.00 (average Rs 640.00 per day over 30 days)
Biggest: November rent on 2026-11-02 (MONDAY)
>
2026-09-01 RENT Rs 15,000.00 September rent
2026-10-01 RENT Rs 15,000.00 October rent
2026-11-02 RENT Rs 15,000.00 November rent
>
FOOD Rs 9,650.50 14.7%
RENT Rs 45,000.00 68.6%
TRAVEL Rs 4,840.00 7.4%
BILLS Rs 1,830.00 2.8%
SHOPPING Rs 3,499.00 5.3%
HEALTH Rs 750.00 1.1%
>
2026-09 Rs 20,820.50 ################
2026-10 Rs 25,549.00 #################### +22.7%
2026-11 Rs 19,200.00 ############### -24.9%
>
Input
budget food 6000
budget shopping 3000
add 2026-09-01 rent 15000 September rent
add 2026-09-03 food 1250.50 Groceries
add 2026-09-12 travel 640 Metro card
add 2026-09-20 food 2100 Restaurant
add 2026-09-28 bills 1830 Electricity
add 2026-10-01 rent 15000 October rent
add 2026-10-04 food 2400 Groceries
add 2026-10-10 shopping 2600 Shoes
add 2026-10-15 food 2600 Birthday dinner
add 2026-10-18 shopping 899 T-shirt
add 2026-10-22 health 750 Pharmacy
add 2026-10-25 food 1300 Groceries
add 2026-11-02 rent 15000 November rent
add 2026-11-05 travel 4200 Train tickets
add 2026-11-31 food 100 Bad date
add 2026-11-08 fun 500 Movies
add 2026-11-09 food -20 Refund
month 2026-10
month 2026-11
top 3
categories
trend
quit

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • October food spending reaches 83% after the birthday dinner and goes over budget (₹6,300 vs ₹6,000) after the last groceries.
  • 2026-11-31 is rejected as an invalid date.
  • The trend shows October up 22.7% on September and November down 24.9%.

Common errors

Months appear in random order

Group into a TreeMap (pass TreeMap::new to groupingBy) so YearMonth keys are sorted.

Average per day is wrong for February

Use YearMonth.lengthOfMonth() instead of assuming 30 days.

Possible improvements

  • Import bank statements from CSV
  • Support recurring expenses
  • Save data to a JSON file

Additional challenges

  1. 1Forecast next month's spending from the last three months.
  2. 2Add income and show monthly savings.
  3. 3Show spending by day of week.

Built and tested it yourself? Mark it to update your dashboard.