toString() method that is declared and implemented in Object class that returns a string representation of the object.
whenever an object is concatenated with a string, using the “+” operator, the Java compiler automatically invokes the toString method to obtain a string representation of the object.
For example:
Point p = new Point(10, 20);
String message = "The current position is " + p; // automatically invokes p.toString()
If x is any object and you callSystem.out.println(x);
then the println method simply calls x.toString() and prints the resulting string.
Object's toString method:
The Object class defines the toString method to print the class name and the memorylocation of the object. For example, the call
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
For example, the call:System.out.println(System.out);
produces an output that looks like this:
java.io.PrintStream@2f6684
The reason is that the implementor of the PrintStream class didn't bother to override the toString method.
0 comments:
Post a Comment