Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaJava String hashCode() Method with Examples

Java String hashCode() Method with Examples

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)
    {
        // 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

 Example 2: 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
RELATED ARTICLES

Most Popular

Recent Comments