📖 Scenario: Imagine you run a small library. You want to keep track of which book belongs to which shelf number. You need a fast way to find the shelf number when you know the book's name.
🎯 Goal: You will create a simple program that stores book names and their shelf numbers using a Java HashMap. You will then look up shelf numbers quickly by book name.
📋 What You'll Learn
Create a HashMap to store book names as keys and shelf numbers as values
Add at least 3 books with their shelf numbers to the HashMap
Use a variable to store the book name to search for
Retrieve the shelf number for the given book name from the HashMap
Print the shelf number found
💡 Why This Matters
🌍 Real World
Libraries, phone books, and databases use hash maps to find information quickly by a key like a name or ID.
💼 Career
Understanding hash maps is essential for software developers to write efficient code for data storage and retrieval.
Progress0 / 4 steps
1
Create the HashMap with books and shelf numbers
Create a HashMap called library that stores String keys and Integer values. Add these entries exactly: "Harry Potter" with 5, "Lord of the Rings" with 3, and "The Hobbit" with 7.
DSA Java
Hint
Use HashMap<String, Integer> and the put method to add entries.
2
Set the book name to search for
Create a String variable called searchBook and set it to "The Hobbit".
DSA Java
Hint
Use String searchBook = "The Hobbit"; to store the book name.
3
Retrieve the shelf number for the book
Create an Integer variable called shelfNumber and set it to the value from library for the key searchBook using the get method.
DSA Java
Hint
Use library.get(searchBook) to get the shelf number.
4
Print the shelf number found
Write a System.out.println statement to print the text "Shelf number: " followed by the value of shelfNumber.
DSA Java
Hint
Use System.out.println("Shelf number: " + shelfNumber); to print the result.
Practice
(1/5)
1. Why do we use a HashMap in Java instead of a simple array when we want to store key-value pairs?
easy
A. Because arrays use more memory than HashMap.
B. Because HashMap allows fast lookup of values by keys.
C. Because HashMap automatically sorts the keys.
D. Because arrays can only store numbers, not keys and values.
Solution
Step 1: Understand the limitation of arrays for key-value storage
Arrays store values by index, not by custom keys, so they can't quickly find a value by a key.
Step 2: Recognize the advantage of HashMap
HashMap stores data as key-value pairs and uses hashing to find values quickly by keys.
Final Answer:
Because HashMap allows fast lookup of values by keys. -> Option B
Quick Check:
Fast key-based lookup = Because HashMap allows fast lookup of values by keys. [OK]
Hint: HashMap = fast key-value lookup, arrays = index-based [OK]
Common Mistakes:
Thinking arrays can store key-value pairs directly
Believing HashMap sorts keys automatically
Confusing memory usage between arrays and HashMaps
2. Which of the following is the correct way to declare a HashMap in Java that maps String keys to Integer values?
easy
A. HashMap map = new HashMap<>();
B. HashMap map = new HashMap();
C. HashMap map = new HashMap<>();
D. HashMap map = new HashMap<String>();
Solution
Step 1: Identify correct generic syntax for HashMap declaration
The correct syntax uses angle brackets with key and value types on both sides or diamond operator on the right side.
Step 2: Check each option for syntax correctness and type order
HashMap map = new HashMap<>(); correctly declares a HashMap with String keys and Integer values using diamond operator. Others have wrong order or missing types.
Final Answer:
HashMap map = new HashMap<>(); -> Option A
Quick Check:
Correct generic syntax = HashMap map = new HashMap<>(); [OK]
Hint: Use diamond operator <> with correct key-value types [OK]
Common Mistakes:
Swapping key and value types
Omitting generic types on right side
Using raw types without generics
3. What will be the output of the following Java code?
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put("apple", 10);
map.put("banana", 20);
map.put("apple", 30);
System.out.println(map.get("apple"));
}
}
medium
A. 10
B. null
C. 20
D. 30
Solution
Step 1: Understand how put works in HashMap with duplicate keys
When a key already exists, put replaces the old value with the new one.
Step 2: Trace the code for key "apple"
First, "apple" is set to 10, then replaced by 30. So map.get("apple") returns 30.
Final Answer:
30 -> Option D
Quick Check:
Last value for key "apple" = 30 [OK]
Hint: Last put value for a key overwrites previous [OK]
Common Mistakes:
Assuming first value stays for duplicate keys
Expecting null for existing keys
Confusing values of different keys
4. The following code tries to check if a key exists in a HashMap and print its value. What is wrong?
HashMap map = new HashMap<>();
map.put("x", 5);
if (map.containsKey("y")) {
System.out.println(map.get("y"));
} else {
System.out.println("Key not found");
}
medium
A. The code throws NullPointerException when key is missing.
B. Using containsKey is wrong; should use get only.
C. No error; code works correctly.
D. The code should check for null instead of using containsKey.
Solution
Step 1: Understand containsKey usage
containsKey safely checks if a key exists without throwing errors.
Step 2: Check code behavior for missing key "y"
Since "y" is missing, containsKey returns false and prints "Key not found" without error.
Final Answer:
No error; code works correctly. -> Option C
Quick Check:
Using containsKey prevents errors = No error; code works correctly. [OK]
Hint: Use containsKey before get to avoid null issues [OK]
Common Mistakes:
Expecting NullPointerException on missing key
Using get without checking key existence
Thinking containsKey is unnecessary
5. You want to count how many times each word appears in a list of words using a HashMap. Which approach correctly solves this problem?
hard
A. Use a HashMap<String, Integer>, for each word check if it exists; if yes, increment count; else, add with count 1.
B. Use a HashMap<Integer, String> and store counts as keys and words as values.
C. Use an array to store counts and loop through words without a map.
D. Use a HashMap<String, String> and store words as both keys and values.
Solution
Step 1: Identify the correct key-value types for counting words
Keys should be words (String), values should be counts (Integer).
Step 2: Understand the counting logic using HashMap
For each word, check if it exists in map; if yes, increment count; else add with count 1.
Final Answer:
Use a HashMap, increment counts per word. -> Option A
Quick Check:
Word count needs String keys and Integer values [OK]
Hint: Map words to counts; increment existing or add new [OK]
Common Mistakes:
Swapping key and value types
Using arrays without keys for counting
Storing words as values instead of counts
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.