It is a method of String Class which is used to return the value of hash code of the instance of string.
It is frequently used in Java and its return type is integer. Basically Hashmap and HashSet uses hashing to manipulate data. This hash code represents the integer representation of memory address.
If content of two string objects is same, then calling the hashcode() method, both objects must return the same value of hash code but not necessarily vice versa.
String Str1 = new String("Hello World"); String Str2 = new String("Hello World"); System.out.println("Hashcode for Str1 :" + Str1.hashCode() ); System.out.println("Hashcode for Str2 :" + Str2.hashCode() );
Hashcode for Str1 :-862545276 Hashcode for Str2 :-862545276
StringBuffer is a class which creates modifiable string called mutable strings.
This class allows to Update, replace, append, concatenate the whole string or sequence of its characters. It has methods to modify even the length and memory allocation for string.
StringBuffer inherits many methods from java.lang.object. It implements clearSequence, Appendble, Serializable interface.
It is thread safe, multiple threads cannot use its methods simultaneously. Most of the methods are synchronized due to which it operates slowly and it is also less efficient.
String Builder is also used to create mutable string. This class also allows to Update, replace, append, concatenate the whole string or sequence of its characters. It is not safe thread, which means multiple threads can use its methods simultaneously. It is faster and more efficient than StringBuffer.
String intern() is a method for keeping single copy of immutable string value. This methods ensures that all the strings having same value are using same memory’s location.
With the help of string interning, so much memory can be saved. Basically this method returns the interned string. When intern() method is called it checks if that string is already existed in the specified memory i.e. String constant pool or not. If it is present then it return the string from the String constant pool. Otherwise creates it and returns its reference.
Java platform provides predefined class known as String. String class represents string of characters and is used to create String objects. All the strings in java program are the instances of class java.lang.String. This class includes methods for manipulating strings like examining individual elements of the string, comparing string objects, searching strings, extracting substrings from string objects, converting strings to uppercase or to lowercase. It also facilitate to concatenate string and conversion of objects to string using “+” operator and toString() method respectively.