String is one of the most used classes in any programming language. We know that String is immutable and final in java and java runtime maintains a String pool that makes it a special class.
String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.
Note : HashMap uses hashCode() and equals() methods on keys for get and put operations. So HashMap key object should provide good implementation of these methods. This is the reason immutable classes are better suitable for keys,
Let's say, We have some data of the students and we need to keep that data for further processing in a Hashmap.
HashMap<String, String> students = new HashMap<>();
Here we have used some Strings as key in Hashmap. Now we have put 6 students data into the students map and due to immutability of the String all the keyswill be catched into the system and while retrieving the value of the object based on key system no need to calculate the hashcode of the key again and again. So with little efforts we can get the value against the key.
String s1 = students.get("S1");