Search Java Programs

Showing posts with label hashCode(). Show all posts
Showing posts with label hashCode(). Show all posts

Wednesday, January 20, 2010

Java String hashCode Example

String class hashCode method example


String class hashCode method example:- This example demonstrates the working of hashCode method. this method returns corresponding hashCodes of objects value passed.

Syntax:-hashCode()

Here is the code:-

 /**
* @(#) HashCodeString.java
* HashCodeString class demonstrates the working of hashCode() method of String class of lang package
* @version 16-May-2008
* @author Rose India Team
*/



public class HashCodeString {
public static void main(String args[]) {

// hashCode method generates hash codes repersentations of only objects
// values
// arithmetically hash Codes of numbers are generated as follows
// s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
// here i is any character value or number value of the object,
// n is .length method value of the object say String, and ^ denotes
// exponentiation.
// The hash value of the empty string is zero
Integer j = new Integer(10);
Long k = new Long(10);
Integer v = new Integer(0);
// here value types don't match therefore methos returns false
System.out.println("false is returned: " + j.equals(k));
// hash codes of different objects with same value are always same
System.out.println("Hash code of number 10 is: " + j.hashCode()
+ "\nHash code of number 10 is: " + k.hashCode());
// corresponding hash code value of number zero(0) is zero(0)
System.out.println("Method returns zero: " + v.hashCode());

String baadshah = "latter in time there will be my empire every where";
// hashCode representation of the value ofobject 'baadshah'
// every object has its own hash code representation of their values
// every value of any object consists of unique hash codes
System.out.println("Corresponding hash code value returned is: "
+ baadshah.hashCode());
}

}
Output of the program:-
false is returned: false
Hash code of number 10 is: 10
Hash code of number 10 is: 10
Method returns zero: 0
Corresponding hash code value returned is: 342164105

Website Design by Mayuri Multimedia