Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 04 / Stage 1

Arrays and collections basics

Goal: Store many values in one place. Learn fixed-size arrays (1D and 2D), then the three ready-made collection tools you will reach for constantly — ArrayList, HashMap, HashSet — and how to pick between an array and an ArrayList. Time: ~6 hours

What you will learn

  • Declaring, filling and reading 1D arrays; the index loop and the for-each loop
  • 2D arrays: a grid of values, rows and columns, nested loops
  • Why a fixed-size array is not always enough, and what ArrayList<T> gives you instead
  • ArrayList<T> as a ready-made, resizable list: add, get, set, remove, contains, size
  • Autoboxing: how int and Integer convert back and forth automatically, and where that can go wrong
  • HashMap<K, V> as a ready-made key → value lookup: put, get, getOrDefault, containsKey, keySet, entrySet
  • HashSet<T> as a ready-made "no duplicates allowed" collection
  • How to choose: array vs. ArrayList vs. HashMap vs. HashSet

About the diamond <>: ArrayList<String>, HashMap<String, Integer> and similar are generic types — the word in angle brackets tells the collection what it holds. This part teaches you to read and copy that syntax as a recipe: "the type I'm storing goes inside <>." Why generics work the way they do, and how to write your own, is Stage 2 Part 9. For now: see <String>, think "a box that only holds Strings."

Topics in this part

Practice

Write each answer as its own solutions/exNN.java file with a class ExNN (matching the stage-wide convention — see solutions/ex01.java) holding only a public static void main(String[] args) — no other methods, no classes of your own yet (that starts Part 5 and Stage 2). Use the fixed sample data given in each exercise instead of Scanner, so your program prints the same thing every time you run it. HashMap/HashSet iteration order is not guaranteed by Java — the sample outputs show the order this ran in on this course's JDK (Corretto 21); if your order differs, that is expected, not a bug, as long as every value is correct.


📁 About examples/ filenames: most examples follow the stage-wide NN_descriptive_name.java convention (e.g. 01_array_basics.java). ArrayOutOfBounds.java and Autoboxing.java keep their original PascalCase names instead, because both are shown crashing with a real stack trace that names the file directly (at ArrayOutOfBounds.main(ArrayOutOfBounds.java:6), at Autoboxing.main(Autoboxing.java:34)) — renaming them would mean faking that trace instead of showing the real one.


Exercise 1: Ravi's tea-stall expenses

Scenario: Ravi runs a small tea stall in Pune and tracks what he spends each day for a week. What to do: In main():

  1. Make int[] expenses = {120, 95, 140, 80, 200, 150, 60}; (Monday to Sunday).
  2. Print "Days tracked: " + expenses.length.
  3. With an index loop, print "Day 1: ₹120", "Day 2: ₹95", ... (day numbers start at 1, not 0).
  4. With a for-each loop, add up all 7 values into total and print "Total: ₹845".
  5. With an index loop, find the highest expense and which day it fell on (1-based), and print "Highest: ₹200 on day 5".
  6. Compute the average as a double ((double) total / expenses.length) and print it with System.out.printf("Average: ₹%.2f%n", average);.

Sample output:

Days tracked: 7
Day 1: ₹120
Day 2: ₹95
Day 3: ₹140
Day 4: ₹80
Day 5: ₹200
Day 6: ₹150
Day 7: ₹60
Total: ₹845
Highest: ₹200 on day 5
Average: ₹120.71

💡 Hint: Casting (double) total before the division matters — total / expenses.length alone is int / int, which throws away the decimal part.


Exercise 2: Two shops, five days

Scenario: Two grocery shops in Pune compare their sales for Monday to Friday. What to do: In main():

  1. Make a 2D array int[][] sales with row 0 = Shop A's 5 daily sales {2000, 1800, 2200, 2500, 3000}, row 1 = Shop B's {1500, 1600, 1400, 1700, 2100}. Also make String[] shops = {"Shop A", "Shop B"}; and String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};.
  2. With nested loops, print each shop's weekly total: "Shop A total: ₹11500".
  3. With nested loops (outer over days, inner over shops this time), print each day's combined total: "Mon total: ₹3500".
  4. Find the single best (shop, day) combination — the one cell in the grid with the highest value — and print "Best day: Shop A on Fri with ₹3000".

Sample output:

Shop A total: ₹11500
Shop B total: ₹8300
Mon total: ₹3500
Tue total: ₹3400
Wed total: ₹3600
Thu total: ₹4200
Fri total: ₹5100
Best day: Shop A on Fri with ₹3000

💡 Hint: For step 4, start best = sales[0][0] and track bestRow/bestCol alongside it as you scan every cell, the same way you'd track a maximum in a 1D array.


Exercise 3: Asha's grocery list

Scenario: Asha keeps adjusting her grocery list before she leaves for the shop. What to do: In main():

  1. Make ArrayList<String> groceryList and add "Rice", "Dal", "Oil". Print it.
  2. Insert "Onions" at index 1. Print it.
  3. Remove "Oil" by value. Print it.
  4. Print whether the list contains("Dal") and whether it contains("Oil").
  5. Print the final list and its size().

Sample output:

[Rice, Dal, Oil]
[Rice, Onions, Dal, Oil]
[Rice, Onions, Dal]
true
false
Final list: [Rice, Onions, Dal]
Items: 3

💡 Hint: add(1, "Onions") inserts at index 1 and shifts everything from index 1 onward one place to the right — it does not overwrite index 1.


Exercise 4: Store price catalog

Scenario: A Pune store keeps its price catalog in a HashMap so any price can be looked up instantly. What to do: In main():

  1. Make HashMap<String, Integer> catalog and put "Rice" -> 1200, "Dal" -> 450, "Milk" -> 60, "Tea" -> 240.
  2. Print the price of "Sugar" using getOrDefault(..., 0) (it was never added).
  3. Update "Milk"'s price to 65 with another put, and print the new price with get.
  4. remove("Dal"), then print whether containsKey("Dal") is still true.
  5. Loop over catalog.values() to add up every remaining price into catalogValue, and print it, along with catalog.size().

Sample output:

Sugar price: 0
Updated Milk price: 65
Dal still in catalog: false
Total value of catalog: ₹1505
Items left in catalog: 3

💡 Hint: catalog.values() gives you a collection of just the values (no keys) — a plain for-each int price : catalog.values() works, no Integer boxing code needed from you.


Exercise 5: Delivery drop-off scans

Scenario: A delivery rider scans a phone number at every drop-off; the same customer can appear more than once in a day. What to do: In main():

  1. Make String[] scans = {"98001", "98002", "98001", "98003", "98002", "98001", "98004"};.
  2. Make an empty HashSet<String> deliveredTo.
  3. Loop over scans. For each phone number, call deliveredTo.add(phone): if it returns true, count it as a new customer; if false, count it as a repeat scan.
  4. Print the total number of scans, the new-customer count, and the repeat-scan count.
  5. Print whether deliveredTo.size() equals the new-customer count (it must).

Sample output:

Total scans: 7
Unique customers: 4
Repeat scans: 3
Set size matches unique count: true

💡 Hint: add()'s return value is the answer to "have I seen this phone number before?" — you don't need a separate contains() check first.


Exercise 6: Loyalty points and the Integer cache

Scenario: A store's loyalty program stores points earned per visit, and you want to see where comparing Integers with == is safe and where it silently lies. What to do: In main():

  1. Make ArrayList<Integer> pointsEarned and add 40, 25, 35. Sum them with a for-each int loop and print the total.
  2. Make Integer tierA = 50; and Integer tierB = 50;. Print tierA == tierB.
  3. Make Integer bigA = 1000; and Integer bigB = 1000;. Print bigA == bigB, then print bigA.equals(bigB).

Sample output:

Total points: 100
Same object (cached, small value): true
Same object (large value): false
Same value (equals, large value): true

💡 Hint: The cutoff is -128 to 127. 50 is inside it, 1000 is not — that is the entire reason step 2 and step 3's == results differ, even though both pairs hold equal values.


Exercise 7: The shopping cart

Scenario: This is the part's "you will build" — Asha's shopping cart, start to finish, using every tool from this part together. What to do: In main():

  1. Build a fixed catalog: String[] catalogNames = {"Rice", "Dal", "Milk", "Sugar", "Tea", "Oil"}; and double[] catalogPrices = {1200.0, 450.0, 60.0, 55.0, 240.0, 180.0};. Load them into a HashMap<String, Double> priceList.
  2. Build ArrayList<String> scans with, in this order: "Rice", "Milk", "Tea", "Milk", "Oil", "Rice" (two items get scanned twice).
  3. Make a HashSet<String> seen, an ArrayList<String> itemsInCart (unique items, in the order first scanned) and a HashMap<String, Integer> quantities. Loop over scans: if seen.add(item) is true, this is a new item — add it to itemsInCart and set its quantity to 1, and print "New item: " + item; if false, increase its quantity by one in quantities and print "Already in cart, quantity now <n>: " + item.
  4. Print a receipt: loop over itemsInCart, and for each, print name, quantity, unit price and line total (price * quantity), formatted as "Rice x2 @ ₹1200.00 = ₹2400.00" — use System.out.printf("%-6s x%d @ ₹%.2f = ₹%.2f%n", ...). Keep a running total.
  5. If total >= 1000.0, apply a flat ₹50 discount; otherwise the discount is 0. Print the subtotal, the discount and the final total, each to 2 decimal places, and the number of unique items.
  6. In a comment above each collection you declared, write one line explaining why you picked an array, an ArrayList, or a HashMap/HashSet for that piece of data (tie it to section 9's table).

Sample output:

New item: Rice
New item: Milk
New item: Tea
Already in cart, quantity now 2: Milk
New item: Oil
Already in cart, quantity now 2: Rice
--- Receipt ---
Rice   x2 @ ₹1200.00 = ₹2400.00
Milk   x2 @ ₹60.00 = ₹120.00
Tea    x1 @ ₹240.00 = ₹240.00
Oil    x1 @ ₹180.00 = ₹180.00
---------------
Subtotal: ₹2940.00
Discount: ₹50.00
Final total: ₹2890.00
Unique items: 4

💡 Hint: quantities.get(item) always has a value by the time you read it in step 4, because every item in itemsInCart was given an entry in quantities the first time it was seen in step 3 — no getOrDefault needed there, unlike the price lookup in step 4 (an item could, in theory, be scanned that isn't in the catalog).

Show the solutions for Part 4 (7 files)

solutions/ex01.java

class Ex01 {
    public static void main(String[] args) {
        int[] expenses = {120, 95, 140, 80, 200, 150, 60}; // Ravi's tea-stall spend, Mon..Sun

        System.out.println("Days tracked: " + expenses.length);

        for (int i = 0; i < expenses.length; i++) {
            System.out.println("Day " + (i + 1) + ": ₹" + expenses[i]);
        }

        int total = 0;
        for (int amount : expenses) {
            total += amount;
        }
        System.out.println("Total: ₹" + total);

        int highest = expenses[0];
        int highestDay = 1;
        for (int i = 1; i < expenses.length; i++) {
            if (expenses[i] > highest) {
                highest = expenses[i];
                highestDay = i + 1;
            }
        }
        System.out.println("Highest: ₹" + highest + " on day " + highestDay);

        double average = (double) total / expenses.length;
        System.out.printf("Average: ₹%.2f%n", average);
    }
}

solutions/ex02.java

class Ex02 {
    public static void main(String[] args) {
        // rows = shops, columns = days
        int[][] sales = {
            {2000, 1800, 2200, 2500, 3000}, // Shop A
            {1500, 1600, 1400, 1700, 2100}  // Shop B
        };
        String[] shops = {"Shop A", "Shop B"};
        String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // row totals: total sales per shop
        for (int row = 0; row < sales.length; row++) {
            int rowTotal = 0;
            for (int col = 0; col < sales[row].length; col++) {
                rowTotal += sales[row][col];
            }
            System.out.println(shops[row] + " total: ₹" + rowTotal);
        }

        // column totals: total sales per day
        for (int col = 0; col < days.length; col++) {
            int colTotal = 0;
            for (int row = 0; row < sales.length; row++) {
                colTotal += sales[row][col];
            }
            System.out.println(days[col] + " total: ₹" + colTotal);
        }

        // the single best (shop, day) cell
        int best = sales[0][0];
        int bestRow = 0;
        int bestCol = 0;
        for (int row = 0; row < sales.length; row++) {
            for (int col = 0; col < sales[row].length; col++) {
                if (sales[row][col] > best) {
                    best = sales[row][col];
                    bestRow = row;
                    bestCol = col;
                }
            }
        }
        System.out.println("Best day: " + shops[bestRow] + " on " + days[bestCol] + " with ₹" + best);
    }
}

solutions/ex03.java

import java.util.ArrayList;

class Ex03 {
    public static void main(String[] args) {
        ArrayList<String> groceryList = new ArrayList<>();
        groceryList.add("Rice");
        groceryList.add("Dal");
        groceryList.add("Oil");
        System.out.println(groceryList);

        groceryList.add(1, "Onions"); // insert at index 1
        System.out.println(groceryList);

        groceryList.remove("Oil"); // remove by value
        System.out.println(groceryList);

        System.out.println(groceryList.contains("Dal"));
        System.out.println(groceryList.contains("Oil"));

        System.out.println("Final list: " + groceryList);
        System.out.println("Items: " + groceryList.size());
    }
}

solutions/ex04.java

import java.util.HashMap;

class Ex04 {
    public static void main(String[] args) {
        HashMap<String, Integer> catalog = new HashMap<>();
        catalog.put("Rice", 1200);
        catalog.put("Dal", 450);
        catalog.put("Milk", 60);
        catalog.put("Tea", 240);

        System.out.println("Sugar price: " + catalog.getOrDefault("Sugar", 0));

        catalog.put("Milk", 65); // price update: same key, new value
        System.out.println("Updated Milk price: " + catalog.get("Milk"));

        catalog.remove("Dal");
        System.out.println("Dal still in catalog: " + catalog.containsKey("Dal"));

        int catalogValue = 0;
        for (int price : catalog.values()) {
            catalogValue += price;
        }
        System.out.println("Total value of catalog: ₹" + catalogValue);
        System.out.println("Items left in catalog: " + catalog.size());
    }
}

solutions/ex05.java

import java.util.HashSet;

class Ex05 {
    public static void main(String[] args) {
        // Phone numbers scanned at delivery drop-offs over one day; some repeat.
        String[] scans = {"98001", "98002", "98001", "98003", "98002", "98001", "98004"};

        HashSet<String> deliveredTo = new HashSet<>();
        int newCustomers = 0;
        int repeatScans = 0;

        for (String phone : scans) {
            if (deliveredTo.add(phone)) { // true only the first time this number is seen
                newCustomers++;
            } else {
                repeatScans++;
            }
        }

        System.out.println("Total scans: " + scans.length);
        System.out.println("Unique customers: " + newCustomers);
        System.out.println("Repeat scans: " + repeatScans);
        System.out.println("Set size matches unique count: " + (deliveredTo.size() == newCustomers));
    }
}

solutions/ex06.java

import java.util.ArrayList;

class Ex06 {
    public static void main(String[] args) {
        ArrayList<Integer> pointsEarned = new ArrayList<>();
        pointsEarned.add(40); // each add() autoboxes an int into an Integer
        pointsEarned.add(25);
        pointsEarned.add(35);

        int totalPoints = 0;
        for (int points : pointsEarned) { // each Integer auto-unboxes back to int
            totalPoints += points;
        }
        System.out.println("Total points: " + totalPoints);

        // Small loyalty-tier numbers (-128..127) are cached by Java.
        Integer tierA = 50;
        Integer tierB = 50;
        System.out.println("Same object (cached, small value): " + (tierA == tierB));

        // Bigger numbers are not cached: each boxing makes a new object.
        Integer bigA = 1000;
        Integer bigB = 1000;
        System.out.println("Same object (large value): " + (bigA == bigB));
        System.out.println("Same value (equals, large value): " + bigA.equals(bigB));
    }
}

solutions/ex07.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

class Ex07 {
    public static void main(String[] args) {
        // Catalog: a fixed, known-size set of items the store sells -> arrays.
        String[] catalogNames = {"Rice", "Dal", "Milk", "Sugar", "Tea", "Oil"};
        double[] catalogPrices = {1200.0, 450.0, 60.0, 55.0, 240.0, 180.0};

        // Built once, so price lookup is instant instead of scanning the arrays -> HashMap.
        HashMap<String, Double> priceList = new HashMap<>();
        for (int i = 0; i < catalogNames.length; i++) {
            priceList.put(catalogNames[i], catalogPrices[i]);
        }

        // Scans: grow one at a time as Asha shops, unknown final size -> ArrayList.
        ArrayList<String> scans = new ArrayList<>();
        scans.add("Rice");
        scans.add("Milk");
        scans.add("Tea");
        scans.add("Milk"); // scanned again
        scans.add("Oil");
        scans.add("Rice"); // scanned again

        HashSet<String> seen = new HashSet<>();             // "have I scanned this before?"
        ArrayList<String> itemsInCart = new ArrayList<>();  // unique items, first-scanned order
        HashMap<String, Integer> quantities = new HashMap<>(); // item -> how many times scanned

        for (String item : scans) {
            if (seen.add(item)) {
                itemsInCart.add(item);
                quantities.put(item, 1);
                System.out.println("New item: " + item);
            } else {
                quantities.put(item, quantities.get(item) + 1);
                System.out.println("Already in cart, quantity now " + quantities.get(item) + ": " + item);
            }
        }

        System.out.println("--- Receipt ---");
        double total = 0.0;
        for (String item : itemsInCart) {
            int qty = quantities.get(item);
            double price = priceList.getOrDefault(item, 0.0);
            double lineTotal = price * qty;
            total += lineTotal;
            System.out.printf("%-6s x%d @ ₹%.2f = ₹%.2f%n", item, qty, price, lineTotal);
        }

        double discount = (total >= 1000.0) ? 50.0 : 0.0;
        double finalTotal = total - discount;

        System.out.println("---------------");
        System.out.printf("Subtotal: ₹%.2f%n", total);
        System.out.printf("Discount: ₹%.2f%n", discount);
        System.out.printf("Final total: ₹%.2f%n", finalTotal);
        System.out.println("Unique items: " + itemsInCart.size());
    }
}

A crash you will meet: ArrayIndexOutOfBoundsException

Reading or writing a slot that doesn't exist crashes the program immediately. Exception handling (try/catch) is Part 6 — for now, just recognise this error and read it.

public class ArrayOutOfBounds {
    public static void main(String[] args) {
        int[] cart = {199, 299, 99};
        System.out.println("Cart has " + cart.length + " items");
        System.out.println("Reading index 5...");
        System.out.println(cart[5]); // there is no slot 5: valid indexes are 0, 1, 2
    }
}

Real, captured output and exit code (examples/ArrayOutOfBounds.java):

Cart has 3 items
Reading index 5...
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
	at ArrayOutOfBounds.main(ArrayOutOfBounds.java:6)
EXIT:1

Everything printed before the bad line still appears; the program then stops, and a non-zero exit code (1) tells the operating system "this run failed." The message already names the problem: index 5, length 3. Valid indexes for a length-3 array are 0, 1, 2 — always 0 to length - 1.

Common mistakes

Mistake Why it is wrong Fix
int[] prices = new int[5]; prices.add(10); Arrays have no add method; size is fixed forever Use ArrayList<Integer> if the size can change
arr[arr.length] Valid indexes are 0 to length - 1; length itself is one past the end Loop with i < arr.length, never i <= arr.length
ArrayList<int> nums = new ArrayList<>(); Collections hold objects, never primitives ArrayList<Integer> — the wrapper class, autoboxing handles the rest
Comparing Integer objects with == Only works by accident for cached values (-128..127); breaks for bigger numbers Use .equals(...) for wrapper objects, always
Unboxing a value that might be null (e.g. int x = map.get(missingKey);) get on a missing key returns null; unboxing null throws NullPointerException Use getOrDefault(key, fallback), or check containsKey first
map.get(key) with a key that was never put Returns null silently, not an error getOrDefault(...), or containsKey(...) before trusting the result
Relying on HashMap/HashSet iteration order The order is not part of the API's guarantee, even when it looks stable Don't depend on it; use a sorted/ordered structure if order matters (Stage 2)
list.remove(1) on an ArrayList<Integer> expecting to remove the value 1 remove(int) removes by index; you need remove(Integer.valueOf(1)) to remove by value Be explicit about index vs. value when the list holds Integers

Quick recap

  • Arrays (int[], String[][], ...) hold a fixed number of same-type slots; .length is a field, indexes run 0 to length - 1.
  • 2D arrays are arrays of arrays; walk them with nested loops, one for rows, one for columns.
  • ArrayList<T> is a resizable, ready-made list for when you don't know the final size up front; it holds objects only.
  • Autoboxing/unboxing convert int ↔ Integer (and the other primitive/wrapper pairs) automatically; compare wrapper objects with .equals(), and watch out for unboxing null.
  • HashMap<K, V> is a ready-made key → value lookup: put, get, getOrDefault, containsKey.
  • HashSet<T> is a ready-made "no duplicates" collection: add()'s boolean return doubles as the "have I seen this?" check.
  • HashMap/HashSet never promise an iteration order — treat any order you observe as incidental, not guaranteed.
  • Pick by shape of the problem: fixed size and known up front → array; grows over time → ArrayList; lookup by key → HashMap; no duplicates → HashSet.

Checklist

  • I can declare, fill and loop over a 1D array with both an index loop and a for-each loop.
  • I can declare and walk a 2D array with nested loops, computing row and column totals.
  • I can explain why an array can't grow, and when I'd reach for ArrayList instead.
  • I can add, get, set, remove and contains on an ArrayList<T>.
  • I can explain autoboxing/unboxing in one sentence, and why == is unsafe on Integer objects.
  • I can build a HashMap<K, V>, look values up safely with getOrDefault, and loop its entrySet().
  • I can build a HashSet<T> and use add()'s return value to detect duplicates.
  • I can justify, for a given piece of data, whether it belongs in an array, an ArrayList, a HashMap, or a HashSet.

Search the guide