Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

840 Part II: The Java Library


You can try this example without actually having a remote server. To do so, simply
install all of the programs on the same machine, startrmiregistry, startAddServer, and
then executeAddClientusing this command line:

java AddClient 127.0.0.1 8 9

Here, the address 127.0.0.1 is the “loop back” address for the local machine. Using this
address allows you to exercise the entire RMI mechanism without actually having to install
the server on a remote computer.
In either case, sample output from this program is shown here:

The first number is: 8
The second number is: 9
The sum is: 17.0

Text Formatting
The packagejava.textallows you to format, search, and manipulate text. Chapter 32 illustrates
itsNumberFormatclass, which is used to format numeric data. This section examines two
more of its most commonly used classes: those that format date and time information.

DateFormat Class

DateFormatis an abstract class that provides the ability to format and parse dates and
times. ThegetDateInstance( )method returns an instance ofDateFormatthat can format
date information. It is available in these forms:

static final DateFormat getDateInstance( )
static final DateFormat getDateInstance(intstyle)
static final DateFormat getDateInstance(intstyle, Localelocale)

The argumentstyleis one of the following values:DEFAULT,SHORT,MEDIUM,LONG,
orFULL. These areintconstants defined byDateFormat. They cause different details about
the date to be presented. The argumentlocaleis one of the static references defined byLocale
(refer to Chapter 18 for details). If thestyleand/orlocaleis not specified, defaults are used.
One of the most commonly used methods in this class isformat( ). It has several
overloaded forms, one of which is shown here:

final String format(Dated)

The argument is aDateobject that is to be displayed. The method returns a string containing
the formatted information.
The following listing illustrates how to format date information. It begins by creating
aDateobject. This captures the current date and time information. Then it outputs the date
information by using different styles and locales.

// Demonstrate date formats.
import java.text.*;
import java.util.*;

public class DateFormatDemo {
public static void main(String args[]) {
Date date = new Date();
Free download pdf