toString() In Java Example
Chapter:
String Handling
Last Updated:
10-06-2017 12:19:30 UTC
Program:
/* ............... START ............... */
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
public String toString() {
return "Dimensions are " + width + " by " + depth + " by " + height + ".";
}
}
public class JavaStringConversionUsingToString {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s);
}
}
/* ............... END ............... */
Output
Dimensions are 10.0 by 14.0 by 12.0.
Box b: Dimensions are 10.0 by 14.0 by 12.0.
Notes:
-
toString() method returns the string representation of the object.
- By overriding the toString() method of the Object class, you can write your own string content to return.
- Implementing toString method in java is done by overriding the Object’s toString method. The java toString() method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String representation of the Object.
Tags
toString(), Java