Print Object of a Class in Java

Exercise:

Write a Java Program to print object of a class.

Click Here to View the Solution!
class TestClass {
}
public class Main {
    public static void main(String[] args) {

        // create an object of the Testclass
        TestClass obj = new TestClass();

        // print the object
        System.out.println(obj);
    }
}
Click Here to View the Output!
TestClass@6a6824be
Click Here to View the Explanation!
  • This program will help in understanding the method of printing the value of a class object.
  • In the following example we have created a TestClass, which does not contain any method initially.
  •  In the Main method, we instantiate an object of TestClass.
  • But when we try to print this object, although no error occurs, the type of the value turns out to be in hash-code form.
  • As the default format employed by toString() method is in hash-code.
  • Therefore, we require overriding technique to convert the return type into string format.
  • This time we create our own toString() method in TestClass and override it using @Override key word.
  • The return value will be object- a string, now.

%d bloggers like this: