Java Reference
In-Depth Information
number into a string is to use the overloaded static valueOf method. This method can also be
used to convert a character or an array of characters into a string, as shown in Figure 10.17.
overloaded valueOf
java.lang.String
+valueOf(c: char): String
+valueOf(data: char[]): String
+valueOf(d: double): String
+valueOf(f: float): String
+valueOf(i: int): String
+valueOf(l: long): String
Returns a string consisting of the character c .
Returns a string consisting of the characters in the array.
Returns a string representing the double value.
Returns a string representing the float value.
Returns a string representing the int value.
Returns a string representing the long value.
+valueOf(b: boolean): String
Returns a string representing the boolean value.
F IGURE 10.17
The String class contains the static methods for creating strings from prim-
itive type values.
For example, to convert a double value 5.44 to a string, use String.valueOf(5.44) .
The return value is a string consisting of the characters '5' , '.' , '4' , and '4' .
10.10.7 Formatting Strings
The String class contains the static format method to return a formatted string. The syntax
to invoke this method is:
String.format(format, item1, item2, ..., item k )
This method is similar to the printf method except that the format method returns a for-
matted string, whereas the printf method displays a formatted string. For example,
String s = String.format( "%7.2f%6d%-4s" , 45.556 , 14 , "AB" );
System.out.println(s);
displays
45.56
14AB
Note that
System.out.printf(format, item1, item2, ..., item k );
is equivalent to
System.out.print(
String.format(format, item1, item2, ..., item k ));
where the square box ( ) denotes a blank space.
10.15
Suppose that s1 , s2 , s3 , and s4 are four strings, given as follows:
Check
Point
String s1 = "Welcome to Java" ;
String s2 = s1;
String s3 = new String( "Welcome to Java" );
String s4 = "Welcome to Java" ;
What are the results of the following expressions?
a. s1 == s2
b. s1 == s3
 
 
Search WWH ::




Custom Search