How to Implement a Shopping Cart in Java Using a List

How to Implement a Shopping Cart in Java Using a List: A Step-by-Step Guide

In this guide, we’ll walk through how to implement a simple shopping cart using a List in Java. We’ll explore how to design a shopping cart, add items, remove items, and calculate the total price. The shopping cart will be implemented using Java’s powerful ArrayList class, which is a part of the Java Collections Framework.

What is a Shopping Cart?

A shopping cart is an online system that allows users to browse and store items that they intend to purchase later. In the real world, a shopping cart holds the selected products, quantities, and prices. In this tutorial, we’ll simulate the behavior of a shopping cart using Java.

Step 1: Define the Shopping Cart Item

Before we dive into the shopping cart implementation, let’s first define what an item will look like. Each item in the shopping cart will be an instance of an Item class.

Item Class Implementation:

        
public class Item {
    private String name;
    private double price;
    
    // Constructor to initialize item properties
    public Item(String name, double price) {
        this.name = name;
        this.price = price;
    }
    
    // Getter for name
    public String getName() {
        return name;
    }
    
    // Getter for price
    public double getPrice() {
        return price;
    }
    
    // Override the toString method for easy display of items
    @Override
    public String toString() {
        return name + " - $" + price;
    }
}
        
        

This simple class contains two properties: name and price. We also have a constructor to initialize these properties and getter methods to retrieve them. The toString() method allows easy printing of item details.

Step 2: Define the Shopping Cart

Now that we have our Item class, we can define the ShoppingCart class. The ShoppingCart class will maintain a list of items and provide methods to add, remove, and display items in the cart.

ShoppingCart Class Implementation:

        
import java.util.ArrayList;
import java.util.List;

public class ShoppingCart {
    private List cartItems; // List to store items in the cart
    
    // Constructor to initialize the cart
    public ShoppingCart() {
        cartItems = new ArrayList<>();
    }
    
    // Method to add an item to the cart
    public void addItem(Item item) {
        cartItems.add(item);
    }
    
    // Method to remove an item from the cart
    public void removeItem(Item item) {
        cartItems.remove(item);
    }
    
    // Method to get the total price of items in the cart
    public double getTotalPrice() {
        double total = 0;
        for (Item item : cartItems) {
            total += item.getPrice();
        }
        return total;
    }
    
    // Method to display the items in the cart
    public void displayCart() {
        if (cartItems.isEmpty()) {
            System.out.println("Your shopping cart is empty.");
        } else {
            System.out.println("Items in your shopping cart:");
            for (Item item : cartItems) {
                System.out.println(item);
            }
        }
    }
}
        
        

The ShoppingCart class contains several methods:

  • addItem(Item item) – Adds an item to the cart.
  • removeItem(Item item) – Removes an item from the cart.
  • getTotalPrice() – Calculates the total price of all items in the cart.
  • displayCart() – Displays the items currently in the cart.

Step 3: Using the Shopping Cart in Main

Now that we have our Item and ShoppingCart classes, let’s put everything together in the main method.

Example Code:

        
public class ShoppingCartApp {
    public static void main(String[] args) {
        // Create some items
        Item apple = new Item("Apple", 1.2);
        Item banana = new Item("Banana", 0.5);
        Item orange = new Item("Orange", 0.8);
        
        // Create a shopping cart
        ShoppingCart cart = new ShoppingCart();
        
        // Add items to the cart
        cart.addItem(apple);
        cart.addItem(banana);
        cart.addItem(orange);
        
        // Display the cart
        cart.displayCart();
        
        // Display the total price
        System.out.println("Total Price: $" + cart.getTotalPrice());
        
        // Remove an item from the cart
        cart.removeItem(banana);
        
        // Display the updated cart
        cart.displayCart();
        
        // Display the updated total price
        System.out.println("Updated Total Price: $" + cart.getTotalPrice());
    }
}
        
        

This code demonstrates how to create items, add them to the shopping cart, display the cart, and calculate the total price. It also shows how to remove an item and display the updated cart and total.

Step 4: Output Explanation

Running the ShoppingCartApp class will produce the following output:

        
Items in your shopping cart:
Apple - $1.2
Banana - $0.5
Orange - $0.8
Total Price: $2.5
Items in your shopping cart:
Apple - $1.2
Orange - $0.8
Updated Total Price: $2.0
        
        

Here’s what’s happening:

  • First, the cart displays all three items (Apple, Banana, and Orange) with their respective prices and the total price of $2.5.
  • Then, we remove the Banana from the cart, and the updated cart is displayed with the new total price of $2.0.

Step 5: Enhancements and Future Considerations

The basic shopping cart implementation we’ve built can be extended in several ways:

  • Item Quantity: Currently, each item is added only once to the cart. You could enhance the system to allow quantities of items (e.g., adding multiple Apples).
  • Discounts: You could implement methods to apply discounts to certain items or to the entire cart.
  • Save Cart State: In a real-world application, you would likely want to save the user’s cart to a database or a file.
  • Checkout Process: Add methods for processing checkout, applying taxes, and finalizing the order.

© 2025 Tech Interview Guide. All rights reserved.

Please follow and like us:

Leave a Comment