Printing Strings and Characters

The c and s conversion characters are used to print individual characters and strings, respectively. Conversion character s can also print objects with the results of implicit calls to method toString. Conversion character c and C requires a char argument. Conversion character s and S can take a String or any Object (this includes all subclasses of Object) as an argument. When an object is passed to the conversion character s, the program implicitly uses the object's toString method to obtain the String representation of the object. When conversion characters C and S are used, the output is displayed in uppercase letters. The program shown in Fig. 28.5 displays characters, strings and objects with conversion characters c and s. Note that autoboxing occurs at line 10 when an int constant is assigned to an Integer object. Line 15 associates an Integer object argument to the conversion character s, which implicitly invokes the toString method to get the integer value. Note that you can also output an Integer object using the %d format specifier. In this case, the int value in the Integer object will be unboxed and output.

Figure 28.5. Using character and string conversion characters.

(This item is displayed on page 1332 in the print version)

1 // Fig. 28.5: CharStringConversion.java 2 // Using character and string conversion characters. 3 4 public class CharStringConversion 5 { 6 public static void main( String args[] ) 7 { 8 char character = 'A'; // initialize char 9 String string = "This is also a string"; // String object 10 Integer integer = 1234; // initialize integer (autoboxing) 11 12 System.out.printf( "%c ", character ); 13 System.out.printf( "%s ", "This is a string" ); 14 System.out.printf( "%s ", string ); 15 System.out.printf( "%S ", string ); 16 System.out.printf( "%s ", integer ); // implicit call to toString 17 } // end main 18 } // end class CharStringConversion  

A This is a string This is also a string THIS IS ALSO A STRING 1234  

Common Programming Error 28.1

Using %c to print a string causes an Illegal FormatConversionExceptiona string cannot be converted to a character.

Категории