Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised October 21, 2025)

Previous: Zoo

Coding Exercises: Lists of Objects

Items

  1. Write a class Item, representing a single item you can buy at a store. You should include:

    • private member variables for the name (String) and price (float) of the item
    • a constructor that sets these member variables
    • public accessor functions for the member variables
  2. Write a class ItemCalculator that calculates various things about a list of Item objects. Include these functions:

    • a function that takes an ArrayList of Item objects as input, and prints the names and prices of the items in the list (returns nothing)
    • a function that takes an ArrayList of Item objects as input, and returns
      the average price of the items
    • a function that takes an ArrayList of Item objects as input, and returns the name of the most expensive Item

Write unit tests for all ItemCalculator functions that return a value, to demonstrate that the functions are working correctly. These tests can be written in the ItemCalculator class, or in an external ItemCalculatorTest class.

Persons

  1. Write a class Person, including:

    • private member variables for the person’s name (String) and number of pets (int)
    • a constructor that sets these member variables
    • public accessor functions for the member variables
  2. Write a class PersonStats that calculates various things about lists of Person objects. Include three functions:

    • a function that takes an ArrayList of Person objects, and calculates the average number of pets
    • a function that takes an ArrayList of Person objects, and returns the name of the person with the most pets
    • a function that takes an ArrayList of Person objects, and returns an ArrayList of Person objects representing those people who have at least 2 pets.

Write unit tests for all PersonStats functions that return a value, to demonstrate that the functions are working correctly. These tests can be written in PersonStats, or in an external PersonStatsTest class.


Next: