javaobjecttostringhashcodeocpjp

Java: ToString() prints the same hashcode each time


class Point {
    private int xPos, yPos;

    public Point(int x, int y) {
        xPos = x;
        yPos = y;
    }
    public static void main(String[] args) {
        System.out.println(new Point(10,20));
    }
}

The output of above code returns the same ClassName@hex version of the object's hashcode, although the text I am referring to (OCPJP Guide by S G Ganesh and Tushar Sharma) states "The Hexadecimal value will be different for each instance." Am I not understanding this correctly?


Solution

  • Try making two instances,

    System.out.println(new Point(10, 20));
    System.out.println(new Point(10, 20));
    

    And you'll get two distinct hashCodes.