Build a Contact Book with Java HashMaps

Build a console contact book using Java HashMaps for O(1) lookups.

Introduction

30 Second Summary

Think about how you look up a contact on your phone. You type a name and the number appears instantly. You never scroll through every single entry to find someone.

In this project, you will build a contact book application in Java that stores names and phone numbers. You'll use a HashMap to power instant lookups by name, just like your phone does.

What You'll Build

A console-based Contact Book application where you can add, look up, update, delete, and list contacts through an interactive menu.

By the end of this project, you'll have:

  • A working ContactBook.java file containing a fully functional HashMap-powered contact manager.
  • Hands-on experience with all core HashMap operations: put, get, remove, containsKey, keySet, and entrySet.
  • A menu-driven console app that demonstrates why HashMaps exist: instant lookups by name instead of searching through a list.
  • Secret Mission: Add a reverse lookup feature that finds a contact name by phone number.

Are there any prerequisites?

You should be comfortable with basic Java syntax: variables, methods, if/else statements, loops, and System.out.println(). No prior experience with collections is needed.

Before We Start

Before We Start...

Create Your Project and First HashMap

Every contact book works the same way at its core: you type a name, and the app gives you back a phone number. HashMap is the Java data structure built for exactly this kind of name-to-value lookup.

In this step, you will create a new Java project in VS Code, declare your first HashMap, and populate it with contacts. By the end, you will see your HashMap printed in the terminal.

In this step, get ready to:
  • Create a Java project in VS Code with no build tools.
  • Write your first HashMap and populate it with contacts.
  • Run the program and see your contacts printed in the terminal.
Create a new Java project

VS Code's Java extensions include a project wizard that scaffolds a folder structure for you. This saves you from manually creating directories and configuration files.

  • Press Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows) to open the Command Palette.
  • Type Java: Create Java Project and select it from the dropdown.
  • Select No build tools from the project type list.
  • Choose a folder location on your computer where you want the project saved (your Desktop is a good choice).
  • Type ContactBook as the project name and press Enter.

VS Code creates the project and opens it automatically. You will see a src folder in the Explorer sidebar with a sample App.java file.

What did that just create?

The wizard created a ContactBook folder containing a src folder (where your Java source files live) and a lib folder (for external libraries, which you will not need in this project).

Don't see Java: Create Java Project?

This command comes from the Extension Pack for Java. Make sure you have it installed by pressing Ctrl+Shift+X to open the Extensions view and searching for vscjava.vscode-java-pack.

help me troubleshoot the Java: Create Java Project command

Create the ContactBook class

The sample App.java file is a placeholder you do not need. You will replace it with your own class.

  • In the Explorer sidebar, right-click App.java inside the src folder and select Delete.
  • Right-click the src folder and select New File.
  • Name the file ContactBook.java and press Enter.
  • Paste the following code into ContactBook.java:
import java.util.HashMap;

public class ContactBook {
    public static void main(String[] args) {
        // Create a HashMap that maps names (keys) to phone numbers (values)
        HashMap<String, String> contacts = new HashMap<>();
    }
}

What does this code do?

import java.util.HashMap loads Java's HashMap class so you can use it in your code.

HashMap<String, String> declares a HashMap where both the key (contact name) and the value (phone number) are Strings. The <String, String> part is called a type parameter. It tells Java what types of data are allowed in the map.

new HashMap<>() creates an empty HashMap in memory, ready for you to fill with contacts.

  • Save ContactBook.java.
  • You will not see any output yet because the program does not print anything. The next substep adds contacts and prints them.

Seeing red squiggly lines in the editor?

Make sure your filename is exactly ContactBook.java with a capital C and capital B. The filename must match the class name ContactBook in your code. Java requires this.

help me fix red underlines in my ContactBook.java file

Add contacts with put() and run

The put() method is how you add entries to a HashMap. Each call maps a key (the name) to a value (the phone number).

  • In ContactBook.java, find the line HashMap<String, String> contacts = new HashMap<>(); and add the following code below it:
contacts.put("Alice", "555-0101");
contacts.put("Bob", "555-0102");
contacts.put("Charlie", "555-0103");

// Print the entire HashMap and how many entries it contains
System.out.println("All contacts: " + contacts);
System.out.println("Number of contacts: " + contacts.size());

What does this code do?

Each contacts.put("Alice", "555-0101") call stores a name-to-number mapping inside the HashMap. If you call put() with a key that already exists, it replaces the old value.

contacts.size() returns the number of key-value pairs currently stored. Printing the HashMap itself shows all entries in curly braces, but the order may not match your insertion order.

  • Save ContactBook.java.
  • Click the Run button that appears above public static void main (or press F5).
  • In the terminal panel at the bottom, you should see output like:
All contacts: {Bob=555-0102, Charlie=555-0103, Alice=555-0101}
Number of contacts: 3

Why is the order different?

HashMap does not guarantee iteration order. Your names might print in a different sequence than you added them. This is normal. HashMap prioritizes fast lookups over preserving insertion order.

Not seeing any output in the terminal?

Make sure you clicked the Run text above the main method, not above the class declaration. If the terminal shows an error about the file not being found, confirm that your file is saved and is inside the src folder.

help me run my ContactBook.java program in VS Code

✔️ Awesome, I've got everything!

Great. Make sure you have saved ContactBook.java and that your terminal shows three contacts printed.

ⓧ I'd like to double check the full code

Here is the complete ContactBook.java at the end of this step:

import java.util.HashMap;

public class ContactBook {
    public static void main(String[] args) {
        HashMap<String, String> contacts = new HashMap<>();

        contacts.put("Alice", "555-0101");
        contacts.put("Bob", "555-0102");
        contacts.put("Charlie", "555-0103");

        System.out.println("All contacts: " + contacts);
        System.out.println("Number of contacts: " + contacts.size());
    }
}

You have a working HashMap with three contacts stored inside it. Next up, you will learn how to retrieve specific contacts by name and handle the case where a contact does not exist.

Retrieve and Check Contacts

Your HashMap is loaded with three contacts. Now the real question is: how do you get information back out?

In this step, you'll retrieve contacts by name, handle the case where a name doesn't exist, and update a contact's phone number.

In this step, get ready to:
  • Look up contacts by name using get().
  • Check if a contact exists before acting on it.
  • Update an existing contact's phone number.
Look up contacts with get()

The get() method retrieves a value by its key. If the key doesn't exist in the HashMap, it returns null.

  • In ContactBook.java, find the line that says System.out.println("Number of contacts: " + contacts.size());.
  • Copy the following code below it:
// Look up a contact that exists
String aliceNumber = contacts.get("Alice");
System.out.println("Alice's number: " + aliceNumber);

// Look up a contact that does NOT exist
String unknownNumber = contacts.get("Dave");
System.out.println("Dave's number: " + unknownNumber);

What does this code do?

contacts.get("Alice") looks up the key "Alice" and returns her phone number. This is the O(1) instant lookup that makes HashMaps so powerful.

contacts.get("Dave") tries to find a key that doesn't exist. Instead of crashing, HashMap returns null to signal "nothing here."

  • Save ContactBook.java and click the Run button above main (or press F5).
  • In the terminal output, you should see Alice's number: 555-0101 and Dave's number: null.

Seeing a compilation error?

  • Make sure the new code is inside the main method's curly braces, after the existing println statements.
  • Check that each line ends with a semicolon.
  • help me fix a compilation error in my ContactBook.java
Use containsKey() and getOrDefault()

Getting null back from a missing key can cause problems if your code tries to use that value. Java gives you two ways to handle this safely.

  • Add the following code below the Dave's number println line:
// Check if a key exists before using it
if (contacts.containsKey("Bob")) {
    System.out.println("Bob is in our contacts!");
}

// Provide a fallback value instead of null
String daveNumber = contacts.getOrDefault("Dave", "Not found");
System.out.println("Dave's number: " + daveNumber);

What does this code do?

  • containsKey("Bob") returns true or false, letting you check if a key exists before you try to use its value.
  • getOrDefault("Dave", "Not found") works like get(), but returns the fallback "Not found" instead of null when the key is missing.
  • Save ContactBook.java and press F5 to run.
  • You should see Bob is in our contacts! and Dave's number: Not found in the output.

Not seeing the expected output?

  • Make sure the string inside containsKey() matches the exact capitalization of the key you used in put(). HashMap keys are case-sensitive.
  • Check that the if block has matching opening and closing curly braces.
  • help me debug my containsKey or getOrDefault code
Update an existing contact

Calling put() with a key that already exists replaces the old value with the new one. This is how you update entries in a HashMap.

  • Add the following code at the end of your main method, after the getOrDefault println:
// Update Alice's number by calling put() with the same key
contacts.put("Alice", "555-9999");
System.out.println("Alice's updated number: " + contacts.get("Alice"));

What does this code do?

You already used put("Alice", "555-0101") earlier to add Alice. Calling put("Alice", "555-9999") again overwrites the old value. There's no separate "update" method in HashMap.

  • Save ContactBook.java and press F5 to run.
  • You should see Alice's updated number: 555-9999 at the bottom of the output.

Still seeing the old number?

  • Make sure the update put() call comes after the earlier get("Alice") call. Order matters.
  • Confirm the key string is exactly "Alice" with a capital A.
  • help me figure out why my HashMap update isn't working

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

Here's what your complete ContactBook.java should look like at this point:

import java.util.HashMap;

public class ContactBook {
    public static void main(String[] args) {
        HashMap<String, String> contacts = new HashMap<>();

        contacts.put("Alice", "555-0101");
        contacts.put("Bob", "555-0102");
        contacts.put("Charlie", "555-0103");

        System.out.println("All contacts: " + contacts);
        System.out.println("Number of contacts: " + contacts.size());

        String aliceNumber = contacts.get("Alice");
        System.out.println("Alice's number: " + aliceNumber);

        String unknownNumber = contacts.get("Dave");
        System.out.println("Dave's number: " + unknownNumber);

        if (contacts.containsKey("Bob")) {
            System.out.println("Bob is in our contacts!");
        }

        String daveNumber = contacts.getOrDefault("Dave", "Not found");
        System.out.println("Dave's number: " + daveNumber);

        contacts.put("Alice", "555-9999");
        System.out.println("Alice's updated number: " + contacts.get("Alice"));
    }
}

You can now store, retrieve, check, and update contacts. Next up, you'll learn how to remove contacts and loop through your entire contact book.

Remove Contacts and Iterate

You can now add, retrieve, and update contacts in your HashMap. But what about removing contacts that are no longer needed, or viewing everyone in your book at once?

In this step, you'll learn how to delete entries and loop through your entire contact book. These are essential operations for any real-world application that manages collections of data.

In this step, get ready to:
  • Remove a contact from your HashMap and verify it's gone.
  • Iterate through all contact names using keySet().
  • Iterate through all key-value pairs using entrySet().
Remove a contact with remove()

The remove() method deletes a key-value pair from the HashMap by its key. You can then use containsKey() to confirm the entry is truly gone.

  • In ContactBook.java, find the last line that says System.out.println("Alice's updated number: " + contacts.get("Alice"));.
  • Add the following code below that line to remove Charlie and confirm the removal:
// Remove a contact by key
contacts.remove("Charlie");
System.out.println("After removing Charlie: " + contacts);
System.out.println("Contains Charlie? " + contacts.containsKey("Charlie"));

What does this code do?

  • contacts.remove("Charlie") deletes the key "Charlie" and its associated phone number from the HashMap entirely.
  • Printing the map afterwards shows Charlie is no longer listed.
  • containsKey("Charlie") returns false, confirming the removal worked.
  • Save ContactBook.java.
  • Click the Run button above main (or press F5). Near the bottom of the output, you should see Contains Charlie? false.

Still seeing Charlie in the output?

  • Make sure the remove() line comes after the initial put() calls. If it's placed before them, Charlie gets re-added.
  • Check that you typed the name "Charlie" with a capital C. HashMap keys are case-sensitive.

Help me debug why Charlie still appears after calling remove()

Iterate over all keys with keySet()

The keySet() method returns all the keys in your HashMap as a Set. You can loop through it with a for-each loop to print every contact name.

  • Add the following code below the Contains Charlie? print line to iterate over all contact names:
// Print all contact names using keySet()
System.out.println("\n--- All Contact Names ---");
for (String name : contacts.keySet()) {
    System.out.println(name);
}

What does this code do?

  • contacts.keySet() returns a Set containing all the keys (contact names) in the HashMap.
  • The for-each loop assigns each key to the variable name one at a time, so you can print them individually.
  • The order of names printed may not match the order you added them. HashMap does not guarantee insertion order.
  • Save ContactBook.java and press F5 to run.
  • In the terminal output, you should see a --- All Contact Names --- header followed by Alice and Bob printed on separate lines.

Not seeing any names printed?

  • Check that your for loop uses a colon (:) not a semicolon. The for-each syntax is for (String name : contacts.keySet()).
  • Make sure the code is placed inside the main method's curly braces, not after them.

Help me fix my keySet() for-each loop

Iterate over key-value pairs with entrySet()

When you need both the key and value during iteration, entrySet() is the way to go. It returns each key-value pair as a single Map.Entry object.

  • Add the following code below the keySet() loop to iterate over all key-value pairs:
// Print all contacts with their phone numbers using entrySet()
System.out.println("\n--- Full Contact List ---");
for (var entry : contacts.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

What does this code do?

  • contacts.entrySet() returns a Set of Map.Entry objects. Each entry holds one key-value pair.
  • entry.getKey() retrieves the contact name, and entry.getValue() retrieves the phone number.
  • The var keyword lets Java infer the type automatically. It's equivalent to writing Map.Entry<String, String> but much shorter.

Why use entrySet() instead of keySet()?

With keySet(), you only get keys. If you also need values, you'd have to call get() for each key inside the loop.

entrySet() gives you both the key and value together in one pass. This is the most common iteration pattern in professional Java code.

  • Save ContactBook.java and press F5 to run.
  • You should see a --- Full Contact List --- header followed by lines showing each contact's name and phone number separated by a colon.

Seeing a compile error on the var keyword?

  • The var keyword requires Java 10 or higher. Since you're running JDK 26, this should work. If you see an error, check that your VS Code Java extension is using JDK 26 and not an older version.
  • Make sure you typed var in lowercase. It's not a capital-V keyword.

Help me fix a compile error with var in my entrySet() loop

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

Here's the complete ContactBook.java file at this point. Compare it with yours to spot any differences.

import java.util.HashMap;

public class ContactBook {
    public static void main(String[] args) {
        HashMap<String, String> contacts = new HashMap<>();

        contacts.put("Alice", "555-0101");
        contacts.put("Bob", "555-0102");
        contacts.put("Charlie", "555-0103");

        System.out.println("All contacts: " + contacts);
        System.out.println("Number of contacts: " + contacts.size());

        String aliceNumber = contacts.get("Alice");
        System.out.println("Alice's number: " + aliceNumber);

        String unknownNumber = contacts.get("Dave");
        System.out.println("Dave's number: " + unknownNumber);

        if (contacts.containsKey("Bob")) {
            System.out.println("Bob is in our contacts!");
        }

        String daveNumber = contacts.getOrDefault("Dave", "Not found");
        System.out.println("Dave's number: " + daveNumber);

        contacts.put("Alice", "555-9999");
        System.out.println("Alice's updated number: " + contacts.get("Alice"));

        contacts.remove("Charlie");
        System.out.println("After removing Charlie: " + contacts);
        System.out.println("Contains Charlie? " + contacts.containsKey("Charlie"));

        System.out.println("\n--- All Contact Names ---");
        for (String name : contacts.keySet()) {
            System.out.println(name);
        }

        System.out.println("\n--- Full Contact List ---");
        for (var entry : contacts.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

You can now add, retrieve, update, remove, and iterate over contacts. Next up, you'll combine all of these operations into an interactive menu that lets you manage your contact book in real time.

Build the Interactive Menu

You've used every core HashMap operation individually. You can add, retrieve, update, delete, and iterate over contacts.

Now it's time to combine all of those operations into a single interactive app. You'll replace the hardcoded demonstrations with a menu loop that lets you type choices and see your HashMap respond in real time.

In this step, get ready to:
  • Add a Scanner import and build a menu loop with user input.
  • Wire each menu option to the matching HashMap operation.
  • Run the final interactive version and test every feature.
Add the Scanner import and menu loop

Right now your file runs a set of hardcoded demos from top to bottom. You'll replace the entire contents with a loop that displays a menu, reads the user's choice, and acts on it.

  • In VS Code, open ContactBook.java from the src folder.
  • Select all the code (Cmd+A on macOS, Ctrl+A on Windows) and delete it.
  • Replace it with this menu loop skeleton by pasting the following code:
import java.util.HashMap;
import java.util.Scanner;

public class ContactBook {
    public static void main(String[] args) {
        HashMap<String, String> contacts = new HashMap<>();
        Scanner scanner = new Scanner(System.in);

        // Pre-populate with sample contacts
        contacts.put("Alice", "555-0101");
        contacts.put("Bob", "555-0102");
        contacts.put("Charlie", "555-0103");

        System.out.println("Welcome to your Contact Book!");
        System.out.println("Loaded " + contacts.size() + " sample contacts.\n");

        boolean running = true;

        while (running) {
            System.out.println("--- Contact Book Menu ---");
            System.out.println("1. Add a contact");
            System.out.println("2. Look up a contact");
            System.out.println("3. Update a contact");
            System.out.println("4. Delete a contact");
            System.out.println("5. List all contacts");
            System.out.println("6. Exit");
            System.out.print("Choose an option: ");

            String choice = scanner.nextLine();

            switch (choice) {
                case "6":
                    running = false;
                    System.out.println("Goodbye!");
                    break;

                default:
                    System.out.println("Invalid option. Please choose 1-6.");
            }
            System.out.println();
        }

        scanner.close();
    }
}

What does this code do?

This skeleton sets up the structure your interactive app needs before you fill in each menu option.

  • import java.util.Scanner; brings in Java's keyboard input reader.
  • Scanner scanner = new Scanner(System.in); creates a Scanner that reads from the terminal.
  • boolean running = true; controls the while loop. Setting it to false exits the menu.
  • The switch block routes each choice to the correct action. Right now only Exit and an invalid-input default are wired.
  • Save ContactBook.java.
  • Press F5 to run. You should see a welcome message, the menu printed, and a prompt waiting for your input.
  • Type 6 and press Enter to confirm the exit path works.

Can't type in the terminal?

If the program runs but you can't type input, your output may be going to the Debug Console instead of the integrated terminal. Click inside the Terminal tab at the bottom of VS Code to focus it.

If that doesn't help, check that your launch.json has "console": "integratedTerminal" so Java runs in a terminal that accepts input.

Still stuck? Help me fix Scanner input not working in VS Code

Implement each menu option

The skeleton can only exit. Now you'll wire options 1 through 5 to the HashMap operations you already know from the previous steps.

  • In ContactBook.java, find this line inside the switch block:
            switch (choice) {
  • Add all five cases below that line, before the existing case "6": line:
                case "1":
                    System.out.print("Enter name: ");
                    String addName = scanner.nextLine();
                    if (contacts.containsKey(addName)) {
                        System.out.println("Contact already exists! Use option 3 to update.");
                    } else {
                        System.out.print("Enter phone number: ");
                        String addNumber = scanner.nextLine();
                        contacts.put(addName, addNumber);
                        System.out.println("Added " + addName + "!");
                    }
                    break;

                case "2":
                    System.out.print("Enter name to look up: ");
                    String lookupName = scanner.nextLine();
                    String lookupResult = contacts.getOrDefault(lookupName, "Not found");
                    System.out.println(lookupName + ": " + lookupResult);
                    break;

                case "3":
                    System.out.print("Enter name to update: ");
                    String updateName = scanner.nextLine();
                    if (contacts.containsKey(updateName)) {
                        System.out.print("Enter new phone number: ");
                        String newNumber = scanner.nextLine();
                        contacts.put(updateName, newNumber);
                        System.out.println("Updated " + updateName + "!");
                    } else {
                        System.out.println("Contact not found. Use option 1 to add.");
                    }
                    break;

                case "4":
                    System.out.print("Enter name to delete: ");
                    String deleteName = scanner.nextLine();
                    if (contacts.containsKey(deleteName)) {
                        contacts.remove(deleteName);
                        System.out.println("Deleted " + deleteName + ".");
                    } else {
                        System.out.println("Contact not found.");
                    }
                    break;

                case "5":
                    if (contacts.isEmpty()) {
                        System.out.println("No contacts stored.");
                    } else {
                        System.out.println("\n--- All Contacts (" + contacts.size() + ") ---");
                        for (var entry : contacts.entrySet()) {
                            System.out.println(entry.getKey() + ": " + entry.getValue());
                        }
                    }
                    break;

What does each case do?

  • Case 1 (Add) uses containsKey() as a guard. If the name already exists, it tells you to use update instead of silently overwriting.
  • Case 2 (Look up) uses getOrDefault() so you always get a readable message instead of null.
  • Case 3 (Update) checks the key exists first, then calls put() to replace the old value.
  • Case 4 (Delete) uses remove() after confirming the contact exists.
  • Case 5 (List all) iterates with entrySet() to print every name and number. It also handles the empty-map edge case.
  • Save ContactBook.java.

Seeing red underlines in VS Code?

Make sure the new cases sit between switch (choice) { and case "6":. If they're outside the switch or after the default, Java will show syntax errors.

Also check that every case ends with break;. A missing break won't cause a syntax error, but it will make multiple cases run at once.

Need more help? Help me fix the syntax errors in my switch statement

Run the final interactive version

Your contact book is complete. Time to take it for a spin and see every HashMap operation working through the menu.

  • Press F5 to run the program.
  • Click inside the Terminal panel at the bottom of VS Code so your keyboard input goes to the program.
  • Type 1 and press Enter to add a new contact. Enter a name and phone number when prompted.
  • Type 2 and look up the contact you just added. You should see the phone number you entered.
  • Type 1 again and try adding a duplicate name. You should see the message telling you to use option 3 instead.
  • Type 5 to list all contacts and confirm your new entry appears alongside Alice, Bob, and Charlie.
  • Type 6 to exit. The program should print Goodbye! and stop.

Why does put() sometimes add and sometimes update?

HashMap's put() always associates a key with a value. If the key is new, it adds an entry. If the key already exists, it replaces the old value.

That's why the Add option (case 1) uses a containsKey() guard. Without it, adding "Alice" a second time would silently overwrite her number.

Program exits immediately without showing the menu?

Check that boolean running = true; appears before the while loop. If running starts as false, the loop body never executes.

Also confirm you're clicking into the Terminal tab (not the Debug Console). The Debug Console doesn't accept typed input.

Still having issues? Help me debug why my Java menu loop exits immediately

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

Here's the complete ContactBook.java file. Compare it against yours line by line.

import java.util.HashMap;
import java.util.Scanner;

public class ContactBook {
    public static void main(String[] args) {
        HashMap<String, String> contacts = new HashMap<>();
        Scanner scanner = new Scanner(System.in);

        // Pre-populate with sample contacts
        contacts.put("Alice", "555-0101");
        contacts.put("Bob", "555-0102");
        contacts.put("Charlie", "555-0103");

        System.out.println("Welcome to your Contact Book!");
        System.out.println("Loaded " + contacts.size() + " sample contacts.\n");

        boolean running = true;

        while (running) {
            System.out.println("--- Contact Book Menu ---");
            System.out.println("1. Add a contact");
            System.out.println("2. Look up a contact");
            System.out.println("3. Update a contact");
            System.out.println("4. Delete a contact");
            System.out.println("5. List all contacts");
            System.out.println("6. Exit");
            System.out.print("Choose an option: ");

            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    System.out.print("Enter name: ");
                    String addName = scanner.nextLine();
                    if (contacts.containsKey(addName)) {
                        System.out.println("Contact already exists! Use option 3 to update.");
                    } else {
                        System.out.print("Enter phone number: ");
                        String addNumber = scanner.nextLine();
                        contacts.put(addName, addNumber);
                        System.out.println("Added " + addName + "!");
                    }
                    break;

                case "2":
                    System.out.print("Enter name to look up: ");
                    String lookupName = scanner.nextLine();
                    String lookupResult = contacts.getOrDefault(lookupName, "Not found");
                    System.out.println(lookupName + ": " + lookupResult);
                    break;

                case "3":
                    System.out.print("Enter name to update: ");
                    String updateName = scanner.nextLine();
                    if (contacts.containsKey(updateName)) {
                        System.out.print("Enter new phone number: ");
                        String newNumber = scanner.nextLine();
                        contacts.put(updateName, newNumber);
                        System.out.println("Updated " + updateName + "!");
                    } else {
                        System.out.println("Contact not found. Use option 1 to add.");
                    }
                    break;

                case "4":
                    System.out.print("Enter name to delete: ");
                    String deleteName = scanner.nextLine();
                    if (contacts.containsKey(deleteName)) {
                        contacts.remove(deleteName);
                        System.out.println("Deleted " + deleteName + ".");
                    } else {
                        System.out.println("Contact not found.");
                    }
                    break;

                case "5":
                    if (contacts.isEmpty()) {
                        System.out.println("No contacts stored.");
                    } else {
                        System.out.println("\n--- All Contacts (" + contacts.size() + ") ---");
                        for (var entry : contacts.entrySet()) {
                            System.out.println(entry.getKey() + ": " + entry.getValue());
                        }
                    }
                    break;

                case "6":
                    running = false;
                    System.out.println("Goodbye!");
                    break;

                default:
                    System.out.println("Invalid option. Please choose 1-6.");
            }
            System.out.println();
        }

        scanner.close();
    }
}

Secret mission

Add Reverse Lookup by Phone Number

Your contact book can look up a phone number by name instantly. But what if you have a phone number and want to find who it belongs to? Add a reverse lookup feature and discover why this search is fundamentally different from a name lookup.

Clean Up Your Resources

Clean Up Your Resources

Decide whether to keep your resources running, pause them to come back later, or delete them entirely. This project runs entirely locally, so there are no ongoing costs.

Resources you used:

  • The ContactBook project folder (contains src/ContactBook.java and project files).

Keep everything running

No action needed. Choose this if you're still actively building or want to experiment more with HashMap operations.

  • Your ContactBook project stays on your machine, ready to open in VS Code whenever you want.
  • There are no background processes or services running from this project.

Pause - I'll come back to this later

Close VS Code to free up memory. Your files stay on disk and you can reopen the project any time.

  • Close the VS Code window with the ContactBook project.
  • To resume later, open VS Code and use File > Open Folder to navigate back to your ContactBook folder.

Delete - I don't want to use this again

Remove the project folder entirely to start fresh.

  • Close VS Code if it's still open.
  • Delete the ContactBook folder. On macOS/Linux, open Terminal and run the command below (replacing the path with wherever you created the project). On Windows, open PowerShell and use the second command.
rm -rf ~/Desktop/ContactBook
Remove-Item -Recurse -Force ~\Desktop\ContactBook

If you saved your project in a different location, adjust the path accordingly.

Nice Work!

Nice Work!

You just built a fully interactive contact book powered by Java's HashMap! From storing and retrieving contacts to iterating over entries and handling missing keys, you now have hands-on experience with the most-used data structure in professional Java development.

You learned how to:

  • Created and populated a HashMap with String key-value pairs, then retrieved values with get() and handled missing keys with containsKey() and getOrDefault().
  • Iterated over keys with keySet() and over key-value pairs with entrySet(), the two most common HashMap iteration patterns.
  • Built a menu-driven console application that combines add, lookup, update, delete, and list operations into a real-world interactive program.
  • Added a reverse lookup feature to understand the performance trade-offs of key vs. value searches in a HashMap.

Ready to quiz yourself?