Skip to content
Tutorials Center
My learning

Topics

Lesson 179 of 201 ยท Projects

Project: Employee Management System

Build an employee management system in Java - records, a repository interface, CRUD commands from input, stream reports and file persistence that survives a restart.

Almost every business program is, at its core, a list of records that people add to, look up, change and delete, plus reports on top. Developers call that CRUD: create, read, update, delete. In this project you'll build a small but properly designed employee management system: employees are validated records, storage hides behind an interface, a command shell drives everything from the Input box, streams produce the reports, and a file keeps the data between runs.

The most important idea in the project is the repository interface. The rest of the program never knows whether employees live in a Map or in a file. It talks to an EmployeeRepository, and you can swap the implementation without changing a single command. That's the same idea behind JDBC and Spring Data repositories in Advanced Java, at a scale you can read in one sitting.

You'll build it in five stages, each one a complete program you can run and change. The project uses records, enums, interfaces, Optional, TreeMap, streams with collectors, BigDecimal, dates and files.

What the system does

An employee has an id, a name, a department, a monthly salary and a hire date. The finished program understands these commands, one per input line:

Command Example What it does
add add Ana Souza | ENGINEERING | 5200 | 2021-03-15 Hire someone; the system assigns the id
list list salary Show everyone, sorted by id, name, salary or hired
show show 2 Show one employee
update update 2 salary 4400 Change name, dept or salary
delete delete 3 Remove an employee
raise raise SALES 5 Give a whole department (or all) a raise in percent
dept, top, search, stats top 3 Reports
restart restart Reload everything from the file, as if the program had been restarted

Fields in add are separated by | because names contain spaces. A broken command prints a clear message and the shell carries on with the next line; one bad line never ends the session.

Stage 1: an employee record that can't be invalid

The employee is a record: immutable, with equals, hashCode and toString for free. The compact constructor checks every field and normalizes what it can, so an invalid Employee object simply can't exist. Every later stage relies on that guarantee.

Money is a BigDecimal, never a double: 0.1 + 0.2 is not 0.3 in binary floating point, and salaries must add up to the cent. The constructor fixes the scale to two decimals, so 5200 and 5200.00 become the same value.

Java Stage 1: a validated Employee record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first line shows the record's generated toString, with the name already trimmed and the salary normalized to 5200.00. The raise gives 5382.00, and the original object still says 5200.00.

Things to notice:

  • Validation runs for every path into the type. The with... methods don't change the record (they can't: its fields are final); they build a new one through the canonical constructor, so a raise to a negative salary is rejected exactly like a bad new Employee(...). These "wither" methods are the standard way to "modify" immutable objects (see Immutable Classes).
  • The compact constructor can reassign its parameters. name = name.strip() and salary = salary.setScale(...) change the values before they are stored in the fields.
  • | is forbidden in names because it will be the field separator in commands and in the data file. Validating it here, in one place, makes both parsers simpler and safe.
  • Department.parse wraps valueOf to produce a helpful message listing the valid choices. valueOf's own message, No enum constant Department.LEGAL, is meant for programmers, not users.
  • Runnable lambdas let one loop try five different mistakes. Each lambda runs inside the same try, so each rejection is caught and printed.

Stage 2: a repository interface

Now storage. The program needs to save employees, find one by id, list them and delete them. Those four operations become an interface, and the first implementation keeps everything in a TreeMap keyed by id, so listings come out in id order without sorting.

Who decides the id? The repository does, like an auto-increment column in a database. A new employee is created with id 0, meaning "not saved yet", and save returns a copy with the real id. Saving an employee whose id already exists is an update. Ids are never reused: after deleting employee 1, the next hire still gets a fresh number, so an old reference such as "employee 1" in an email can never silently point to someone else.

Java Stage 2: the EmployeeRepository interface and a Map implementation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

To keep this stage short, the record's validation is condensed into one if; the full version from Stage 1 returns in the final program.

The interface decisions are the ones you'll see in real data-access code:

  • findById returns Optional<Employee>, not null. The return type itself tells callers that "nobody" is a normal outcome, and map(...).orElse(...) handles it without an if. See Optional.
  • deleteById returns boolean. Deleting an id that doesn't exist isn't an error worth an exception; the caller learns what happened and can tell the user.
  • Updating a missing id is an error. Silently inserting an employee with a made-up id 42 would break the id sequence, so save throws NoSuchElementException.
  • findAll returns List.copyOf(...), an unmodifiable snapshot. Returning the map's live values() would let callers change the repository behind its back, or see it change while they loop.
  • count and findByDepartment are default methods. They're written once in terms of findAll, so every implementation gets them for free. An implementation backed by a database could override them with a faster query.

Stage 3: commands from the Input box

With storage in place, a small command shell connects the user to the repository. Each input line is split into a command word and the rest. A switch dispatches the command, and every handler throws IllegalArgumentException (or a subclass such as NumberFormatException) when something is wrong. One try/catch around the dispatch turns all of those into one-line error messages.

The shell receives the repository through its constructor, typed as the interface. It has no idea which implementation it's talking to, and in Stage 5 it won't need a single change to work with a file.

Java Stage 3: a CRUD command shell

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output from top to bottom and match each line of input with its response. The LEGAL department and the salary lots are rejected without adding anything, so Dev and Eve never get ids. update 9, the second delete 1 and the unknown command fire each get a message, and the final list shows the two remaining employees.

How the shell stays robust:

  • split("\\s+", 2) splits on the first run of spaces only, so update 3 name Chloe Martin-Diaz keeps the full new name together. The limit argument is the difference between parsing a name and losing half of it.
  • Every error is an IllegalArgumentException or NoSuchElementException. LocalDate.parse throws DateTimeParseException, which is also an IllegalArgumentException subclass, so a date like 2024-13-01 is handled by the same catch. The multi-catch catch (IllegalArgumentException | NoSuchElementException e) covers the rest.
  • Validation lives in the record, not in the shell. The shell never checks "is the salary positive?"; it builds a record and lets the constructor decide. Adding a rule later means changing one place.
  • Parse helpers convert library errors into user messages. Integer.parseInt("x") says For input string: "x", which is fine for logs but cryptic for users, so parseId rethrows it with a clearer text.

Stage 4: reports with streams

Lists of records are what streams were made for. This stage leaves the shell aside and builds the reports a manager would ask for: payroll, headcount and average salary per department, the top earners, everyone hired per year, and who has been here longest.

Reports that depend on "today" (like years of service) use a fixed date here, so the output doesn't change from day to day. A real program would use LocalDate.now(), or better, a Clock passed in from outside so tests can still fix the date.

Java Stage 4: stream reports over the employees

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output starts with a payroll of 40750.00, names Greta, Chloe and Elif as the top earners, and lists departments in the enum's order. Marketing has no employees, so it doesn't appear at all: groupingBy only creates groups for values it actually sees.

The stream techniques, each with a reason:

  • reduce(BigDecimal.ZERO, BigDecimal::add) sums money exactly. There's no sum() for BigDecimal streams, because sum() exists only on the primitive streams (IntStream, DoubleStream), and using mapToDouble would bring floating-point errors back.
  • Comparator.comparing(...).reversed().thenComparing(...) sorts by salary descending and breaks ties by name. reversed() applies to the whole comparator built so far, which is why it comes before thenComparing; put it at the end and names would be sorted Z to A too. Comparable and Comparator covers this.
  • groupingBy with a map factory. The three-argument version lets you choose the map: an EnumMap keeps departments in declaration order, a TreeMap sorts years. The default HashMap would print groups in an unpredictable order. See Stream Collectors.
  • divide(..., 2, RoundingMode.HALF_UP) is required for BigDecimal averages. A plain divide throws ArithmeticException when the result has an endless decimal expansion, such as 10 / 3.
  • partitioningBy always returns both keys, true and false, even when one group is empty, which makes it safer than groupingBy for yes/no questions.
  • Period.between gives years and months the way people count them. ChronoUnit.DAYS.between would be the tool for an exact day count.

Stage 5: saving to a file

Data that disappears when the program ends isn't much of a management system. The final stage adds FileEmployeeRepository, a second implementation of the same interface. It keeps employees in memory for fast lookups, loads them from a text file when it starts, and rewrites the file after every change.

The file format is one employee per line, fields separated by |, with a header line naming the format version (so a future program can recognize old files) and a line that remembers the next id:

TEXT
# employees v1
# next-id 6
1|Ana Souza|ENGINEERING|5200.00|2021-03-15
2|Ben Okoro|SALES|4100.00|2019-07-01

Since the Employee record rejects | in names, a line always splits into exactly five fields. Each save writes a temporary file first and then moves it over the real one, so a crash in the middle of saving never leaves a half-written file (the technique from Files).

FileEmployeeRepository extends the in-memory version and adds persistence around it: save and deleteById call super and then write the file. Inheritance is fine here because the file repository really is an in-memory repository with one extra duty. To load employees with their stored ids and keep the id counter, the parent class gets three small protected methods (restore, setNextId and nextId) that only subclasses can call.

Our runner deletes files when the program ends, so the program creates its data file in a temporary directory and simulates a restart with the restart command: it throws the current repository away and builds a new one from the file. Everything still there after restart really came from disk. The file command prints the raw file so you can see exactly what was saved.

Java Stage 5: the complete system with file persistence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Follow the run: five hires, one update and one delete are each written to disk immediately. The file command shows the result, and after the first restart the four remaining employees come back from the file with their ids, salaries and dates intact. After the 5% raise and a new hire, the second restart proves those changes were saved too: Ana's 5200.00 is now 5460.00 and Chloe's 6100.00 is 6405.00. show 4 fails because Dev was deleted before the first restart, and he stays deleted.

Design points in the final version:

  • The shell didn't change to gain persistence. It still receives an EmployeeRepository. The only new shell code is the report commands (raise, dept, top, search, stats), which are stream pipelines like the ones in Stage 4.
  • The file stores # next-id. Without it, the loader would compute the next id as "highest id + 1". Delete the newest employee, restart, and the next hire would get the deleted person's id back, which is exactly what the in-memory version promised never to do.
  • raise collects the affected employees with toList() first, then saves them. Saving while streaming over findAll() would work here because findAll returns a copy, but collecting first makes the intent obvious, and it's the safe habit with live collections, where changing a map while iterating over it throws ConcurrentModificationException.
  • movePointLeft(2) turns 5 into 0.05 without any floating-point arithmetic, so the factor is exactly 1.05.
  • I/O errors become UncheckedIOException. The interface methods don't declare throws IOException (an in-memory store can't fail that way), so the file implementation wraps the checked exception, and the shell reports it as "Could not save" instead of crashing. Wrapping I/O failures like this is a common choice for repositories; see Exception Best Practices.
  • The loader is strict. A file with a wrong header or a line without five fields throws IllegalStateException instead of loading half the data and saving over the rest. When stored data is damaged, stopping loudly is safer than guessing.
  • Rewriting the whole file on every change is simple and fine for hundreds or thousands of employees. For millions, or for several programs writing at once, you need a database, which is where the JDBC lessons pick up.

Ideas to extend it

  • Undo. Keep a stack of previous versions of changed employees (records make this cheap: they're immutable) and add an undo command.
  • A real database. Write JdbcEmployeeRepository with the H2 in-memory database and plain JDBC (JDBC CRUD). The shell shouldn't change at all; that's the payoff of the interface.
  • Managers. Add an optional managerId field, refuse to delete someone who still manages people, and print the organization as a tree with recursion.
  • CSV import and export. Read a spreadsheet export with quoted fields, like in the Inventory Manager project.
  • Contract tests. Write one set of JUnit tests against EmployeeRepository and run it against both implementations. If both pass, they're interchangeable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the shell take an EmployeeRepository in its constructor instead of creating an InMemoryEmployeeRepository itself?

    The shell depends only on the interface. Stage 5 passes a FileEmployeeRepository and the shell code doesn't change at all.
  2. 2. What does "update 3 name Chloe Martin-Diaz".split("\\s+", 2) produce?

    The limit 2 means at most two parts, so the string is split only at the first run of spaces. The update handler then splits the rest with a limit of 3, which keeps the full name together.
  3. 3. Why does findAll() return List.copyOf(employees.values()) instead of the map's values() directly?

    values() is a live view of the map. Returning an unmodifiable copy protects the repository and gives callers a stable list to loop over.
  4. 4. What happens with Comparator.comparing(Employee::salary).thenComparing(Employee::name).reversed()?

    reversed() applies to everything built before it. To reverse only the salary order, call reversed() right after comparing(...) and then add thenComparing.
  5. 5. Why does the file repository write a temporary file and then move it over the real one?

    Writing in place destroys the old content before the new content is complete. Writing elsewhere and moving the finished file over the old one avoids that window.

Summary

  • An immutable Employee record validates and normalizes every field in its compact constructor, and with... methods "change" it by building validated copies.
  • Money is BigDecimal with a fixed scale: sum it with reduce(BigDecimal.ZERO, BigDecimal::add) and divide with an explicit rounding mode.
  • The EmployeeRepository interface hides storage: save inserts or updates and assigns ids, findById returns Optional, findAll returns an unmodifiable snapshot.
  • A command shell splits each line with a limit, dispatches with switch, and turns every IllegalArgumentException or NoSuchElementException into a one-line message.
  • Streams with sorted, limit, groupingBy (with EnumMap or TreeMap), partitioningBy and min produce the reports.
  • FileEmployeeRepository reuses the in-memory logic, loads a versioned text file at start and saves atomically after every change; because the shell only knows the interface, persistence needed no change elsewhere.

Next: Project: Snake Game, where you'll build a game model that moves, grows and collides, and render it as text frames and in a Swing window.