This project simulates a teacher's digital gradebook. It demonstrates how to use the containsKey() method in a HashMap to verify if a specific entry exists before attempting to retrieve and process its value. This approach prevents potential null pointer issues and ensures data integrity.
- Task: Create a
HashMap<String, Integer>namedstudentGrades. - Action: Add a record for "Anna" with a grade of 5.
- Validation: Check if the record for "Anna" exists using map properties.
- Output: Display Anna's grade only if the record is found.
- Goal: Master safe data retrieval techniques in associative arrays.
- Java 8+
The HashMap provides an efficient containsKey(Object key) method that returns a boolean. By using this method inside an if statement, we can safely access values. This is a fundamental pattern for handling dynamic data where certain keys might be missing.
Anna's grade: 5
Project Structure:
src/com/yurii/pavlenko/
└── Solution.java
Code
package com.yurii.pavlenko;
import java.util.HashMap;
import java.util.Map;
public class Solution {
public static void main(String[] args) {
Map<String, Integer> studentGrades = new HashMap<>();
studentGrades.put("Anna", 5);
if (studentGrades.containsKey("Anna")) {
Integer grade = studentGrades.get("Anna");
System.out.println("Anna's grade: " + grade);
} else {
System.out.println("Record not found.");
}
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT