Java Reference
In-Depth Information
To convert an array of characters into a string, use the String(char[]) constructor or
the valueOf(char[]) method. For example, the following statement constructs a string
from an array using the String constructor.
String str = new String( new char []{ 'J' , 'a' , 'v' , 'a' });
The next statement constructs a string from an array using the valueOf method.
valueOf
String str = String.valueOf( new char []{ 'J' , 'a' , 'v' , 'a' });
9.2.10 Converting Characters and Numeric Values to Strings
The static valueOf method can be used to convert an array of characters into a string. There
are several overloaded versions of the valueOf method that can be used to convert a charac-
ter and numeric values to strings with different parameter types, char , double , long , int ,
and float , as shown in Figure 9.9.
overloaded valueOf
java.lang.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(c: char): String
+valueOf(data: char[]): String
+valueOf(d: double): String
+valueOf(f: float): String
+valueOf(i: int): String
+valueOf(l: long): String
+valueOf(b: boolean): String
Returns a string representing the boolean value.
F IGURE 9.9 The String class contains the static methods for creating strings from primi-
tive 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' .
Note
You can use Double.parseDouble(str) or Integer.parseInt(str) to con-
vert a string to a double value or an int value. Double and Integer are two classes
in the java.lang package.
9.2.11 Formatting Strings
The String class contains the static format method to create a formatted string. The syntax
to invoke this method is:
String.format(format, item1, item2, ..., itemk)
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, ..., itemk);
 
Search WWH ::




Custom Search