What happens when printing an object in java

Viewed 32853
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?

7 Answers

when we print object of any class System.out.print() gives string of class name along with memory address of object (ClassName@MemoryAdress)

In Addition to @JB Nizet answer,

To Provide our own string representation, we have to override toString() in our class which is highly recommended because

There are some classes in which toString() is overridden already to get the proper string representation.

Examle: String, StringBuffer, StringBuilder and all wrapper classes

    Integer ob1 = new Integer("10");
    String ob2 = new String("Doltan Roy");
    StringBuffer ob3 = new StringBuffer("The Rock");
    StringBuilder ob4 = new StringBuilder("The Joshua");

    System.out.println(ob1);
    System.out.println(ob2);
    System.out.println(ob3);
    System.out.println(ob4);

Output:

10

Doltan Roy

The Rock

The Joshua

Hope this would help!

Related