8

I want to know what exactly the output is when I do the following.

class Data {
  int a = 5;
}

class Main {
  public static void main(String[] args) {
    data dObj = new data();
    System.out.println(dObj);
  }
}

I know it gives something related to object as the output in my case is data@1ae73783. I guess the 1ae73783 is a hex number. I also did some work around and printed

System.out.println(dObj.hashCode());

I got the number 415360643. I got an integer value. I don't know what hashCode() returns, still out of curiosity, when I converted 1ae73783 to decimal, I got 415360643!

That's why I am curious about what exactly is this number. Is this some memory location of Java's sandbox or some other thing?

1

4 Answers 4

17

What happens is that the default toString() method of your class is getting used. This method is defined as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

The value returned by the default hashCode() method is implementation-specific:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

1
  • 1
    Yes, this is almost the same as I experimented later, I did codeSystem.out.println(String.valueOf(Integer.parseInt("1ae73783",16))); code and got the decimal value
    – upInCloud
    Nov 21, 2012 at 17:01
3

When you print an instance of your class, that does not override the toString method, then the toString method of Object class is used. Which prints an output in the form: -

data@1ae73783
  • The first part of that output shows the type of the object.

  • And the 2nd part is the hexadecimal representation of the hashCode of your object.

Here's the source code of Object.toString() method, that you can find in the installation directory of your jdk, under src folder: -

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
3

The Javadoc for hashCode() and toString() in the Object class should be able to clarify this for you.

0
2

That code calls the default toString() implementation of the Object class, that is:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.