MyMisPal
← Java lessons
Lesson 9 of 9

HashMap and exceptions

JAVA
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> stock = new HashMap<>();
        stock.put("Laptop", 25);
        stock.put("Router", 60);
        stock.put("Laptop", 20);
        System.out.println(stock.get("Laptop"));
        System.out.println(stock.getOrDefault("Chair", 0));
        System.out.println(stock.containsKey("Router") + " " + stock.size());
    }
}
Output
20
0
true 2
Watch output with an existing key replaces the value. HashMap order isn't guaranteed; use TreeMap (sorted) or LinkedHashMap (insertion order) when order matters.

Exceptions: try and catch handle runtime errors, and finally always runs:

JAVA · inside main
try {
    int qty = Integer.parseInt("ten");
    System.out.println(qty);
} catch (NumberFormatException e) {
    System.out.println("Not a number");
} finally {
    System.out.println("Done");
}
Output
Not a number
Done
Same idea in both languages
Python
try:
    qty = int("ten")
except ValueError:
    print("Not a number")
Java
try {
    int qty = Integer.parseInt("ten");
} catch (NumberFormatException e) {
    System.out.println("Not a number");
}
Spotted a mistake on this page, or have an idea to improve the site?