2. Exercises and Mini-Projects
Practice turns the short examples in this book into working habits. Start with small changes, then combine several chapters into one program.
2.1. Syntax practice
Change the
HelloWorldprogram so it prints your name and the current year.Create variables for a product name, price, quantity, and total cost.
Put a multi-line report template in a text block.
Write an
ifstatement that prints a letter grade from a numeric score.Rewrite the grade logic with a
switchexpression when the input is already a letter.Use a
forloop to print the first ten square numbers.
2.2. Object practice
Create a
Studentclass withfirstName,lastName, andgradefields.Add getters, setters, and a
getFullName()method.Override
toString()so a student prints clearly.Create an interface named
Reportablewith one method namedreport.Make
StudentimplementReportable.Rewrite
Studentas a record and decide which version is clearer.
2.3. Collection practice
Store five students in a
List.Find all students with grades greater than or equal to
90.Store unique course names in a
Set.Store student IDs and students in a
Map.Sort students by last name, then first name.
2.4. Streams practice
Convert a loop that sums numbers into a stream pipeline.
Use
filterto keep only passing grades.Use
mapto convert students into full names.Use
toList()to place filtered results into a new list.Use
groupingByto group students by letter grade.
2.5. Modern Java practice
Create a sealed interface named
Commandwith records namedAdd,Remove, andListAll.Write a
switchexpression that pattern matches each command.Use a record pattern to extract fields from one command.
Use
_for a caught exception that you intentionally ignore.Use
varin a lambda parameter when you want to annotate that parameter.Run five independent blocking tasks with virtual threads.
2.6. Mini-project: gradebook
Build a command-line gradebook.
Requirements:
Read students from a CSV file with columns for ID, first name, last name, and numeric grade.
Convert each row into a
Studentobject.Store students in a
Mapkeyed by ID.Print the class average, highest grade, and lowest grade.
Print students grouped by letter grade.
Write a summary report to a text file.
Add tests for the grade conversion logic.
This project uses classes, collections, streams, exceptions, file IO, and tests in one small program. Use records for immutable row data when that keeps the model simpler.
2.7. Mini-project: contact manager
Build a contact manager that stores names, email addresses, and phone numbers.
Requirements:
Add a contact.
Search contacts by last name.
Remove a contact by ID.
Save contacts to a CSV file.
Load contacts from a CSV file.
Validate that an email address is present before saving.
Add tests for searching and validation.
Use this project to practice object modeling. A Contact class or record is
clearer than passing several unrelated strings through the program.