0% found this document useful (0 votes)
10 views

Murach's Java Programming

This document discusses working with dates and strings in Java. It covers using the GregorianCalendar class to set dates and times, manipulating dates using Calendar and GregorianCalendar fields and methods, formatting dates with DateFormat, and working with the String and StringBuilder classes.

Uploaded by

H. Đông Hoàng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Murach's Java Programming

This document discusses working with dates and strings in Java. It covers using the GregorianCalendar class to set dates and times, manipulating dates using Calendar and GregorianCalendar fields and methods, formatting dates with DateFormat, and working with the String and StringBuilder classes.

Uploaded by

H. Đông Hoàng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

13

How to work with


dates and strings
In section 1 of this book, you learned some basic skills for working with
strings. In this chapter, you’ll learn more about working with strings, and you’ll
learn how to work with dates. Because you’ll use dates and strings in many of
the applications that you develop, you should know how to use all of the skills
presented in this chapter.

How to work with dates and times................................... 406


How to use the GregorianCalendar class to set dates and tim es.................406
How to use the Calendar and GregorianCalendar fields and methods...... 408
How to use the Date class.............................................................................410
How to use the DateFormat class to format dates and times.......................412
A DateUtils class that provides methods for handling dates.......................414
An Invoice class that includes an invoice d ate............................................ 416
How to work with the String class................................... 418
Constructors of the String class....................................................................418
Code examples that create strings................................................................418
Methods of the String class..........................................................................420
Code examples that work with strings......................................................... 422
How to work with the StringBuilder class....................... 424
Constructors and methods of the StringBuilder class................................. 424
Code examples that work with the StringBuilder class............................... 426
Perspective..........................................................................428
406 Section 3 More Java essentials

How to work with dates and times


Although Java doesn’t have a primitive data type for working with dates and
times, it does have several classes that you can use to work with dates and
times. In this topic, you’ll learn how to create objects that store dates and times,
how to manipulate the values stored in those objects, and how to format those
objects.

How to use the GregorianCalendar class


to set dates and times
When you create dates and times, you usually use the GregorianCalendar
class as shown in figure 13-1. Although you might think that a class named after
a calendar would work mainly with dates, this class actually represents a point
in time down to the millisecond.
This figure starts by showing four constructors of the GregorianCalendar
class. The first constructor creates an object that contains the current date and
time. The next three constructors create objects that contain values for a date
and time that you specify. For instance, the second constructor creates a date
and time using integer values for year, month, and day. In this case, Java sets the
hour, minute, and second to 00. However, you can use the third or fourth
constructors to set these values.
The statement in the first example shows how to get the current date and
time. When you call this constructor, it sets the GregorianCalendar object equal
to the current date and time. Java gets this date from your computer’s internal
clock. As a result, the date and time should be set correctly for your time zone.
The two statements in the second example show how to create a date using
literals as arguments in the constructor of the GregorianCalendar class. Here,
the first statement creates a GregorianCalendar object named startDate and sets
the date to January 30, 2009. The second statement creates a GregorianCalendar
object named startTime and sets it to 3:30 PM on July 20, 2012. Notice in both
of these examples that the month is specified as an integer between 0 and 11,
which might not be what you’d expect.
Like the first statement in the second example, the statement in the third
example creates a GregorianCalendar object by supplying just a date. In this
case, though, the year, month, and day are supplied as variables instead of
literals.
When setting times, any values that you don’t set will default to 0. The
exception is if you use the first constructor shown in this figure, in which case
the time is set to the current time. In addition, to set the hour, you must enter an
integer between 0 and 23 where 0 is equal to midnight and 23 is equal to 11 PM.
As a result, the first statement of example 2 and example 3 sets the time to
midnight (12:00:00 AM). The second statement of example 2 sets the hours to
15, which represents 3:00 PM, and the minutes to 30.
Chapter 13 How to work with dates and strings 407

The GregorianCalendar class


j ava.util.GregorianCalendar;

Common constructors of the GregorianCalendar class


Method Description
GregorianCalendar() Creates a GregorianCalendar object set to the
current date and time.
GregorianCalendar ( y e a r , m o n th . Creates a GregorianCalendar object set to the
day ) specified date.
GregorianCalendar ( y e a r , m o n th . Creates a GregorianCalendar object set to the
d a y , h o u r , m in u te ) specified date and time.
GregorianCalendar ( y e a r , m o n th . Creates a GregorianCalendar object set to the
d a y , h o u r , m in u te , se c o n d ) specified date and time.

Example 1: A statement that gets the current date


GregorianCalendar now = new GregorianCalendar() ;

Example 2: Statements that create dates with literals


GregorianCalendar startDate = new GregorianCalendar(2009, 0, 30);
GregorianCalendar startTime = new GregorianCalendar(2012, 6 ,20, 15, 30);

Example 3: A statement that creates a date with variables


GregorianCalendar birthDate =
new GregorianCalendar(birthYear, birthMonth, birthDay);

Description
• Year must be a four-digit integer.
• Month must be an integer from 0 to 11 with 0 being January and 11 being December.
• Day must be an integer from 1 to 31.
• Hour must be an integer from 0 to 23, with 0 being 12 AM (midnight) and 23 being
11PM.
• Minute and second must be integers from 0 to 59.

Figure 13-1 How to use the GregorianCalendar class to set dates and times
408 Section 3 More Java essentials

How to use the Calendar and GregorianCalendar


fields and methods
The GregorianCalendar class is a subclass of the Calendar class. As a result,
it inherits all the public and protected fields and methods of the Calendar class.
Then, the GregorianCalendar class overrides some of the methods of the Calen­
dar class.
Once you create an object from the GregorianCalendar class, you can use
the fields and methods shown in figure 13-2 to work with the object. The
examples in this figure show how to use several of these fields and methods.
Although these examples show how to work with the date portion of a
GregorianCalendar object, you can use the same skills to work with the time
portion. You can also find other fields and methods for working with dates and
times in the API documentation for the Calendar and GregorianCalendar
classes.
The first example shows how to use the set, add, and roll methods to change
the value that’s stored in a GregorianCalendar object. As you can see, you can
use the same arguments for the set method that you used for the constructors of
the GregorianCalendar class. In addition, you can use fields from the Calendar
class, such as JANUARY and FEBRUARY, to set the month. Notice that when
you use the add method to add 14 months to the date, the year is also increased.
In contrast, when you use the roll method to roll the current month forward by
14 months, the year isn’t affected. As a result, it only changes the month from
August to October.
When you manipulate dates and times, you need to make sure to supply
values that make sense. For example, since there are only 30 days in November,
it doesn’t make sense to use 31 as the day argument. If you do that, Java sets the
date to December 1.
The second example shows how to use the get method to return various
integer values that are stored in the GregorianCalendar object. Here, the year is
2010, the month is 1 (February), the day is 4, the day of the week is 5 (Thurs­
day), and the day of the year is 35 (the 31 days of January plus the 4 days of
February).
The other two methods listed in this figure, setTime and getTime, work with
Date objects. The setTime method sets a GregorianCalendar object to the date
specified by a Date object, and the getTime method returns a Date object for a
GregorianCalendar object. You’ll leam more about Date objects in the next
topic.
Chapter 13 How to work with dates and strings 409

The Calendar class


j ava.util.Calendar;

Common fields of the Calendar class


DATE DAYOFMONTH DAYOFWEEK DAYOFYEAR
HOUR HOUROFDAY MINUTE MONTH
SECOND YEAR MONDAY...SUNDAY JANUARY...DECEMBER

Common methods of the Calendar and GregorianCalendar classes


Method Description
set(intYear, intMonth, ...) Sets the values for year, month, day, hour, minute,
and second just as they are set in the constructor
for the GregorianCalendar class.
set(intField, intValue) Sets the specified field to the supplied value.
setTime(Date) Sets the date and time values based on the supplied
Date object.
add(intField, intValue) Adds the supplied value to the specified field.
roll(intField, intValue) Adds the supplied value to the specified field, but
doesn’t affect other fields.
roll(intField, booleanValue) Increments the value of the specified field by 1 for
true values and decrements the value of the field by
1 for false values.
g e t (intField) Returns the int value of the specified field.
getTime() Returns a Date object.

Example 1: Code that changes a GregorianCalendar object


GregorianCalendar endDate = new
GregorianCalendar(2010, 0, 1); // January 1, 2010
endDate.set(2010, 2, 30); // March 30, 2010
endDate.set(2010, Calendar.MARCH, 30); // March 30, 2010
endDate.set(Calendar.MONTH, Calendar.JANUARY); // January 30, 2010
endDate.add(Calendar.MONTH, 5); // June 30, 2010
endDate.add(Calendar.MONTH, 14); // August 30, 2011
endDate.roll(Calendar.MONTH, 14); // October 30, 2011
endDate.roll(Calendar.MONTH, true); // November 30, 2011
endDate.roll(Calendar.DAYOFMONTH, false); // November 29, 2011

Example 2: Code that accesses fields in a GregorianCalendar object


GregorianCalendar birthday = new
GregorianCalendar(2010, Calendar.FEBRUARY, 4); // Thurs, Feb 4, 2010
int year = birthday.get(Calendar.YEAR); // year is 2 01 0
int month = birthday.get(Calendar.MONTH); // month is 1
int day = birthday.get(Calendar.DAY_OF_MONTH); // day is 4
int dayOfWeek = birthday.get(Calendar.DAY_OF_WEEK) // dayOfWeek is 5
int dayOfYear = birthday.get(Calendar.DAY_OF_YEAR) // dayOfYear is 35

Note
• For more information about these and other fields and methods, look up the Calen­
dar and GregorianCalendar classes in the documentation for the Java API.

Figure 13-2 How to use the Calendar and GregorianCalendar fields and methods
410 Section 3 More Java essentials

How to use the Date class


Figure 13-3 shows how to use the Date class. Unlike the GregorianCalendar
class, the Date class doesn’t have fields that represent the year, month, day, and
so on. Instead, the Date class represents a point in time by the number of
milliseconds since January 1, 1970 00:00:00 Greenwich Mean Time (GMT).
You need to use Date objects when you want to format a date as shown in the
next figure. You may also find Date objects useful when you want to perform
arithmetic operations on dates like subtracting one date from another.
To create a Date object, you can invoke the getTime method of a
GregorianCalendar object as shown in the first example in this figure. Since the
getTime method returns a Date object, you don’t need to call either of the Date
constructors. However, you can also use either of the constructors in this figure
to create a Date object. The first constructor creates a Date object for the current
date and time while the second constructor creates a Date object based on the
number of milliseconds that are passed to it. The second example shows how to
use the first constructor to create a Date object for the current date and time.
The third example shows how to use the toString and getTime methods of
the Date class. The toString method returns a readable string that displays the
day of the week, month, date, time, time zone, and year. The getTime method
returns a long integer that represents the number of milliseconds since January
1, 1970 00:00:00 GMT.
The fourth example shows how Date objects can be useful when you want to
calculate the elapsed time between two dates. First, two GregorianCalendar dates
are converted to Date objects using the getTime method of the
GregorianCalendar class. Next, the Date objects are converted to milliseconds
using the getTime method of the Date class. Then, the starting date in millisec­
onds is subtracted from the ending date in milliseconds to get the elapsed milli­
seconds, and that result is divided by the number of milliseconds in a day to get
the elapsed days. This type of routine is useful in many business programs.
Chapter 13 How to work with dates and strings

The Date class


java.util.Date;

Common constructors
Constructor Description
Date () Creates a Date object for the current date and time based
on your computer’s internal clock.
D a t e ( l o n g M i l li s e c o n d s ) Creates a Date object based on the number of milliseconds
that is passed to it.

Common methods
Method Description
getTime () Returns a long value that represents the number of milliseconds for the date.
toString () Returns a String object that contains the date and time formatted like this:
Wed Aug 04 08:31:25 PDT 2009.

Example 1: A statement that converts a GregorianCalendar object to


a Date object
Date endDate = gregEndDate.getTime();

Example 2: A statement that gets a Date object for the current date/time
Date now = new D a t eO ;

Example 3: Statements that convert Date objects to string


and long variables
String nowAsString = now.toString(); // converts to a string
long nowInMS = now.getTime(); // converts to milliseconds

Example 4: Code that calculates the number of days between two dates
Date startDate = gregStartDate.getTime();
Date endDate = gregEndDate.getTime();
long startDateMS = startDate.getTime();
long endDateMS = endDate.getTime();
long elapsedMS = endDateMS - startDateMS;
long elapsedDays = elapsedMS / (24 * 60 * 60 * 1000) ;

Description
• A Date object stores a date and time as the number of milliseconds since January 1,
1970 00:00:00 GMT (Greenwich Mean Time).
• You need to convert GregorianCalendar objects to Date objects when you want to
use the DateFormat class to format them as shown in the next figure.
• Date objects are also useful when you want to calculate the number of milliseconds
(or days) between two dates.

Figure 13-3 How to use the Date class


412 Section 3 More Java essentials

How to use the DateFormat class


to format dates and times
Figure 13-4 shows how to use the DateFormat class to convert a Date object
to a string that you can use to display dates and times. In addition, it shows how
to control the format of these strings. Since this class works similarly to the
NumberFormat class, you shouldn’t have much trouble using it.
Before you can format a date, you need to use one of the static methods of
the DateFormat class to create a DateFormat object that has a particular format.
When you do that, you can choose to return the date only, the time only, or the
date and time. If you don’t specify a format, the DateFormat object will use the
default format. However, you can use one of the four DateFormat fields to
override the default date format. Once you’ve created a DateFormat object that
has the format you want, you can use its format method to apply the specified
format to a Date object.
The first example shows how to format a Date object with the default
format. Here, the getDateTimelnstance method is used to return both date and
time. Since no arguments are supplied for this method, it will return a string that
contains the current date and time with the default format, which should look
something like this:
Jan 30, 2010 12:10:10 PM
The second example shows how to format a GregorianCalendar object with
the default date format. Here, you can see that you start by using the getTime
method to convert the GregorianCalendar object to a Date object. Then, you use
the getDatelnstance method to return a format with the date only. Since no
arguments are supplied for this method, it will return a string that contains this
date:
Dec 31, 2010
The third example shows how you can use the fields of the DateFormat
class to override the default date format. Here, you can see how to use the
SHORT field, but the same skills apply to the other three fields. If you use the
getDateTimelnstance method, you need to supply the first argument for the date
and the second argument for the time. Since both of the arguments are specified
as short in this example, they will return a date with a format something like
this:
12/31/10 7:30 AM
When you use the LONG and FULL fields, the time portion of the date will
end with an abbreviation for the current time zone. In this figure, the examples
use the Pacific Standard Time (PST) time zone.
Chapter 13 How to work with dates and strings 413

The DateFormat class


j ava.text.DateFormat;

Common static methods


Method Description
getDatelnstance() Returns a DateFormat object with date, but not time.
getTimelnstance() Returns a DateFormat object with time, but not date.
getDateTimelnstance() Returns a DateFormat object with date and time.
getDatelnstance(intField) Same as above, but you can use the fields shown below to
override the default date format.
getTimelnstance(intField) Same as above, but you can use the fields shown below to
override the default time format.
getDateTimelnstance(intField, Same as above, but you can use the fields shown below to
intField) override the default date and time formats.

Common fields
Style Date example Time example
SHORT 12/31/10 12:00 AM
MEDIUM Dec 31, 2010 7:30:00 PM
LONG December 31, 2010 7:30:00 AM PST
FULL Saturday, December 31, 2010 7:30:00 AM PST

Common method
Method Description
format (Date) Returns a String object of the Date object with the
format that’s specified by the DateFormat object.

Example 1: Code that formats a Date object


Date now = new D a t eO ;
DateFormat defaultDate = DateFormat.getDateTimelnstance() ;
String nowString = defaultDate.format(now);

Example 2: Code that formats a GregorianCalendar object


GregorianCalendar gregEndDate = new GregorianCalendar(2010,11,31,7,30);
Date endDate = gregEndDate.getTime();
DateFormat defaultDate = DateFormat.getDatelnstance();
String endDateString = defaultDate.format(endDate);

Example 3: Code that overrides the default date and time formats
DateFormat shortDate = DateFormat.getDatelnstance(DateFormat.SHORT);
DateFormat shortTime = DateFormat.getTimelnstance(DateFormat.SHORT);
DateFormat shortDateTime =
DateFormat.getDateTimelnstance(DateFormat.SHORT, DateFormat.SHORT);

Description
• You can use the DateFormat class to format Date objects in various ways.

Figure 13-4 How to use the DateFormat class to format dates and times
414 Section 3 More Java essentials

A DateUtils class that provides methods


for handling dates
Although the date handling features of the Java API are powerful, they must
frequently be used in combination to provide some of the most common opera­
tions needed by business applications. As a result, it’s common for an applica­
tion that uses dates to include a class like the one in figure 13-5. This class
presents just a few of the date handling operations you may need to perform, but
it should give you a good idea of what you can do with the date handling
features.
In the DateUtils class, the getCurrentDate method returns a Date object that
contains just the current date. To do that, it creates a GregorianCalendar object
with the current date and time. Then, it uses the set method to set the hour,
minute, and second to zero. Finally, it uses the getTime method to convert the
GregorianCalendar object to a Date object. You might want to use a method like
this to get a date that you can use to calculate the age of an invoice. In that case,
you’ll want to be sure that neither the invoice date or the current date contains a
time so the age is calculated properly.
The createDate method provides a simple way to create a Date object for a
specific date with the hour, minute, and second set to zero. This method starts
by creating a GregorianCalendar object for the specified date. Then, it uses the
getTime method to convert the GregorianCalendar object to a Date object.
The stripTime method strips the hour, minute, and second from a Date
object. It works by setting a GregorianCalendar object to the date and time
specified by the Date object so the hour, minute, and second can be accessed.
Then, it sets these values to zero and converts the result back to a Date object.
The daysDiff method calculates the difference between two Date objects in
days. To do that, it starts by calling the stripTime method to remove the time-of-
day component from both Date objects. That’s important when you’re working
with Date objects that include times, because you don’t want the time of day to
be considered in the calculation.
Next, the daysDiff method uses the getTime method to convert the Date
objects to long values. Then, it subtracts these two values to get the difference,
which is expressed in milliseconds. To convert that value to days, it divides it by
the number of milliseconds in a day, which is represented by the constant
named MILLS_IN_DAY that’s defined at the top of the class.
The code example at the bottom of this figure shows how you might use the
DateUtils class in a simple application. This example determines the number of
days between the current date and Christmas. The first two lines get the current
date and then extract the current year using the get method. Next, a Date object
named currentDate is set to the current date and another Date object named
Christmas is set to December 25 of the current year. Then, an int variable named
daysToChristmas is calculated by calling the daysDiff method. The rest of the
code formats and displays the result.
Chapter 13 How to work with dates and strings 415

The code for the DateUtils class


import java.util.*;

public class DateUtils {


static final int M I L L S I N D A Y = 24 * 60 * 60 * 1000;

public static Date getCurrentDate() {


GregorianCalendar currentDate = new GregorianCalendar();
currentDate.set(Calendar.HOUR, 0);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
return currentDate.getTime();
}
public static Date createDate(int year, int month, int day) {
GregorianCalendar date = new GregorianCalendar(year, month, day);
return date.getTime();
}
public static Date stripTime(Date date) {
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.setTime(date);
currentDate.set(Calendar.HOUR, 0);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
return currentDate.getTime();
}
public static int daysDiff(Date datel. Date date2) {
datel = stripTime(datel);
date2 = stripTime(date2);
long longDatel = datel.getTime();
long longDate2 = date2.getTime();
long longDiff = longDate2 - longDatel;
return (int) (longDiff / M I L L S I N D A Y ) ;
}
}
Code that uses some of the DateUtils methods
GregorianCalendar currentGC = new GregorianCalendar();
int currentYear = currentGC.get(Calendar.YEAR);

Date currentDate = DateUtils.getCurrentDate();


Date Christmas = DateUtils.createDate(currentYear, Calendar.DECEMBER, 25);
int daysToChristmas = DateUtils.daysDiff(currentDate, Christmas);

DateFormat dateFormat = DateFormat.getDateinstance(DateFormat.LONG) ;


String formattedDate = dateFormat.format(currentDate);
System.out.println("Today is " + formattedDate);
System.out.println("There are " + daysToChristmas + " days until Christmas.");

Resulting output
f( Today is July 11, 2011 ^
II There are 166 days until Christmas. J

Figure 13-5 A DateUtils class that provides methods for handling dates
416 Section 3 More Java essentials

An Invoice class that includes an invoice date


To show how you can use some of the date skills you just learned, figure
13-6 shows how to add a date to the Invoice class that was presented in chapter
12. The constructor for this class sets the invoice date, which is declared as a
Date object, to the current date. To do that, it uses the getCurrentDate method of
the DateUtils class so that the invoice date doesn’t include a time.
Two methods have also been added to this class to provide access to the
invoice date. The getlnvoiceDate method simply returns the invoice date as a
Date object. The getFormattedDate method applies a short date format to the
invoice date and returns it as a string.
To make the date classes available to this class, the two import statements at
the beginning of the class have been changed. Now, instead of just importing the
NumberFormat class of the java.text package and the ArrayList class of the
java.util package, they import all of the classes in these packages. That way, the
DateFormat class is available from the java.text package, and the
GregorianCalendar, Calendar, and Date classes are available from the java.util
package.
Chapter 13 How to work with dates and strings 417

Code that adds a date to the Invoice class


import j ava.text.* ;
import java.util.*;

public class Invoice


{
private ArrayList<LineItem> linelterns;
private Date invoiceDate;

public Invoice()
{
lineltems = new A r r a y L i s t o () ;
invoiceDate = DateUtils.getCurrentDate();
}
public ArrayList<LineItem> getLinelterns()
{
return lineltems;
}
public void addltem(Lineltem lineltem)
{
this.lineltems.add(lineltem);
}
public double getlnvoiceTotal()
{
double invoiceTotal = 0 ;
for (Lineltem lineltem : this.lineltems)
{
invoiceTotal += lineltem.getTotal();
}
return invoiceTotal;
}
public String getFormattedTotal()
{
NUmberFormat currency = NumberFormat.getCurrencylnstance();
return currency.format(this.getlnvoiceTotal());
}
public Date getlnvoiceDate()
{
return invoiceDate;
}
public String getFormattedDate()
{
DateFormat shortDate = DateFormat.getDatelnstance(DateFormat.SHORT);
return shortDate.format(invoiceDate);
}
}

Figure 13-6 An Invoice class that includes an invoice date


418 Section 3 More Java essentials

How to work with the String class


In section 1, you learned how to create a String object and how to use two
methods of the String class that compare two strings. Now, you’ll leam some
new ways to create String objects, and you’ll leam how to use more of the
methods of the String class.

Constructors of the String class


Figure 13-7 shows three constructors of the String class. The first construc­
tor provides another way to create an empty string, and the second and third
constructors allow you to create a string from an array of char or byte types.
Although none of these constructors are commonly used, the second and third
constructors show that you can think of a string as an array of Unicode charac­
ters.
You may remember from chapter 3 that char is a primitive type that can
hold a Unicode character with two bytes used for each character. That provides
for over 65,000 unique characters. Now, you’ll leam that a String variable can
store an array of these Unicode characters.

Code examples that create strings


The first two examples in this figure show how to create a string. In ex­
ample 1, the first statement uses the shorthand notation you learned how to use
in chapter 2. Then, the second statement shows how to do the same task using a
constructor of the String class. In example 2, the first statement initializes the
new string from a string literal, and the second statement initializes it from a
variable.
The third example creates a string from an array of characters. Here, the
second statement converts the entire array of characters to a string named
cityStringl. Then, the third statement converts the first three characters in the
array to a string named cityString2. Although there’s little reason to create a
string in this way, we included this example to demonstrate that an array of
characters can be converted to a string. Note that literal char values must be
enclosed in single quotes, not double quotes the way string literals are.
The fourth example creates a string from an array of bytes. Here, the first
statement creates an array of bytes that represents the same characters as the
characters that are used in the third example. That’s because every character in
the ASCII character set corresponds to a byte value. For example, the byte value
of 68 represents the character D. Then, the second and third statements in this
example work just like they did in the previous example.
Chapter 13 How to work with dates and strings 419

The String class


j ava.lang.String;

Common constructors of the String class


Constructor Description
String() Creates an empty string ("").
String (array N am e) Creates a string from an array of char or byte types.
String (a rray N am e, in tO ffs e t, Creates a string from a subset of an array of char or
in tL e n g th ) byte types.

Example 1: Two ways to create an empty string


String name = " " ;
String name = new String();

Example 2: Two ways to create a string from another string


String title = "Murach's Beginning Java";
String title = bookTitle;

Example 3: Two ways to create a string from an array of characters


char cityArray[] = {'D', 'a', Ί ' , Ί ' , 'a', 's'};
String cityStringl =new String(cityArray);
String cityString2 =new String(cityArray, 0, 3);

Example 4: Two ways to create a string from an array of bytes


byte cityArray[] = {6 8 , 97, 108, 108, 97, 115};
String cityStringl =new String(cityArray);
String cityString2 =new String(cityArray, 0, 3);

Notes
• For the third constructor shown above, the characters referred to by the intOffset
and intLength arguments must fall within the array. Otherwise, the constructor will
throw an IndexOutOfBoundsException.
• A char data type contains a single Unicode character, which is stored in two bytes.
When you use the second and third constructors above, you can construct a String
object from an array of char types. To code a literal char value, you use single
quotes instead of double quotes as shown in the third example.
• Because a byte data type can hold the Unicode value for every character in the
ASCII character set, you can also construct a String object from an array of bytes
as shown in the fourth example.
• Since String objects are immutable, they can’t grow or shrink. Later in this chapter,
you’ll learn how to work with StringBuilder objects that can grow and shrink.

Figure 13-7 How to create strings


420 Section 3 More Java essentials

Methods of the String class


In chapters 2 and 4, you learned how to use the equals and
equalsIgnoreCase methods of the String class to compare strings. Now, figure
13-8 reviews these methods and introduces you to 17 more methods that you
can use to work with strings. In the next figure, you’ll see some examples that
use some of these methods. You can also get more information about any of
these methods by looking up the String class in the documentation for the Java
API.
As you can see, we divided the methods presented in this figure into two
categories. The first table lists methods that are used to manipulate the value of
the string in one way or another. The first five of these methods return int
values. The length method returns the total number of characters in the string.
The indexOf and lastlndexOf methods return a value that represents an index
within the string. This index value works as if the string was an array of charac­
ters. In other words, the index value for the first character in a string is 0, the
index value for the second character is 1, and so on.
The next four methods return String objects. Here, the trim method returns
the string, but it removes any spaces from the beginning and end of the string.
The substring methods allow you to return part of a string by specifying index
values. The replace method replaces all occurrences of a specified character
with another character.
The split method returns an array of String objects. This method splits the
string up into individual strings based on the delimiter string you specify.
Actually, the delimiter string can be any regular expression, which is a compli­
cated expression that can contain wildcards and other special characters. If you
want to leam more about regular expressions, you can search the web for “java
regular expression.” In most cases, however, the delimiter string will be a single
character or an escape sequence such as “\t” for tabs or “\n” for returns.
When using methods that require an index, you must be careful to supply a
valid index. If you supply an index argument that’s negative or greater than the
length of the string minus one, the method will throw a
StringlndexOutOfBoundsException.
The second table in this figure lists methods that are useful for comparing
string values. The first six of these methods return boolean values. You’ve
already seen the equals and equalsIgnoreCase methods, which compare strings
and return a true value if the strings are equal. The startsWith and endsWith
methods check whether a string starts or ends with a certain combination of
characters and return a true value if it does. And the isEmpty method checks
whether the string is an empty string and returns a true value if it is.
The last two methods are used to compare two strings to see which one is
greater according to the sort order of the strings. These methods return an int
value that’s negative if the string is less than the specified string, zero if the
strings are equal, and positive if the string is greater than the specified string.
These methods are useful because you can’t use normal comparison operators
(such as < and >) with String objects.
Chapter 13 How to work with dates and strings

Methods for manipulating strings


Method Description
length () Returns an int value for the number of characters in this string.
indexOf ( S t r i n g ) Returns an int value for the index of the first occurrence of the
specified string in this string. If the string isn’t found, this
method returns -1.
indexOf ( S t r i n g , s ta rtln d e x ) Returns an int value for the index of the first occurrence of the
specified string starting at the specified index. If the string isn’t
found, this method returns -1.
lastlndexOf ( S t r i n g ) Returns an int value for the index of the last occurrence of the
specified string in this string.
lastlndexOf ( S t r i n g , Returns an int value for the index of the last occurrence of
s ta rtln d e x ) the specified string in this string starting at the specified index.
trimO Returns a String object with any spaces removed from the
beginning and end of this string.
substring ( s t a r t l n d e x ) Returns a String object that starts at the specified index and goes
to the end of the string.
substring ( s t a r t l n d e x , Returns a String object that starts at the specified start index
e n d ln d e x ) and goes to, but doesn’t include, the end index.
replace ( o ld C h a r, new Char) Returns a String object that results from replacing all instances
of the specified old char value with the specified new char value.
split ( d e l i m i t e r ) Returns an array of String objects that were separated in the
original string by the specified delimiter.
charA t( in d e x ) Returns the char value at the specified index.

Methods for comparing strings


Method Description
equals ( S t r i n g ) Returns a boolean true value if the specified string is equal to the
current string. This comparison is case-sensitive.
equalsIgnoreCase ( S t r i n g ) Returns a boolean true value if the specified string is equal to the
current string. This comparison is not case-sensitive.
startsWith ( S t r i n g ) Returns a boolean true value if this string starts with the
specified string.
startsWith ( S t r i n g , Returns a boolean true value if this string starts with the
s ta rtln d e x ) specified string starting at the start index.
endsWith ( S t r i n g ) Returns a boolean true value if the string ends with the specified
string.
isEmpty() Returns a Boolean true value if this string contains an empty
string. This method was introduced with Java 1.6.
compareTo ( S t r i n g ) Returns an int that’s less than zero if the string is less than the
specified string, greater than zero if the string is greater than the
specified string, and zero if the strings are equal.
compareToIgnoreCase ( S t r i n g ) The same as compareTo, but the case of the strings is ignored.

Figure 13-8 Methods of the String class


422 Section 3 More Java essentials

Code examples that work with strings


Figure 13-9 shows some examples of how you can use the methods of the
String class. The first example shows how to parse the first name from a string
that contains a full name. Here, the first statement sets the string to a string
literal that includes a first and last name, and the second statement uses the trim
method to remove any spaces from the beginning or end of the string. Then, the
third statement uses the indexOf method to get the index of the first space in the
string, which is the space between the first and last names. Finally, the last
statement uses the substring method to set the first name variable equal to the
string that begins at the first character of the string and ends at the first space
character in the string.
The second example shows how to parse a string that contains an address
into the components of the address. In this case, tab characters separate each
component of the address. Here, the second statement uses the trim method to
remove any spaces that may have been included at the beginning or end of the
string. Next, the split method is used to separate the string into its individual
components. Then, simple assignment statements are used to assign the compo­
nents to individual strings. Note that this code doesn’t account for an improp­
erly formatted address string. In an actual application, you’d want to at least
check the length of the addressParts array to make sure the string was success­
fully parsed into four components.
The third example shows how to add dashes to a phone number. To do that,
this example creates a second string. Then, it uses the substring method to parse
the first string and add the dashes at the appropriate locations in the string. In
figure 13-11, you’ll learn an easier way to accomplish this task.
The fourth example shows how to remove the dashes from a phone number.
To do that, this example creates a second string. Then, it uses a for loop to cycle
through each character in the first string. The only statement within this loop
uses the charAt method to add all characters in the first string that are not equal
to a dash to the second string. As a result, the second string won’t contain any
dashes. You’ll learn another way to accomplish this task in figure 13-11.
The fifth example shows how to compare two strings to determine which
one comes first based on the string’s sort order. Here, two strings are created.
Then, the compareToIgnoreCase method of the first string is used to compare
the strings. If the result is less than zero, a message is printed indicating that the
first string comes first in sequence. If the result is zero, the message indicates
that the strings are equal. And if the result is greater than zero, the message
indicates that the second string comes first.
The sixth example shows how to use the isEmpty method that was intro­
duced with Java 1.6 to check if a string contains an empty string. Here, the first
statement creates a string variable named customerNumber that contains an
empty string. Then, two commented out if statements show two ways that were
commonly used to check for empty strings prior to Java 1.6. Although these
statements will still work, the isEmtpy method that’s used in the third if state­
ment requires less typing and is easier to read.
Chapter 13 How to work with dates and strings 423

Example 1 : Code that parses a first name from a name string


String fullName = " Pamela Caldwell ";
fullName = fullName.trim();
int indexOfSpace = fullName.indexOf(" ");
String firstName = fullName.substring(0, indexOfSpace);

Example 2: Code that parses a string containing a tab-delimited address


String address = "805 Main Street\tDallas\tTX\tl2345";
address = address.trim();
String[] addressParts = address.split("\t");
String street = addressParts[0];
String city = addressParts[1];
String state = addressParts[2];
String zip = addressParts[3] ;

Example 3: Code that adds dashes to a phone number


String phoneNumberl = "9775551212";
String phoneNumber2 = phoneNumberl.substring(0, 3);
phoneNumber2 + = "-";
phoneNumber2 + = phoneNumberl.substring(3, 6 );
phoneNumber2 +=
phoneNumber2 += phoneNumberl.substring(6 );

Example 4: Code that removes dashes from a phone number


String phoneNumber3 = "977-555-1212";
String phoneNumber4 =
for(int i = 0; i < phoneNumber3.length(); i++)
{
i f (phoneNumber3.charAt(i) 1= 1 - 1)
phoneNumber4 += phoneNumber3.charAt(i);
}

Example 5: Code that compares strings


String lastNamel = "Smith";
String lastName2 = "Lee";
int sortResult = lastNamel.compareToIgnoreCase(lastName2);
if (sortResult < 0)
System.out.println(lastNamel + " comes first.");
else if (sortResult == 0)
System.out.println("The names are the same.");
else
System.out.println(lastName2 + " comes first.");

Example 6: Code that uses the isEmpty method


String custamerNumber =
//if (customerNumber.equals("")) // old way
//if (customerNumber.length() == 0) // old way
if (customerNumber.isEmpty()) // Java 1.6 and later
System.out.println("customerNumber contains an empty string.");

Figure 13-9 Code examples that work with strings


424 Section 3 More Java essentials

How to work with


the StringBuilder class
When you use the String class to work with strings, the string has a fixed
length and you can’t edit the characters that make up the string. In other words,
the String class creates strings that are immutable. Then, when you assign a new
value to a string variable, the original String object is deleted and it’s replaced
with a new String object that contains the new value.
If you want more flexibility when working with strings, you can use the
StringBuilder class. When you use this class, you create strings that are mu­
table. In other words, you can add, delete, or replace the characters in a
StringBuilder object. This makes it easier to write some types of routines, and it
can improve the efficiency of your code in some situations.
Note that the StringBuilder class was introduced with Java 1.5. It’s designed
to be a more efficient replacement for the StringBuffer class that was used prior
to Java 1.5. Because the API for the StringBuffer class is identical to the API for
the StringBuilder class, you can easily switch between StringBuffer and
StringBuilder.

Constructors and methods


of the StringBuilder class
Figure 13-10 shows three constructors and thirteen methods of the
StringBuilder class. In the next figure, you’ll see some examples that use these
constructors and methods. As always, you can find more information by looking
up the StringBuilder class in the documentation for the Java API.
The first constructor in this figure creates an empty StringBuilder object
with an initial capacity of 16 characters. Then, if you add more than 16 charac­
ters to this StringBuilder object, Java will automatically increase the capacity.
To do that, it doubles the current capacity and adds 2.
Whenever possible, you should set the capacity to an appropriate value by
using the second or third constructor shown in the figure. Otherwise, Java will
have to allocate memory each time the capacity is exceeded, and that can cause
your programs to run less efficiently. On the other hand, if you set a large
capacity and use a small percentage of it, you waste memory.
Once you create a StringBuilder object, you can use the methods in this
figure to work with the object. You can use the first three methods to check the
capacity of the object or to check or set the length of the string. You can use the
next six methods to add, edit, or delete strings or characters. And you can use
the last four methods to return a String object or a character.
Chapter 13 How to work with dates and strings 425

The StringBuilder class


j ava.lang.StringBuilder;

Constructors of the StringBuilder class


Constructor Description
StringBuilder() Creates an empty StringBuilder object with an initial capacity of 16
characters.
StringBuilder(intLength) Creates an empty StringBuilder object with an initial capacity of the
specified number of characters.
StringBuilder(String) Creates a StringBuilder object that contains the specified string plus
an additional capacity of 16 characters.

Methods of the StringBuilder class


Methods Description
capacity() Returns an int value for the capacity of this StringBuilder object.
length () Returns an int value for the number of characters in this
StringBuilder object.
setLength(intNumOfChars) Sets the length of this StringBuilder object to the specified number of
characters.
append(value) Adds the specified value to the end of the string.
insert(index, value) Inserts the specified value at the specified index pushing the rest of
the string back.
replace(startlndex. Replaces the characters from the start index to, but not including, the
endlndex. String) end index with the specified string.
delete(startlndex. Removes the substring from the start index to, but not including, the
endlndex) end index.
deleteCharAt(index) Removes the character at the specified index.
setCharAt(index. Replaces the character at the specified index with the specified
character) character.
charAt ( index) Returns a char value for the character at the specified index.
substring(index) Returns a String object that contains the characters starting at the
specified index to the end of the string.
substring(startlndex. Returns a String object that contains the characters from the start
endlndex) index to, but not including, the end index.
toString() Returns a String object that contains the string that’s stored in the
StringBuilder object.

Description
• StringBuilder objects are mutable, which means you can modify the characters in the
string. The capacity of a StringBuilder object is automatically increased if necessary.
• The append and insert methods accept primitive types, objects, and arrays of characters.
• The StringBuilder class was introduced with Java 1.5. It’s designed to replace the older
StringBuffer class, which has identical constructors and methods but isn’t as efficient.

Figure 13-10 Constructors and methods of the StringBuilder class


426 Section 3 More Java essentials

Code examples that work with


the StringBuilder class
Figure 13-11 presents some examples that show how you can use the
constructors and methods of the StringBuilder class. In particular, this figure
shows how to add characters to the end of a string, insert characters into the
middle of a string, and delete characters from a string.
The first example shows how to use the append method of the StringBuilder
class. Here, the first statement creates an empty StringBuilder object with the
default capacity of 16 characters. Then, the next three statements use the append
method to add 10 characters to the end of the string. As a result, the length of
the string is 10 and the capacity of the StringBuilder object is 16. (You can do
the same thing by using simple string concatenation, but Java must create a new
String object for each statement since the length of a String object can’t be
increased. In contrast, when you use the append method of the StringBuilder
class, a new StringBuilder object isn’t created because the length of a
StringBuilder object can be increased.)
The second example adds dashes to the string that was created in the first
example. Here, the first statement uses the insert method to insert a dash after
the first three characters. This pushes the remaining numbers back one index.
Then, the second statement uses the insert method to insert a dash after the
seventh character in the string, which was the sixth character in the original
string. This pushes the remaining four numbers in the string back one index.
The third example shows how to remove dashes from a phone number.
Here, a loop cycles through each character, using the charAt method to check if
the current character is a dash. If so, the deleteCharAt method deletes it. Since
this causes all characters to the right of the dash to move forward one index, it’s
necessary to decrement the counter so the loop doesn’t skip any characters.
The fourth example shows how to use the substring method of the
StringBuilder class to separate the area code, prefix, and suffix components of a
phone number. Here, the first statement uses a constructor to create a
StringBuilder object from a String literal. Then, the next three statements use
the substring method to create three String objects from the StringBuilder
object. For example, the second statement specifies a substring that goes from
the first character up to, but not including, the fourth character. (Note that the
substring method works the same for the String class as it does for the
StringBuilder class, so the same thing could be done with a simple string.)
The fifth example shows how a StringBuilder object automatically increases
its capacity as the length of the string increases. Here, the first statement creates
an empty StringBuilder object with a capacity of 8 characters, and the second
statement uses the capacity method to check the capacity. Next, the third
statement appends a string of 17 characters to the empty string. Since this
causes the capacity of the StringBuilder object to be exceeded, Java automati­
cally increases the capacity. As a result, the capacity of the name string is
increased from 8 to 18 characters. Then, the last two statements check the
length and capacity of the modified StringBuilder object.
Chapter 13 How to work with dates and strings 427

Example 1 : Code that creates a phone number


StringBuilder phoneNumber = new StringBuilder();
phoneNumber.append("977");
phoneNumber.append("555") ;
phoneNumber.append("1212" ) ;

Example 2: Code that adds dashes to a phone number


phoneNumber.insert(3,
phoneNumber.insert(7,

Example 3: Code that removes dashes from a phone number


for(int i = 0; i < phoneNumber.length(); i++)
{
if (phoneNumber.charAt(i) ==
phoneNumber.deleteCharAt(i-- ) ;
}

Example 4: Code that parses a phone number


StringBuilder phoneNumber = new StringBuilder("977-555-1212");
String areaCode = phoneNumber.substring(0,3);
String prefix = phoneNumber.substring(4,7) ;
String suffix = phoneNumber.substring(8 );

Example 5: Code that shows how capacity automatically increases


StringBuilder name = new StringBuilder(8 );
int capacityl = name.capacity(); // capacityl is 8
name.append("Raymond R. Thomas");
int length = name.length(); // length is 17
int capacity2 = name.capacity(); // capacity2 is 18 (2 * capacityl + 2 )

Figure 13-11 Code examples that work with the StringBuilder class
428 Section 3 More Java essentials

Perspective
Now that you’ve finished this chapter, you should be able to use the
classes provided by the Java API to work with dates, and you should be able to
use the String and StringBuilder classes to work with strings. These are skills
that you will use often as you develop Java applications.

Summary
• You can use the GregorianCalendar, Calendar, Date, and DateFormat classes to
create, manipulate, and format dates and times.
• You can use methods of the String class to locate a string within another string,
return parts of a string, and compare all or part of a string. However, String objects
are immutable, so you can’t add, delete, or modify individual characters in a string.
• StringBuilder objects are mutable, so you can use the StringBuilder methods to
add, delete, or modify characters in a StringBuilder object. Whenever necessary,
Java automatically increases the capacity of a StringBuilder object.

Exercise 13-1 Add a due date to the Invoice


application

For this exercise, you’ll modify the Invoice class that’s shown in figure 13-6 so
it contains methods that return a due date, calculated as 30 days after the invoice
date. Then, you’ll modify the Invoice application that was shown in chapter 12
to display the invoice date and due date for a batch of invoices.
1. Open the project named chl3_exl_Invoice that’s in the ex_starts directory.
Then, review the code in the Invoice and InvoiceApp classes.
2. Add two methods named getDueDate and getFormattedDueDate to the
Invoice class. The getDueDate method should calculate and return a Date
object that’s 30 days after the invoice date. The getFormattedDueDate method
should return the due date in the short date format.
3. Modify the displaylnvoices method in the InvoiceApp class so that the invoice
display includes columns for the invoice date and the due date in addition to
the invoice number and total. Then, run the application to make sure it works.
Chapter 13 How to work with dates and strings 429

Exercise 13-2 Calculate the user’s age


In this exercise, you’ll write a program that accepts a person’s birth date from
the console and displays the person’s age in years. To make that easier to do,
we’ll give you a class that contains the code for accepting the birth date. The
console output for the program should look something like this:
f Welcome to the age calculator. j

Enter the month you were born (1 to 12) : 5


Enter the day of the month you were born: 16
Enter the year you were born (four digits): 1959

Your birth date is May 16, 1959


Today's date is Feb 9, 2012
Your age is: 52

1. Open the project named chl3_ex2_AgeCalculator that’s in the ex_starts


directory. Then, review the code in the AgeCalculatorApp class.
2. Add code to this class that gets the current date and then uses the current year
to validate the birth year the user enters. The user should not be allowed to
enter a year after the current year or more than 110 years before the current
year.
3. Add code to create, format, and print the user’s birth date and to format and
print the current date.
4. Add code to calculate and print the user’s age.
5. Test this project with a variety of dates to be sure it works.

Exercise 13-3 Parse a name


In this exercise, you’ll write an application that parses full names into first and
last name or first, middle, and last name, depending on whether the user enters a
string consisting of two or three words. The output for the program should look
something like this:
(r~ Welcome to the name parser. ------------Λ

Enter a name: Joel Murach

First name: Joel


Last name: Murach
V- ---------- J
1. Open the project named chl3_ex3_NameParser that’s in the ex_starts
directory. Then, review the code in the NameParserApp class.
2. Add code that separates the name into two or three strings depending on
whether the user entered a name with two words or three.
430 Section 3 More Java essentials

3. Display each word of the name on a separate line. If the user enters fewer
than two words or more than three words, display an error message. Also,
make sure the application works even if the user enters one or more spaces
before or after the name.
4. Test the project to make sure it works correctly.

Exercise 13-4 Validate a social security number


In this exercise, you’ll add a method named getSSN to the Validator class that
was presented in chapter 7. Then, you’ll use this method in a program to
validate a social security number entered by the user.
1. Open the project named chl3_ex4_SSNValidator that’s in the ex_starts
directory. Then, open the SSNValidatorApp and Validator classes and review
the code.
2. Add a method named getSSN to the Validator class that accepts and validates
a social security number. This method should accept a Scanner object and a
string that will be displayed to the user as a prompt. After it accepts the social
security number, this method should check that the entry contains 11
characters. If it does, the method should validate the entry by checking that
the first three characters are numeric digits, the fourth character is a hyphen,
the fifth and sixth characters are numeric digits, the seventh character is a
hyphen, and the eighth through eleventh characters are numeric digits. To
check for a numeric digit, you can use a private method that tests if a
character is equal to any of the numbers from 0 through 9. If the user’s entry
doesn’t conform to this format, the method should display an error message
and ask the user to enter the number again.
3. Modify the SSNValidatorApp class so it uses the getSSN method. Then,
compile and run this class to make sure the validation works correctly.

You might also like