String str1 = "hello"; String str2 = "world"; int hash1 = str1.hashCode(); int hash2 = str2.hashCode(); System.out.println("Hashcode of " + str1 + " is " + hash1); System.out.println("Hashcode of " + str2 + " is " + hash2);
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public int hashCode() { return Objects.hash(name, age); } } Person person1 = new Person("John Doe", 32); Person person2 = new Person("Jane Smith", 28); int hash1 = person1.hashCode(); int hash2 = person2.hashCode(); System.out.println("Hashcode of " + person1.getName() + " is " + hash1); System.out.println("Hashcode of " + person2.getName() + " is " + hash2);In this example, we create a Person class with a name and age attribute. We override the hashCode() method to generate a unique hashcode for each object based on their name and age. Then we create two Person objects and get their hashcodes. The output will display the hash code value for each Person object. The hashCode() method is part of the java.lang.Object class, which is included in the Java Standard Library.