What is toString() method of object class in java:
The toString
method in Java is a member of the Object
class and is used to return a string representation of an object.
By default, the toString
method provides a string that includes the class name and the memory address of the object.
Default Implementation of toString
:
The toString
method is defined in the Object
class as follows:
Purpose of Overriding toString
:
The default implementation is not very informative for most use cases. Therefore, it is common to override the toString
method in custom classes to provide meaningful and human-readable information about the object's state.
Example: Default Behavior:
public class Main {
public static void main(String[] args)
{
Object obj = new Object();
System.out.println(obj.toString());
}
}
Output:
java.lang.Object@<hashCode>
The <hashCode>
part is the hexadecimal representation of the object's hash code.
Example: Overriding toString
Here's how you might override the toString
method in a custom class:
Comments
Post a Comment