Since 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 that, if another String with the same contents exists in the String constant pool, then a new object won’t be created and the new reference will point to the other String.
We can call the intern() method to tell the JVM to add it to the string pool if it doesn’t already exist there, and return a reference of that interned string:
Example:-
public class Main { public static void main(String[] args) { String s1 = "abc"; String s2 = new String("abc"); String s3 = new String("foo"); String s4 = s1.intern(); String s5 = s2.intern(); System.out.println(s3 == s4); System.out.println(s1 == s5); } } output: false true
Say, equals() method because it compares two string objects based on their content. That provides more logical comparison of two string objects. If you use “==” operator, it checks only references of two objects are equal or not. It may not be suitable in all situations. So, rather stick to equals() method to compare two string objects.
Example:-
public class Main { public static void main(String[] args) { String s1 = new String("HELLO"); String s2 = new String("HELLO"); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); } } output: false true
Yes, Strings are immutable in Java so once we create a String object then we can’t change its content. Hence it’s thread-safe and can be safely used in a multi-threaded environment.