|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Sometimes, you need to convert a number to a string because you need to operate on the value in its string form. All classes inherit a method calledtoStringfrom theObjectclass. The type-wrapper classes override this method to provide a reasonable string representation of the value held by the number object. The following program,ToStringDemo, uses the
toStringmethod to convert a number to a string. Next, the program uses some string methods to compute the number of digits before and after the decimal point:The output of this program is:public class ToStringDemo { public static void main(String[] args) { double d = 858.48; String s = Double.toString(d); int dot = s.indexOf('.'); System.out.println(s.substring(0, dot).length() + " digits before decimal point."); System.out.println(s.substring(dot+1).length() + " digits after decimal point."); } }The3 digits before decimal point. 2 digits after decimal point.toStringmethod called by this program is the class method. Each of the number classes has an instance method calledtoString, which you call on an instance of that type.You don't have to explicitly call the
toStringmethod to display numbers with theSystem.out.printlnmethod or when concatenating numeric values to a string. The Java platform handles the conversion by callingtoStringimplicitly.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.