Shopping Cart in Java: Solution, Explanation & Practice
Create a simple shopping cart system
Problem summary
Create Item and Cart classes. Cart should track items and calculate total.
Starter code
// Create Item class with name and price
// Create Cart class with:
// - addItem(Item item)
// - double getTotal()
// - int getItemCount()
public class Main {
public static void main(String[] args) {
// Add items and print total
// Print: Items: <count>, Total: lt;total>
}
}Expected output and test cases
- 3 items totaling 45.5
Items: 3, Total: $45.5
- Single item
Items: 1, Total: $100.0
- Empty cart
Items: 0, Total: $0.0
Hints
- Use ArrayList to store items
- Sum prices in getTotal()
- getItemCount() returns list size
Validated solution
Reveal Java solution
import java.util.ArrayList;
import java.util.List;
class Item { final double price; Item(double price) { this.price = price; } }
class Cart {
private final List<Item> items = new ArrayList<>();
void add(Item item) { items.add(item); }
double total() { double total = 0; for (Item item : items) total += item.price; return total; }
int count() { return items.size(); }
}
public class Main {
public static void main(String[] args) {
Cart cart = new Cart(); cart.add(new Item(10)); cart.add(new Item(15.5)); cart.add(new Item(20));
System.out.println("Items: " + cart.count() + ", Total: quot; + cart.total());
}
}How to approach the problem
A Cart composes a list of Item objects and calculates its own total. The item count is derived from the collection rather than maintained as a separate, error-prone counter.
Approach
- Represent one purchasable item.
- Add items to the cart-owned list.
- Derive the total by iterating over current items.
Time and space complexity
Time: O(n) for total; O(1) for add and count. Space: O(n).
Edge cases to test
- An empty cart has zero items and total zero.
- Currency rounding should be handled by BigDecimal in real checkout code.
Common mistakes
- Keeping a total field without updating it on every removal.
- Letting callers mutate the cart’s internal list.
Follow-up challenge
Add quantities and a remove-by-product operation without exposing the list.
Related OOP Basics exercises
- Practice Student Grade Calculator in Java
- Practice Bank Account Operations in Java
- Practice Circle Class in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler