Java Employee Manager
A Java employee manager is an HR tool that keeps staff records with departments, job titles, monthly salaries, hire dates and reporting lines. It lets you hire people, give raises, move them between managers and produce payroll reports and an org chart. The project shows how to handle money correctly with BigDecimal, enforce business rules in one place, group data with streams and draw a hierarchy with recursion.
It follows the Java Chat Server and builds on the record-and-repository style of the Java Student Manager, with a stronger focus on money, rules and reports. You model an employee, build a directory that protects company rules, generate reports, store everything in CSV and finish with an interactive console, employees.jar. All examples were run on JDK 21.
Model an Employee With BigDecimal Salaries
Salaries are money, so they use BigDecimal instead of double. A double cannot store most decimal fractions exactly, which causes small but real errors in payroll. Departments are an enum, so only valid values can exist.
package com.gocourse.hr;
public enum Department {
ENGINEERING, SALES, HR, FINANCE;
/** Accepts "sales", "Sales", "SALES" or a unique prefix such as "eng". */
public static Department parse(String text) {
String value = text.strip().toUpperCase();
for (Department d : values()) {
if (!value.isEmpty() && d.name().startsWith(value)) return d;
}
throw new IllegalArgumentException("Unknown department '" + text + "'. Use engineering, sales, hr or finance");
}
}
package com.gocourse.hr;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.Period;
import java.util.regex.Pattern;
/** One employee. Salary is the monthly gross pay in rupees. managerId is null for the top of the company. */
public record Employee(int id, String name, String email, Department department, String title,
BigDecimal salary, LocalDate hireDate, Integer managerId) {
private static final Pattern EMAIL = Pattern.compile("[\\w.+-]+@[\\w-]+(\\.[\\w-]+)+");
public Employee {
if (name == null || name.isBlank()) throw new IllegalArgumentException("name is required");
if (email == null || !EMAIL.matcher(email).matches()) throw new IllegalArgumentException("invalid email: " + email);
if (salary == null || salary.signum() <= 0) throw new IllegalArgumentException("salary must be positive");
if (hireDate == null) throw new IllegalArgumentException("hire date is required");
if (managerId != null && managerId == id) throw new IllegalArgumentException("an employee cannot manage themselves");
name = name.strip();
email = email.strip().toLowerCase();
title = title == null ? "" : title.strip();
salary = salary.setScale(2, RoundingMode.HALF_EVEN); // always two decimal places
}
/** Returns a copy with the salary raised by a percentage, e.g. 7.5 for 7.5%. */
public Employee withRaise(BigDecimal percent) {
if (percent.signum() < 0 || percent.compareTo(new BigDecimal("50")) > 0) {
throw new IllegalArgumentException("raise must be between 0% and 50%");
}
BigDecimal factor = BigDecimal.ONE.add(percent.movePointLeft(2)); // 7.5 -> 1.075
return new Employee(id, name, email, department, title, salary.multiply(factor), hireDate, managerId);
}
public Employee withManager(Integer newManagerId) {
return new Employee(id, name, email, department, title, salary, hireDate, newManagerId);
}
public BigDecimal annualSalary() {
return salary.multiply(BigDecimal.valueOf(12));
}
public int yearsOfService(LocalDate today) {
return Period.between(hireDate, today).getYears();
}
}
package com.gocourse.hr;
import java.math.BigDecimal;
import java.time.LocalDate;
public class EmployeeDemo {
public static void main(String[] args) {
LocalDate today = LocalDate.of(2026, 11, 18);
Employee kavya = new Employee(2, " Kavya Iyer ", "Kavya.Iyer@gocosys.in", Department.parse("eng"),
"Tech Lead", new BigDecimal("185000"), LocalDate.of(2019, 6, 3), 1);
System.out.println(kavya);
System.out.println("Annual salary: " + kavya.annualSalary());
System.out.println("Years of service: " + kavya.yearsOfService(today));
Employee raised = kavya.withRaise(new BigDecimal("7.5"));
System.out.println("After 7.5% raise: " + raised.salary() + " (was " + kavya.salary() + ")");
System.out.println("After 3.33% raise: " + kavya.withRaise(new BigDecimal("3.33")).salary());
System.out.println("double math: " + 185000.0 * 1.0333);
System.out.println("BigDecimal math: " + new BigDecimal("185000").multiply(new BigDecimal("1.0333")));
String[][] bad = {
{"Arun", "arun@gocosys", "10000"},
{"Arun", "arun@gocosys.in", "0"},
};
for (String[] row : bad) {
try {
new Employee(9, row[0], row[1], Department.SALES, "", new BigDecimal(row[2]), today, null);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
try {
kavya.withRaise(new BigDecimal("80"));
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
try {
Department.parse("marketing");
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Employee[id=2, name=Kavya Iyer, email=kavya.iyer@gocosys.in, department=ENGINEERING, title=Tech Lead, salary=185000.00, hireDate=2019-06-03, managerId=1]
Annual salary: 2220000.00
Years of service: 7
After 7.5% raise: 198875.00 (was 185000.00)
After 3.33% raise: 191160.50
double math: 191160.50000000003
BigDecimal math: 191160.5000
Rejected: invalid email: arun@gocosys
Rejected: salary must be positive
Rejected: raise must be between 0% and 50%
Rejected: Unknown department 'marketing'. Use engineering, sales, hr or finance
How it works:
- The compact constructor cleans the input (trims the name, lowercases the email) and rejects bad values, so
Kavya.Iyer@gocosys.inis stored askavya.iyer@gocosys.in. setScale(2, RoundingMode.HALF_EVEN)gives every salary exactly two decimal places.HALF_EVEN(banker's rounding) avoids always rounding.5upwards, which keeps totals fair over many calculations.withRaiseturns7.5into the factor1.075withmovePointLeft(2)and multiplies. The result is then rounded to two places by the constructor.- The demo shows why
BigDecimalmatters:185000.0 * 1.0333withdoublegives191160.50000000003, whileBigDecimalgives the exact191160.50. More detail is in Java BigDecimal. Period.between(hireDate, today).getYears()counts complete years, so someone hired on 3 June 2019 has 7 years of service on 18 November 2026.managerIdis anInteger, not anint, so it can benullfor the person at the top of the company.
Protect Company Rules in an Employee Directory
The directory is the only place where employees are added, changed or removed, so it can enforce rules that involve more than one employee: emails must be unique, managers must exist, and nobody can end up managing their own manager.
package com.gocourse.hr;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
/** All employees, kept in id order, with the company's rules for adding, changing and removing them. */
public class EmployeeDirectory {
private final Map<Integer, Employee> byId = new LinkedHashMap<>();
private int nextId = 1;
public EmployeeDirectory(List<Employee> loaded) {
loaded.forEach(e -> store(e, false)); // a manager may appear later in the file...
for (Employee e : loaded) { // ...so check every manager once all are loaded
if (e.managerId() != null && !byId.containsKey(e.managerId())) {
throw new IllegalArgumentException(e.name() + " has unknown manager id " + e.managerId());
}
}
}
/** Hires a new employee and returns them with their new id. */
public Employee hire(String name, String email, Department department, String title,
BigDecimal salary, LocalDate hireDate, Integer managerId) {
return store(new Employee(nextId, name, email, department, title, salary, hireDate, managerId), true);
}
private Employee store(Employee e, boolean checkManager) {
boolean emailTaken = byId.values().stream()
.anyMatch(other -> other.id() != e.id() && other.email().equals(e.email()));
if (emailTaken) throw new IllegalArgumentException("email already used: " + e.email());
if (checkManager && e.managerId() != null && !byId.containsKey(e.managerId())) {
throw new IllegalArgumentException("no manager with id " + e.managerId());
}
byId.put(e.id(), e);
nextId = Math.max(nextId, e.id() + 1);
return e;
}
public Employee get(int id) {
return Optional.ofNullable(byId.get(id))
.orElseThrow(() -> new IllegalArgumentException("no employee with id " + id));
}
public Employee giveRaise(int id, BigDecimal percent) {
Employee raised = get(id).withRaise(percent);
byId.put(id, raised);
return raised;
}
/** Raises everyone in a department and returns the extra monthly cost. */
public BigDecimal giveDepartmentRaise(Department department, BigDecimal percent) {
BigDecimal extra = BigDecimal.ZERO;
for (Employee e : search(x -> x.department() == department)) {
Employee raised = e.withRaise(percent);
extra = extra.add(raised.salary().subtract(e.salary()));
byId.put(e.id(), raised);
}
return extra;
}
public void changeManager(int id, Integer newManagerId) {
Employee employee = get(id);
// walk up from the new manager: if we reach this employee, the change would create a loop
for (Integer m = newManagerId; m != null; m = get(m).managerId()) {
if (m == id) throw new IllegalArgumentException(employee.name() + " cannot report to their own team");
}
byId.put(id, employee.withManager(newManagerId));
}
/** Removes an employee. People who reported to them now report to their manager. */
public Employee remove(int id) {
Employee leaving = get(id);
for (Employee report : directReports(id)) {
byId.put(report.id(), report.withManager(leaving.managerId()));
}
byId.remove(id);
return leaving;
}
public List<Employee> directReports(int managerId) {
return search(e -> e.managerId() != null && e.managerId() == managerId);
}
public List<Employee> search(Predicate<Employee> filter) {
return byId.values().stream().filter(filter).toList();
}
public List<Employee> all() {
return List.copyOf(byId.values());
}
/** Ready-made filters. */
public static Predicate<Employee> nameContains(String text) {
return e -> e.name().toLowerCase().contains(text.toLowerCase());
}
public static Predicate<Employee> earnsAtLeast(BigDecimal monthly) {
return e -> e.salary().compareTo(monthly) >= 0;
}
public static final Comparator<Employee> BY_SALARY_DESC =
Comparator.comparing(Employee::salary).reversed().thenComparing(Employee::name);
}
The demos share one small company:
package com.gocourse.hr;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
/** A small company used by every demo. */
public class SampleData {
public static EmployeeDirectory company() {
EmployeeDirectory d = new EmployeeDirectory(List.of());
d.hire("Suresh Kumar", "suresh@gocosys.in", Department.ENGINEERING, "CTO", money("250000"), date("2016-04-01"), null);
d.hire("Kavya Iyer", "kavya@gocosys.in", Department.ENGINEERING, "Tech Lead", money("185000"), date("2019-06-03"), 1);
d.hire("Arun Prakash", "arun@gocosys.in", Department.ENGINEERING, "Developer", money("95000"), date("2022-01-10"), 2);
d.hire("Meena Raj", "meena@gocosys.in", Department.ENGINEERING, "Developer", money("88000"), date("2023-07-17"), 2);
d.hire("Divya Nair", "divya@gocosys.in", Department.SALES, "Sales Head", money("160000"), date("2018-09-24"), 1);
d.hire("Ravi Shankar", "ravi@gocosys.in", Department.SALES, "Account Manager", money("72000"), date("2024-02-05"), 5);
d.hire("Priya Menon", "priya@gocosys.in", Department.HR, "HR Manager", money("110000"), date("2020-11-02"), 1);
d.hire("Karthik Rao", "karthik@gocosys.in", Department.FINANCE, "Accountant", money("78000"), date("2021-03-15"), 1);
return d;
}
static BigDecimal money(String amount) {
return new BigDecimal(amount);
}
static LocalDate date(String iso) {
return LocalDate.parse(iso);
}
}
package com.gocourse.hr;
import java.math.BigDecimal;
import java.time.LocalDate;
public class DirectoryDemo {
static void print(String heading, java.util.List<Employee> list) {
System.out.println(heading);
list.forEach(e -> System.out.printf(" #%d %-13s %-12s %,12.2f%n", e.id(), e.name(), e.department(), e.salary()));
}
public static void main(String[] args) {
EmployeeDirectory d = SampleData.company();
print("Engineering, highest paid first:", d.search(e -> e.department() == Department.ENGINEERING)
.stream().sorted(EmployeeDirectory.BY_SALARY_DESC).toList());
print("Name contains 'ra':", d.search(EmployeeDirectory.nameContains("ra")));
print("Earns at least 150,000:", d.search(EmployeeDirectory.earnsAtLeast(new BigDecimal("150000"))));
print("Reports to Kavya (#2):", d.directReports(2));
System.out.println("Raise #3 by 10% -> " + d.giveRaise(3, new BigDecimal("10")).salary());
System.out.println("Sales raise 5% costs " + d.giveDepartmentRaise(Department.SALES, new BigDecimal("5")) + " more per month");
String[] attempts = {"duplicate email", "unknown manager", "loop", "missing id"};
for (String attempt : attempts) {
try {
switch (attempt) {
case "duplicate email" -> d.hire("A. Prakash", "ARUN@gocosys.in", Department.SALES, "", new BigDecimal("50000"), LocalDate.of(2026, 11, 18), null);
case "unknown manager" -> d.hire("New Joiner", "new@gocosys.in", Department.HR, "", new BigDecimal("50000"), LocalDate.of(2026, 11, 18), 42);
case "loop" -> d.changeManager(2, 3); // Kavya would report to Arun, who reports to Kavya
case "missing id" -> d.giveRaise(99, BigDecimal.ONE);
}
} catch (IllegalArgumentException e) {
System.out.println(attempt + " -> " + e.getMessage());
}
}
Employee leaving = d.remove(2);
System.out.println(leaving.name() + " left. Arun and Meena now report to #" + d.get(3).managerId() + " and #" + d.get(4).managerId());
}
}
Engineering, highest paid first:
#1 Suresh Kumar ENGINEERING 250,000.00
#2 Kavya Iyer ENGINEERING 185,000.00
#3 Arun Prakash ENGINEERING 95,000.00
#4 Meena Raj ENGINEERING 88,000.00
Name contains 'ra':
#3 Arun Prakash ENGINEERING 95,000.00
#4 Meena Raj ENGINEERING 88,000.00
#6 Ravi Shankar SALES 72,000.00
#8 Karthik Rao FINANCE 78,000.00
Earns at least 150,000:
#1 Suresh Kumar ENGINEERING 250,000.00
#2 Kavya Iyer ENGINEERING 185,000.00
#5 Divya Nair SALES 160,000.00
Reports to Kavya (#2):
#3 Arun Prakash ENGINEERING 95,000.00
#4 Meena Raj ENGINEERING 88,000.00
Raise #3 by 10% -> 104500.00
Sales raise 5% costs 11600.00 more per month
duplicate email -> email already used: arun@gocosys.in
unknown manager -> no manager with id 42
loop -> Kavya Iyer cannot report to their own team
missing id -> no employee with id 99
Kavya Iyer left. Arun and Meena now report to #1 and #1
How it works:
- A
LinkedHashMap<Integer, Employee>finds employees by id quickly and keeps them in the order they were added, which is id order. - The email check runs against every other employee. Emails are already lowercased by the record, so
ARUN@gocosys.inis caught as a duplicate. changeManagerwalks up the chain from the new manager: Arun (#3) reports to Kavya (#2), so making Kavya report to Arun would create a loop. The loop reaches id2and the change is refused.removereassigns direct reports to the leaving person's own manager before deleting them, so nobody is left pointing at a missing manager.giveDepartmentRaiseadds up the difference between new and old salaries, so HR can see the extra monthly cost (11600.00for a 5% raise in Sales).- The constructor loads saved employees in two passes. A manager might appear later in a file than their team, so manager ids are checked only after everyone is loaded.
Build Payroll Reports and an Org Chart
Reports are read-only views of the directory. The payroll report groups employees by department with Collectors.groupingBy, the org chart follows managerId links with recursion, and the anniversary list filters by hire month.
package com.gocourse.hr;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/** Read-only reports built from the directory with streams. */
public class Reports {
public record DepartmentPay(Department department, int headcount, BigDecimal monthlyTotal,
BigDecimal average, Employee topEarner) { }
/** One row per department, in enum order. */
public static List<DepartmentPay> payroll(EmployeeDirectory directory) {
Map<Department, List<Employee>> groups = directory.all().stream()
.collect(Collectors.groupingBy(Employee::department, () -> new EnumMap<>(Department.class),
Collectors.toList()));
List<DepartmentPay> rows = new ArrayList<>();
groups.forEach((department, staff) -> {
BigDecimal total = staff.stream().map(Employee::salary).reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal average = total.divide(BigDecimal.valueOf(staff.size()), 2, RoundingMode.HALF_EVEN);
Employee top = staff.stream().max(Comparator.comparing(Employee::salary)).orElseThrow();
rows.add(new DepartmentPay(department, staff.size(), total, average, top));
});
return rows;
}
public static String payrollTable(EmployeeDirectory directory) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("%-12s %5s %14s %12s %s%n", "Department", "Staff", "Monthly total", "Average", "Top earner"));
BigDecimal companyTotal = BigDecimal.ZERO;
int companyStaff = 0;
for (DepartmentPay row : payroll(directory)) {
sb.append(String.format("%-12s %5d %,14.2f %,12.2f %s%n", row.department(), row.headcount(),
row.monthlyTotal(), row.average(), row.topEarner().name()));
companyTotal = companyTotal.add(row.monthlyTotal());
companyStaff += row.headcount();
}
sb.append(String.format("%-12s %5d %,14.2f%n", "TOTAL", companyStaff, companyTotal));
sb.append(String.format("Annual payroll cost: %,.2f%n", companyTotal.multiply(BigDecimal.valueOf(12))));
return sb.toString();
}
/** Draws the reporting lines as a tree, starting from people who have no manager. */
public static List<String> orgChart(EmployeeDirectory directory) {
List<String> lines = new ArrayList<>();
for (Employee top : directory.search(e -> e.managerId() == null)) {
addBranch(directory, top, "", true, true, lines);
}
return lines;
}
private static void addBranch(EmployeeDirectory directory, Employee e, String indent, boolean last,
boolean root, List<String> lines) {
String label = e.name() + " (" + e.title() + ")";
lines.add(root ? label : indent + (last ? "└── " : "├── ") + label);
List<Employee> reports = directory.directReports(e.id());
String childIndent = root ? "" : indent + (last ? " " : "│ ");
for (int i = 0; i < reports.size(); i++) {
addBranch(directory, reports.get(i), childIndent, i == reports.size() - 1, false, lines);
}
}
/** Employees whose work anniversary falls in the given month, with the number of years. */
public static List<String> anniversaries(EmployeeDirectory directory, LocalDate today) {
return directory.search(e -> e.hireDate().getMonth() == today.getMonth() && e.hireDate().getYear() < today.getYear())
.stream()
.sorted(Comparator.comparing(e -> e.hireDate().getDayOfMonth()))
.map(e -> String.format("%s - %d years on %s", e.name(),
today.getYear() - e.hireDate().getYear(), e.hireDate().withYear(today.getYear())))
.toList();
}
}
package com.gocourse.hr;
import java.time.LocalDate;
public class ReportsDemo {
public static void main(String[] args) {
EmployeeDirectory directory = SampleData.company();
System.out.print(Reports.payrollTable(directory));
System.out.println();
Reports.orgChart(directory).forEach(System.out::println);
System.out.println();
LocalDate today = LocalDate.of(2026, 11, 18);
System.out.println("Work anniversaries in " + today.getMonth() + ":");
Reports.anniversaries(directory, today).forEach(line -> System.out.println(" " + line));
}
}
Department Staff Monthly total Average Top earner
ENGINEERING 4 618,000.00 154,500.00 Suresh Kumar
SALES 2 232,000.00 116,000.00 Divya Nair
HR 1 110,000.00 110,000.00 Priya Menon
FINANCE 1 78,000.00 78,000.00 Karthik Rao
TOTAL 8 1,038,000.00
Annual payroll cost: 12,456,000.00
Suresh Kumar (CTO)
├── Kavya Iyer (Tech Lead)
│ ├── Arun Prakash (Developer)
│ └── Meena Raj (Developer)
├── Divya Nair (Sales Head)
│ └── Ravi Shankar (Account Manager)
├── Priya Menon (HR Manager)
└── Karthik Rao (Accountant)
Work anniversaries in NOVEMBER:
Priya Menon - 6 years on 2026-11-02
How it works:
groupingBy(Employee::department, () -> new EnumMap<>(Department.class), toList())builds a map from each department to its staff. AnEnumMapkeeps the keys in enum order, so the table always lists Engineering first.BigDecimalhas nosum()in streams, so totals usereduce(BigDecimal.ZERO, BigDecimal::add). The average usesdivide(count, 2, HALF_EVEN), because dividing aBigDecimalwithout a scale throws an exception when the result has no exact decimal form.%,14.2fprints aBigDecimalwith thousands separators and two decimals, as in1,038,000.00.orgChartstarts from everyone without a manager and callsaddBranchfor each direct report. Each level adds"│ "or four spaces to the indent, the same tree-drawing technique as the Java File Manager.anniversarieskeeps employees hired in the current month in an earlier year, andwithYearmoves the hire date into this year to show the anniversary date.
Save Employees to CSV and Report Bad Rows
HR staff often edit the CSV file in a spreadsheet. Instead of failing on the first mistake, the loader collects every bad row with its line number and still loads the good ones.
package com.gocourse.hr;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
/** Saves employees as CSV and loads them back, collecting bad rows instead of stopping at the first one. */
public class CsvStore {
static final String HEADER = "id,name,email,department,title,salary,hire_date,manager_id";
public record LoadResult(List<Employee> employees, List<String> errors) { }
private final Path file;
public CsvStore(Path file) {
this.file = file;
}
public LoadResult load() throws IOException {
List<Employee> employees = new ArrayList<>();
List<String> errors = new ArrayList<>();
if (Files.notExists(file)) return new LoadResult(employees, errors);
List<String> lines = Files.readAllLines(file);
for (int i = 1; i < lines.size(); i++) { // line 0 is the header
String line = lines.get(i);
if (line.isBlank()) continue;
try {
employees.add(parse(splitCsv(line)));
} catch (RuntimeException e) { // bad number, bad date, failed validation...
errors.add("line " + (i + 1) + ": " + e.getMessage());
}
}
return new LoadResult(employees, errors);
}
public void save(List<Employee> employees) throws IOException {
List<String> lines = new ArrayList<>();
lines.add(HEADER);
for (Employee e : employees) {
lines.add(String.join(",", String.valueOf(e.id()), csv(e.name()), e.email(), e.department().name(),
csv(e.title()), e.salary().toPlainString(), e.hireDate().toString(),
e.managerId() == null ? "" : e.managerId().toString()));
}
Path temp = file.resolveSibling(file.getFileName() + ".tmp");
Files.write(temp, lines);
Files.move(temp, file, StandardCopyOption.REPLACE_EXISTING);
}
private static Employee parse(List<String> f) {
if (f.size() != 8) throw new IllegalArgumentException("expected 8 fields, found " + f.size());
return new Employee(Integer.parseInt(f.get(0)), f.get(1), f.get(2), Department.parse(f.get(3)), f.get(4),
money(f.get(5)), date(f.get(6)),
f.get(7).isBlank() ? null : Integer.valueOf(f.get(7)));
}
private static BigDecimal money(String text) {
try {
return new BigDecimal(text.strip());
} catch (NumberFormatException e) {
throw new IllegalArgumentException("salary is not a number: " + text);
}
}
private static LocalDate date(String text) {
try {
return LocalDate.parse(text.strip());
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("hire_date must be a real date in YYYY-MM-DD form: " + text);
}
}
/** Quotes a value that contains a comma or a quote: Lead, Payments -> "Lead, Payments". */
static String csv(String value) {
if (value.contains(",") || value.contains("\"")) return "\"" + value.replace("\"", "\"\"") + "\"";
return value;
}
/** Splits one CSV line, honouring quoted fields. */
static List<String> splitCsv(String line) {
List<String> fields = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean quoted = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (quoted) {
if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') {
current.append('"'); // "" inside quotes is one quote character
i++;
} else if (c == '"') {
quoted = false;
} else {
current.append(c);
}
} else if (c == '"') {
quoted = true;
} else if (c == ',') {
fields.add(current.toString());
current.setLength(0);
} else {
current.append(c);
}
}
fields.add(current.toString());
return fields;
}
}
package com.gocourse.hr;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
public class CsvDemo {
public static void main(String[] args) throws Exception {
Path file = Path.of("employees-demo.csv");
EmployeeDirectory directory = SampleData.company();
directory.hire("Nisha Thomas", "nisha@gocosys.in", Department.FINANCE, "Lead, Payments",
new BigDecimal("98000.50"), SampleData.date("2025-08-01"), 1);
CsvStore store = new CsvStore(file);
store.save(directory.all());
System.out.println("Saved file:");
Files.readAllLines(file).stream().limit(3).forEach(l -> System.out.println(" " + l));
System.out.println(" ...");
System.out.println(" " + Files.readAllLines(file).getLast());
// simulate hand edits with mistakes
Files.writeString(file, String.join("\n",
"",
"10,Bad Salary,bad@gocosys.in,SALES,Rep,ten thousand,2025-01-01,",
"11,Bad Date,date@gocosys.in,HR,Recruiter,50000,2025-13-01,",
"12,Bad Dept,dept@gocosys.in,LEGAL,Counsel,90000,2025-01-01,",
"13,Short Row,short@gocosys.in,HR",
""), java.nio.file.StandardOpenOption.APPEND);
CsvStore.LoadResult result = store.load();
System.out.println("\nLoaded " + result.employees().size() + " employees, " + result.errors().size() + " bad rows:");
result.errors().forEach(e -> System.out.println(" " + e));
EmployeeDirectory reloaded = new EmployeeDirectory(result.employees());
Employee nisha = reloaded.get(9);
System.out.println("\nRound trip: " + nisha.title() + " | " + nisha.salary() + " | manager #" + nisha.managerId());
Files.delete(file);
}
}
Saved file:
id,name,email,department,title,salary,hire_date,manager_id
1,Suresh Kumar,suresh@gocosys.in,ENGINEERING,CTO,250000.00,2016-04-01,
2,Kavya Iyer,kavya@gocosys.in,ENGINEERING,Tech Lead,185000.00,2019-06-03,1
...
9,Nisha Thomas,nisha@gocosys.in,FINANCE,"Lead, Payments",98000.50,2025-08-01,1
Loaded 9 employees, 4 bad rows:
line 12: salary is not a number: ten thousand
line 13: hire_date must be a real date in YYYY-MM-DD form: 2025-13-01
line 14: Unknown department 'LEGAL'. Use engineering, sales, hr or finance
line 15: expected 8 fields, found 4
Round trip: Lead, Payments | 98000.50 | manager #1
How it works:
toPlainString()writes98000.50instead of scientific notation such as9.80005E+4, and reading it back withnew BigDecimal(...)restores the exact value.- The title
Lead, Paymentscontains a comma, socsv()wraps it in quotes.splitCsvreads character by character and ignores commas inside quotes, so the round trip keeps the title intact. - Each row is parsed inside its own
tryblock. AnyRuntimeException(a bad number, an impossible date, an unknown department or a failed record check) becomes an entry inerrors, and the loop moves on. moneyanddateturn low-level parser errors into messages a person can act on, such assalary is not a number: ten thousand.- Line numbers count from 1 and include the header, so
line 12is the line a spreadsheet or text editor shows.
Build the Interactive Java Employee Manager Console
EmployeeApp loads the CSV file, then reads commands in a loop with an hr> prompt. Changes are saved automatically when you quit, or at any time with save.
package com.gocourse.hr;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.List;
/** Interactive HR console: java -jar employees.jar */
public class EmployeeApp {
private final EmployeeDirectory directory;
private final CsvStore store;
private final LocalDate today;
private boolean changed = false;
EmployeeApp(EmployeeDirectory directory, CsvStore store, LocalDate today) {
this.directory = directory;
this.store = store;
this.today = today;
}
public static void main(String[] args) throws IOException {
CsvStore store = new CsvStore(Path.of(System.getProperty("emp.file", "employees.csv")));
LocalDate today = LocalDate.parse(System.getProperty("emp.today", LocalDate.now().toString()));
CsvStore.LoadResult loaded = store.load();
loaded.errors().forEach(e -> System.out.println("warning: skipped " + e));
EmployeeDirectory directory = new EmployeeDirectory(loaded.employees());
System.out.println(directory.all().size() + " employees loaded. Type 'help' for commands.");
new EmployeeApp(directory, store, today).repl(new BufferedReader(new InputStreamReader(System.in)));
}
void repl(BufferedReader in) throws IOException {
while (true) {
System.out.print("hr> ");
String line = in.readLine();
if (line == null || line.strip().equals("quit")) break;
if (line.isBlank()) continue;
String[] words = line.strip().split("\\s+", 2);
String rest = words.length > 1 ? words[1] : "";
try {
run(words[0].toLowerCase(), rest);
} catch (IllegalArgumentException e) { // also NumberFormatException
System.out.println("error: " + e.getMessage());
}
}
if (changed) save();
System.out.println("bye");
}
private void run(String command, String rest) throws IOException {
switch (command) {
case "list" -> table(rest.isBlank() ? directory.all()
: directory.search(e -> e.department() == Department.parse(rest)));
case "find" -> table(directory.search(EmployeeDirectory.nameContains(rest)));
case "top" -> table(directory.all().stream().sorted(EmployeeDirectory.BY_SALARY_DESC)
.limit(rest.isBlank() ? 3 : Integer.parseInt(rest)).toList());
case "hire" -> hire(rest);
case "raise" -> raise(rest.split("\\s+"));
case "move" -> {
String[] ids = rest.split("\\s+");
directory.changeManager(Integer.parseInt(ids[0]), Integer.valueOf(ids[1]));
System.out.println(directory.get(Integer.parseInt(ids[0])).name() + " now reports to "
+ directory.get(Integer.parseInt(ids[1])).name());
changed = true;
}
case "fire" -> {
Employee gone = directory.remove(Integer.parseInt(rest));
System.out.println(gone.name() + " removed; their team now reports to #" + gone.managerId());
changed = true;
}
case "payroll" -> System.out.print(Reports.payrollTable(directory));
case "org" -> Reports.orgChart(directory).forEach(System.out::println);
case "anniversaries" -> Reports.anniversaries(directory, today).forEach(System.out::println);
case "save" -> save();
default -> System.out.println("""
list [department] find <text> top [n]
hire <name>;<email>;<department>;<title>;<salary>;<manager id>
raise <id> <percent> raise <department> <percent>
move <id> <manager id> fire <id>
payroll org anniversaries save quit""");
}
}
private void hire(String rest) {
String[] f = rest.split(";");
if (f.length != 6) throw new IllegalArgumentException("hire needs 6 values separated by ';'");
Employee e = directory.hire(f[0], f[1], Department.parse(f[2]), f[3], number(f[4], "salary"),
today, f[5].isBlank() ? null : Integer.valueOf(f[5].strip()));
System.out.println("Hired " + e.name() + " as #" + e.id());
changed = true;
}
private void raise(String[] args) {
if (args.length != 2) throw new IllegalArgumentException("usage: raise <id or department> <percent>");
BigDecimal percent = number(args[1], "percent");
if (args[0].chars().allMatch(Character::isDigit)) {
Employee e = directory.giveRaise(Integer.parseInt(args[0]), percent);
System.out.printf("%s now earns %,.2f a month%n", e.name(), e.salary());
} else {
Department d = Department.parse(args[0]);
System.out.printf("%s raised by %s%%: extra cost %,.2f a month%n", d, percent,
directory.giveDepartmentRaise(d, percent));
}
changed = true;
}
private static BigDecimal number(String text, String what) {
try {
return new BigDecimal(text.strip());
} catch (NumberFormatException e) {
throw new IllegalArgumentException(what + " must be a number, not '" + text.strip() + "'");
}
}
private void save() throws IOException {
store.save(directory.all());
changed = false;
System.out.println("saved " + directory.all().size() + " employees");
}
private void table(List<Employee> employees) {
for (Employee e : employees) {
System.out.printf("%3d %-14s %-12s %-16s %,12.2f %2d yrs%n", e.id(), e.name(), e.department(),
e.title(), e.salary(), e.yearsOfService(today));
}
if (employees.isEmpty()) System.out.println("(no employees)");
}
}
How it works:
hireuses;as its separator, because names and titles contain spaces, for examplehire Nisha Thomas;nisha@gocosys.in;finance;Payments Lead;98000;8. The hire date is alwaystoday.raisechecks whether the first argument is all digits. If it is, it is an employee id; otherwise it is parsed as a department.- The
changedflag records unsaved work, soquitsaves only when something was modified. - All rule violations are
IllegalArgumentExceptions from the directory, the record or the parsers, and onecatchinreplprints them aserror:lines without leaving the program. - Bad CSV rows found at start-up are printed as warnings, so HR knows what to fix, but the app still starts with the valid employees.
Real-World Example: Run a Month of HR Changes
employee-manager/
├── employees.csv
└── src/
└── com/
└── gocourse/
└── hr/
├── CsvStore.java
├── Department.java
├── Employee.java
├── EmployeeApp.java
├── EmployeeDirectory.java
└── Reports.java
The starting employees.csv holds the same eight employees as SampleData, saved with CsvStore.
cd employee-manager
javac -d out src/com/gocourse/hr/*.java
jar --create --file employees.jar --main-class com.gocourse.hr.EmployeeApp -C out .
# the date is fixed for this demo; leave -Demp.today out to use the real date
java -Demp.today=2026-11-18 -jar employees.jar
8 employees loaded. Type 'help' for commands.
hr> list engineering
1 Suresh Kumar ENGINEERING CTO 250,000.00 10 yrs
2 Kavya Iyer ENGINEERING Tech Lead 185,000.00 7 yrs
3 Arun Prakash ENGINEERING Developer 95,000.00 4 yrs
4 Meena Raj ENGINEERING Developer 88,000.00 3 yrs
hr> top 3
1 Suresh Kumar ENGINEERING CTO 250,000.00 10 yrs
2 Kavya Iyer ENGINEERING Tech Lead 185,000.00 7 yrs
5 Divya Nair SALES Sales Head 160,000.00 8 yrs
hr> hire Nisha Thomas;nisha@gocosys.in;finance;Payments Lead;98000;8
Hired Nisha Thomas as #9
hr> hire Copy Cat;kavya@gocosys.in;hr;Recruiter;60000;7
error: email already used: kavya@gocosys.in
hr> raise 4 12
Meena Raj now earns 98,560.00 a month
hr> raise sales 5
SALES raised by 5%: extra cost 11,600.00 a month
hr> raise 3 abc
error: percent must be a number, not 'abc'
hr> move 1 4
error: Suresh Kumar cannot report to their own team
hr> fire 2
Kavya Iyer removed; their team now reports to #1
hr> move 3 4
Arun Prakash now reports to Meena Raj
hr> org
Suresh Kumar (CTO)
├── Meena Raj (Developer)
│ └── Arun Prakash (Developer)
├── Divya Nair (Sales Head)
│ └── Ravi Shankar (Account Manager)
├── Priya Menon (HR Manager)
└── Karthik Rao (Accountant)
└── Nisha Thomas (Payments Lead)
hr> payroll
Department Staff Monthly total Average Top earner
ENGINEERING 3 443,560.00 147,853.33 Suresh Kumar
SALES 2 243,600.00 121,800.00 Divya Nair
HR 1 110,000.00 110,000.00 Priya Menon
FINANCE 2 176,000.00 88,000.00 Nisha Thomas
TOTAL 8 973,160.00
Annual payroll cost: 11,677,920.00
hr> anniversaries
Priya Menon - 6 years on 2026-11-02
hr> quit
saved 8 employees
bye
employees.csv after the session:
id,name,email,department,title,salary,hire_date,manager_id
1,Suresh Kumar,suresh@gocosys.in,ENGINEERING,CTO,250000.00,2016-04-01,
3,Arun Prakash,arun@gocosys.in,ENGINEERING,Developer,95000.00,2022-01-10,4
4,Meena Raj,meena@gocosys.in,ENGINEERING,Developer,98560.00,2023-07-17,1
5,Divya Nair,divya@gocosys.in,SALES,Sales Head,168000.00,2018-09-24,1
6,Ravi Shankar,ravi@gocosys.in,SALES,Account Manager,75600.00,2024-02-05,5
7,Priya Menon,priya@gocosys.in,HR,HR Manager,110000.00,2020-11-02,1
8,Karthik Rao,karthik@gocosys.in,FINANCE,Accountant,78000.00,2021-03-15,1
9,Nisha Thomas,nisha@gocosys.in,FINANCE,Payments Lead,98000.00,2026-11-18,8
How it works:
- Hiring with checks. Nisha joined Finance under Karthik (#8) with today's date and the next free id,
#9. A second hire reusing Kavya's email was refused before anything changed. - Exact raises. Meena's 12% raise produced exactly
98,560.00, and the Sales raise reported its monthly cost of11,600.00before HR saved it. - Safe reorganisation. Making the CTO report to Meena would have created a loop and was refused. When Kavya left, her team moved up to Suresh, and Arun was then placed under Meena, as the org chart shows.
- Up-to-date reports. The payroll table reflects every change: Engineering now has three people, and the annual payroll cost is
11,677,920.00. - Clean storage.
quitsaved the eight current employees in id order with exact salaries. Kavya's row is gone, Arun's manager is now4, and Nisha's hire date is2026-11-18.
The final project, the Java E-commerce API, combines these business rules with a REST API for products, carts and orders.