toString( )
The toString( ) method has this general form:
String toString( )
By overriding toString( ) for classes that you create, you allow them to be fully integrated into Java's programming environment.
The System.out.println() calls the toString method from Rectangle to get the string representation of the rectangle instance.
class Rectangle {
double width;
double height;
Rectangle(double w, double h) {
width = w;
height = h;
}
public String toString() {
return "Dimensions are " + width + " by " + height + ".";
}
}
public class Main {
public static void main(String args[]) {
Rectangle b = new Rectangle(10, 12);
String s = "Rectangle b: " + b; // concatenate Rectangle object
System.out.println(b); // convert Rectangle to string
System.out.println(s);
}
}
The output of this program is shown here:
Dimensions are 10.0 by 12.0.
Rectangle b: Dimensions are 10.0 by 12.0.
Home
Java Book
Essential Classes
Java Book
Essential Classes
String:
- String type and Literals
- String Concatenation
- String.CASE_INSENSITIVE_ORDER
- String Constructor
- charAt(int index):Get a single char by index
- String: compareTo(String stringValue)
- concat(String str)
- equals():Compare two string value for equality
- equals( ) vs ==
- contains(CharSequence s)
- copyValueOf(char[] data)
- endsWith(String suffix)
- format():Format a string
- getBytes():Get byte array from string
- getChars()
- indexOf
- intern a string
- isEmpty:if string is empty
- lastIndexOf()
- length() Returns the length of this string
- startsWith( )
- toLowerCase() and toUpperCase(): convert string case with locale
- substring:Get sub string from a string
- toCharArray():Get char array from string
- toString( )
- trim()
- valueOf():Convert boolean, char, double, float,int,long,object to String