Developer Forums | About Us | Site Map
Search  
HOME > TUTORIALS > SERVER SIDE CODING > JAVA TUTORIALS > TAMING TIGER: FORMATTED OUTPUT


Sponsors





Useful Lists

Web Host
site hosted by netplex

Online Manuals

Taming Tiger: Formatted output
By John Zukowski - 2004-05-03 Page:  1 2 3 4 5

PrintStream support

The PrintStream class contains the definition of the common System.out and System.err objects for writing to standard output and standard error, respectively. Introduced in Tiger are two new constructors (for going straight to a file) and six methods for formatting support (three sets of pairs). The first pair is different versions of the append() method. This pair implements the new java.lang.Appendable interface. You would typically not call these methods directly. The ones you would call directly are format() and printf(), where the printf() versions are just convenience wrappers for the format() versions, as shown in Listing 4:

Listing 4. PrintStream.format methods

public PrintStream format(String format,
                          Object... args) 
public PrintStream format(Locale l,
                          String format,
                          Object... args) 

Keep in mind the new variable argument support, which is designated by the ... shown in Listing 4 above.

Listing 5 demonstrates the use of the format() method of PrintStream to print today's date:

Listing 5. Example PrintStream.format usage
/
import java.util.Calendar;

public class Now {
  public static void main(String args[]) {
    System.out.format(
        "Today is %1$tB %1$te, %1$tY.",
        Calendar.getInstance()
        );
  }
}

The output from running this program is Today is April 2, 2004., although the actual output depends on the date you run the program. The %1$tB formatting string in the code above tells the program to use the first argument and print out the full month name for the date object. The %1$te formatting string means to display the day of the month and the %1$tY formatting string is for the four-digit year. Other options for printing dates and times are shown in the Javadoc for the Formatter object.



View Taming Tiger: Formatted output Discussion

Page:  1 2 3 4 5 Next Page: String support

First published by IBM developerWorks


Copyright 2004-2024 GrindingGears.com. All rights reserved.
Article copyright and all rights retained by the author.