Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when printing an object in java

Tags:

java

object

class Data {
    int a = 5;
}

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

I want to know what's happening when printing a object or number or string.

I ran the above code, I'm getting the result as "data@1ae73783" for System.out.println(dObj); and "5" for System.out.println(b);

Then I did debug to check whats really happening when printing a object, there was lot of parameter called in a debug mode(like classloader,theards)
I know for the first print the value represent class name followed by address. But don't know what's really happening in debug mode, for the 2nd print only variable assignment happened in the debug mode i.e b=5.

Please explain whats really happening?

like image 785
Marjer Avatar asked Dec 22 '13 23:12

Marjer


1 Answers

You don't need a debugger to know what's happening. System.out is of type PrintStream. The javadoc of PrintStream.println(Object) says:

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

The javadoc of String.valueOf(Object) says:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

And the javadoc of Object.toString() says:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

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())
 
like image 170
JB Nizet Avatar answered Sep 24 '22 20:09

JB Nizet