Java String hashCode() Method with Examples
Last Updated :
06 Jun, 2023
The Java String hashCode() method is used to return the particular value’s hash value. The hashCode() uses an internal hash function that returns the hash value of the stored value in the String variable.
Hash Value: This is the encrypted value that is generated with the help of some hash function. For example, the hash value of ‘A’ is 67.
The hashCode() method of Java String is the method of the object class that is the parent class of all the classes in Java. The string class also inherits the object class. That’s why it is available in the String class. The hashCode is used for the comparison of String objects. A code hash function always returns the unique hash value for every String value.
The hashCode() method is the inherited method from the Object class in the String class that is used for returning the hash value of a particular value of the String type.
Syntax of Java hashcode()
int hashCode();
Parameters
- This method doesn’t take any parameters.
Return type
- This method returns the hash value in int format.
Example of Java String hashCode()
Example 1:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String m = "A" ;
String n = "Aayush" ;
System.out.println(m.hashCode());
System.out.println(n.hashCode());
}
}
|
Example 2: Comparing two String values using hashCode().
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String n = "A" ;
String m = new String( "A" );
int hashValue_n = n.hashCode();
int hashValue_m = m.hashCode();
if (hashValue_n == hashValue_m) {
System.out.println( "Values Same" );
}
else {
System.out.println( "Not Same" );
}
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...