Skip to content
Related Articles

Related Articles

Java String hashCode() Method with Examples

Improve Article
Save Article
  • Last Updated : 28 Dec, 2021
Improve Article
Save Article

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:

int hashCode()

Parameter: This method doesn’t take any parameters.

Return type: This method returns the hash value in int format.

Example:

Java




import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {  
          // Creating the two String variable.
        String m = "A";
        String n="Aayush";
        
          // Returning the hash value of m variable
        System.out.println(m.hashCode());
         
          // Returning the hash value of n variable.
        System.out.println(n.hashCode());
    }
}


Output

65
1954197169

 Comparing two String values using hashCode().

Java




import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Creating variable n of String type
        String n = "A";
  
        // Creating an object of String containing same
        // value;
        String m = new String("A");
  
        // Getting the hashvalue of object and the variable
        int hashValue_n = n.hashCode();
        int hashValue_m = m.hashCode();
  
        // Hash value is same whether is created from
        // variable or object.
        if (hashValue_n == hashValue_m) {
  
            // Printing the output when the output is same
            System.out.println("Values Same");
        }
        else {
            System.out.println("Not Same");
        }
    }
}


Output

Values Same

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!