Search code examples
javastringreturn-value-optimization

valueOf() in java Returns Object But why hashcode is not there?


The API for Integer.valueOf("123") returns an object.. So if I'am Writing This

System.out.println(Integer.valueOf("456")); or System.out.println(String.valueOf(256));

these should give me the hashcode of the object but instead it printing simple value 456 and 256.

So can anyone explain me why instead of hashcode i'm getting the value

Thanks :)


Solution

  • Because Integer and String overrides the toString() method.

    Also The hashCode of Integer is the int value of it:

    /**
     * Returns a hash code for this {@code Integer}.
     *
     * @return  a hash code value for this object, equal to the
     *          primitive {@code int} value represented by this
     *          {@code Integer} object.
     */
    public int hashCode() {
        return value;
    }