Pages

toString() in java

toString() in java ?

We can use toString() method to get string representation of an object.

String s = object.toString();

whenever we are trying to print object reference internally toString() will be invoked from object.class.

Demo on toString() method:
public class StringDemo {
    public static void main(String[] args) {
        StringDemo sd = new StringDemo();
        System.out.println(sd);
        System.out.println(sd.toString()); //toString() method invoked from object.class
    }
}
Output:
StringDemo@378bf509
StringDemo@378bf509
If we execute above progam toString() will be invoked from object class and toString() will return 
 classname+"@"+hashcode in hexa decimal format.
Implementation of toString() method in object.class:

public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
So, if a class doesn't contain toString() method then object.toString() method will be invoked.
toString() method
toString() method in java
Based on our requirement we can override the toString() method.
public class StringDemo { public String toString() { return "toString() method overrided"; } public static void main(String[] args) { StringDemo sd = new StringDemo(); System.out.println(sd); System.out.println(sd.toString()); } }
Output:
toString() method overrided
toString() method overrided If we observe above program, toString() method will be checked in class if it is available then it will invoked otherwise it will invoked from object.class. Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.