0

In C++, one can implement the ostream operator << to be able to define how a class can be output to the stream cout << Class.

Is it possible in java to do something like out.println(Class)?

6
  • 1
    toString helps you Commented Mar 16, 2016 at 13:02
  • 1
    override toString method for you object Commented Mar 16, 2016 at 13:03
  • 2
    why is OP downvoted? he comes from C++ Commented Mar 16, 2016 at 13:05
  • @AndrewTobilko Can't do C++ developers any research? Commented Mar 16, 2016 at 13:10
  • I'd down vote your comment for terrible structure. I tried 'java override println' and 'java overload operator" and a few others. Didn't find a solution. Commented Mar 16, 2016 at 13:12

1 Answer 1

6

System.out.print() calls the toString() method of the object passed to it. If you override the toString() method in your class, you can implement a custom behaviour there. Your class inherit the method from Object. Every class has Object as a superclass in java. Below is the default implementation.

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

The print method (System.out.print(Object obj)) looks like this

public void print(Object obj) {
    write(String.valueOf(obj));
}

and the String.valueOf(Object obj) method finally calls toString().

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Appreciate the answer! Works perfectly :D

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.