×
☰ See All Chapters

toString() method in Java

  1. If you want to represent any object as a string, toString() method comes into picture. 

  2. The toString() method returns the string representation of the object. 

  3. 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-in-java-0
 

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
Author