Python | Java |
The str function converts any object to its string representation.
Example: str(3.14) # returns ‘3.14’ This function can be customized to return the appropriate string for objects of any programmer-defined class by including an __str__ method. When the __str__ method is available, operations such as print automatically use it to obtain an object’s string representation. Example: NUM_GRADES = 5 def __init__(self, name): def __str__(self): Usage: s1 = Student(‘Mary’) |
The toString() method returns the string representation of an object. A default implementation of this method is included in the Object class. This implementation returns a string containing the name of the object’s class and its hash code. Thus, if the programmer does not include toString in a given class, the default is used via inheritance (Object is the ancestor class of all objects).Operations such as println and + automatically call toString with objects to obtain their string representations.
The header of toString is public String toString() Example: public class Student{ public static final int NUM_GRADES = 5; private String name; public Student(String name){ public String toString(){ Usage: s1 = new Student(“Mary”); |