Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
229: Building a Simple E-Commerce Cart System
We've spent a lot of time on the theory of collections and object-oriented design, but now it's time to glue it all together. We're going to build a small e-commerce cart system. Now, in a production environment, you'd be dealing with databases, API endpoints, and complex state management, but for this lesson, we're focusing on the core business logic: how to manage a set of items and calculate a total accurately.
Setting up the Data Models
First, we need a way to represent what we're actually selling. I'll start with a simple Product class. It doesn't need much—just a name and a price. I'm using double for the price here for simplicity, though if this were a real banking app, I'd be screaming at you to use BigDecimal to avoid floating-point errors.
public class Product {
private final String name;
private final double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() { return name; }
public double getPrice() { return price; }
}
Next, we need a CartItem. A common mistake I see is people putting the quantity directly into the Product class. Don't do that. A product's price doesn't change just because someone wants three of them. We need a wrapper that associates a product with a specific quantity for a specific user's session.
public class CartItem {
private final Product product;
private int quantity;
public CartItem(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public void addQuantity(int amount) { this.quantity += amount; }
public Product getProduct() { return product; }
public int getQuantity() { return quantity; }
}
Building the Cart Logic
Now for the main event: the ShoppingCart class. I'll use an ArrayList to hold our CartItem objects. My goal here is to create a method that lets us add products to the cart easily.
import java.util.*;
public class ShoppingCart {
private final List<CartItem> items = new ArrayList<>();
public void addItem(Product product, int quantity) {
items.add(new CartItem(product, quantity));
}
public List<CartItem> getItems() {
return items;
}
}
Fixing the Duplicate Item Bug
I just noticed a problem with the code I wrote above. If a user adds a "Mechanical Keyboard" to their cart, and then adds another "Mechanical Keyboard" later, my current addItem method just adds a second CartItem to the list. That's messy. When the user looks at their checkout page, they shouldn't see the same item listed three times; they should see one item with a quantity of three.
I need to pivot. Instead of blindly adding to the list, I should check if the product already exists in the cart first. If it does, I'll just bump up the quantity of the existing item.
public void addItem(Product product, int quantity) {
for (CartItem item : items) {
if (item.getProduct().equals(product)) {
item.addQuantity(quantity);
return; // Exit the method once we've updated the existing item
}
}
// If we get here, it's a new product for this cart
items.add(new CartItem(product, quantity));
}
Tallying Up the Total
Finally, we need to know how much the customer owes. I'll implement a calculateTotal method. I'm going to use a simple for-each loop here because it's readable and efficient for a small list of items.
public double calculateTotal() {
double total = 0;
for (CartItem item : items) {
total += item.getProduct().getPrice() * item.getQuantity();
}
return total;
}
And that's it. We've built a system that handles product definitions, manages quantities without duplicating entries, and calculates a final price. It's a small building block, but this pattern—separating the entity (Product) from the session state (CartItem)—is something you'll use constantly in professional Java development.
📋 Practical Task
Implementing a Percentage-Based Discount Voucher
Now it's your turn to extend the system. Your task is to modify the ShoppingCart class to support a discount voucher system.
- Add a private field to
ShoppingCartcalleddiscountPercentage(a double, e.g., 0.10 for 10%). - Create a method called
applyVoucher(double percentage)that updates this field. - Modify the
calculateTotal()method so that it applies the discount to the final sum before returning the value. For example, if the total is $100 and the discount is 0.10, the method should return $90.00. - Test your implementation by adding multiple items to a cart, applying a 20% discount, and printing the final total to the console.
There are no comments for now.