Inventory Management in Java: Solution, Explanation & Practice
Create an inventory system with products
Problem summary
Create Product class with name, price, quantity. Implement addStock(), sell(), and getValue() methods.
Starter code
// Create Product class with:
// - String name, double price, int quantity
// - addStock(int amount), sell(int amount), getValue()
public class Main {
public static void main(String[] args) {
// Create product, add stock, sell some
// Print: Stock: <qty>, Value: lt;value>
}
}Expected output and test cases
- 10+0-2 = 8 @ $10
Stock: 8, Value: $80.0
- Sold all
Stock: 0, Value: $0.0
- Added stock
Stock: 15, Value: $75.0
Hints
- Track quantity as instance variable
- sell() decreases quantity
- getValue() = price * quantity
Validated solution
Reveal Java solution
class Product {
private final String name; private final double price; private int quantity;
Product(String name, double price, int quantity) { this.name = name; this.price = price; this.quantity = quantity; }
void addStock(int amount) { if (amount <= 0) throw new IllegalArgumentException(); quantity += amount; }
boolean sell(int amount) { if (amount <= 0 || amount > quantity) return false; quantity -= amount; return true; }
int quantity() { return quantity; }
double value() { return quantity * price; }
}
public class Main {
public static void main(String[] args) {
Product product = new Product("Notebook", 10, 10); product.sell(2);
System.out.println("Stock: " + product.quantity() + ", Value: quot; + product.value());
}
}How to approach the problem
The Product owns the rule that stock cannot become negative. Selling returns a boolean for an ordinary unavailable-stock outcome, while invalid quantities are rejected at the method boundary.
Approach
- Construct with name, unit price, and quantity.
- Validate stock changes.
- Derive inventory value from current quantity and price.
Time and space complexity
Time: O(1). Space: O(1).
Edge cases to test
- Selling more than available should not change stock.
- A real catalog would validate nonnegative price and initial quantity.
Common mistakes
- Exposing quantity as a public writable field.
- Reducing quantity below zero to represent backorders without a separate policy.
Follow-up challenge
Introduce reservations so concurrent orders cannot oversell inventory.
Related OOP Basics exercises
- Practice Temperature Converter in Java
- Practice Point Distance Calculator in Java
- Practice Rational Number Class in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler