.hashCode()
Published Mar 27, 2023
Contribute to Docs
The .hashCode()
method returns an integer hash code value for the object on which it is invoked. The hash code for a String
object is computed as follows:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
s[i]
is the i
-th character of the string, n
is the length of the string, and ^
indicates exponentiation.
Syntax
int hashCodeValue = objectName.hashCode();
hashCodeValue
is an integer variable that stores the hash code value returned by the.hashCode()
method.
Example
The example below demonstrates the use of the .hashCode()
method:
// Example.javapublic class Example {public static void main(String[] args) {String str = "codeacademy.com";int hashCodeValue = str.hashCode();System.out.println(hashCodeValue);}}
This outputs the following:
667975538
Note: The hash code value may vary for the same object when the program is executed multiple times. This is because the hash code value is generated based on the object’s memory address, which may vary each time the program is run due to the dynamic nature of memory allocation in computer systems.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours