1. Explain about toString() metho of Object class?


     public String toString()

    Returns a string representation of the object

      We can use toString() method to get String representation of an Object.

    Whenever we are trying to print any object reference then internally toString() method will be executed.

   In java.lang package Object class contains toString() method as non-final method.

  The toString() method of Object class returns ClassName@hashCodeInHexadecimalNotation.

   As Object class is super class for every method so it is inherited into every java class.

 The toString method is non-final method every class can override this method.

   Whenever we are displaying a ref on the monitor using println() or print() methods and if the reference is not pointing null then these methods internally call toString() on the ref and prints the result of toString().

   If reference is pointing null then NullPointerException is not generated only null is printed.

  If our class is overriding toString() then our class toString() return value is printed.

   If  our class is not overriding toString() then Object class toString() return value is printed i.e.,    ClassName@hashCodeInHexadecimalNotation.

Example: without toString() method

//StudentDemo.java

public class StudentDemo{

String name;

Int rollno;

Student(String name,  Int rollno){

this.name = name;

this.rollno = rollno;

}

public static void main(String[] args){

Student s1 = new Student(“durga”,101);

Student s2= new Student(“nag”,102);

System.out.println(s1);

System.out.println(s2);

//System.out.println(s1.toString());

}//main

}//class

javac StudentDemo.java

java StudentDemo

OUTPUT:

StudentDemo@3e25a5

StudentDemo@19821f

Example: with toString() method

//TestDemo.java

public class TestDemo{

public String toString(){

return “TestDemo object”

}

public static void main(String[] args){

String s = new String(“durga”);

Integer I = new Integer(10);

TestDemo t = new TestDemo();

System.out.println(s);

System.out.println(I);

System.out.println(t);

}//main

}//class

javac TestDemo.java

java TestDemo

OUTPUT:

Durga

10

TestDemo object