☰ See All Chapters |
toString() method in Java
If you want to represent any object as a string, toString() method comes into picture.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
toString() method example
class A { void meth() { System.out.println(" class A"); } }
class StringHandling { public static void main(String args[]) { A a = new A(); System.out.println(a.toString()); StringBuffer s = new StringBuffer("AdiTemp"); String s1 = s.toString(); System.out.println(s1); } } |
Output:
A@6e818805 AdiTemp |
All Chapters