0

I have this code

class A
{
 public static void main(String reds[])
  {
    A ob=new A();
    System.out.println("Object "+ob);
    System.out.println("HashCode "+ob.hashCode());
  }
}

Output is: Output image

The output for above code gives different value most of the time. Also, the below link mentions that printing a reference variable prints ClassName@hashcode.

printing reference variable is not printing the object's address

However, the output for printing reference varibale differs from hashCode().What is actually happening here?

Just wanted to clear my concepts of hashcode in java.

2 Answers 2

2

When you call println() on your object (of type A), it prints getClass().getName() + "@" + Integer.toHexString(hashCode()) (which is the default implementation of toString() in Object class) i.e, it converts hashCode to hexString. If you do the same for your hashCode (when printing), you will get the same value.

If your class overrides toString, then it will be printed.

Sign up to request clarification or add additional context in comments.

4 Comments

Also, directly printing an object using println() calls its toString() method which does mentioned tasks.
@PrasadKharkar - Yes. It calls Object's toString if your class (or any of its direct parents) don't override toString()
It prints the result of calling A.toString(), whatever that may be. In this case it wasn't overridden, so it printed the result of Object.toString(). None of this behaviour is attributable to println().
@EJP - I thought that the OP's question was how className@someHexVal was being generated. Edited my answer to add the toString part
0

Object.toString() uses the hashCode in hex. You are printing it yourself in decimal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.