Monday 1 April 2019

What happens when we print object in Java?

               In this post, we will see "What happens when we print object in Java?". Many programmers have this curiosity.


Look at the following code:

Program (Sample.java)
class Test
{
Test()
{
System.out.println("Hello PICT");
}
}

class Sample
{
public static void main(String args[])
{
Test b=new Test();
System.out.println(b);
}
}
  
output (Sample.java)
parag@parag-Inspiron-N4010:~/Desktop$ javac Sample.java
parag@parag-Inspiron-N4010:~/Desktop$ java Sample
Hello PICT
Test@2a139a55

                     Look at the output. Here we got Hello PICT from constructor execution. While, when we print object, we got Test@2a139a55. Here, Test is the class name of object b and 2a139a55 is the hexadecimal representation of hash code of object.

Explanation
                   Every class in Java is inherited by standard class java.lang.Object. That means, every class in Java is a subclass of class java.lang.Object. This Object class has predefined method toString().

prototype: 
public String toString()

                   If we do not override this method in our class, then we get the default execution of this method mentioned in Object class. It returns: 
getClass().getName() + '@' + Integer.toHexString(hashCode())
i.e. class name followed by '@' followed by hexadecimal representation of hash code of the object.

                   If we want our own message instead of this output, then we have to override method toString().


                   Go through the following code:

Program (Sample.java)
class Test
{
Test()
{
System.out.println("Hello PICT");
}

public String toString()
{
return "Hello World";
}

}

class Sample
{
public static void main(String args[])
{
Test b=new Test();
System.out.println(b);
}
}
  
output (exception.cpp)
parag@parag-Inspiron-N4010:~/Desktop$ javac Sample.java
parag@parag-Inspiron-N4010:~/Desktop$ java Sample
Hello PICT
Hello World

                      Look at the output. Here, when we print an object, we got Hello World which is returned by toString() method.

                      Thank you for reading this post. All the best.

No comments:

Post a Comment