Chapter 10 – Strings and Characters Outline 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 10.13 10.14 10.15 Introduction Fundamentals of Characters and Strings String Constructors String Methods length, charAt and getChars Comparing Strings String Method hashCode Locating Characters.

Download Report

Transcript Chapter 10 – Strings and Characters Outline 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 10.13 10.14 10.15 Introduction Fundamentals of Characters and Strings String Constructors String Methods length, charAt and getChars Comparing Strings String Method hashCode Locating Characters.

Chapter 10 – Strings and Characters
Outline
10.1
10.2
10.3
10.4
10.5
10.6
10.7
10.8
10.9
10.10
10.11
10.12
10.13
10.14
10.15
Introduction
Fundamentals of Characters and Strings
String Constructors
String Methods length, charAt and getChars
Comparing Strings
String Method hashCode
Locating Characters and Substrings in Strings
Extracting Substrings from Strings
Concatenating Strings
Miscellaneous String Methods
Using String Method valueOf
String Method intern
StringBuffer Class
StringBuffer Constructors
StringBuffer Methods length, capacity, setLength and
ensureCapacity
 2002 Prentice Hall, Inc. All rights reserved.
Chapter 10 – Strings and Characters
10.16
10.17
10.18
10.19
10.20
10.21
10.22
StringBuffer Methods charAt, setCharAt, getChars and
reverse
StringBuffer append Methods
StringBuffer Insertion and Deletion Methods
Character Class Examples
Class StringTokenizer
Card Shuffling and Dealing Simulation
(Optional Case Study) Thinking About Objects: Event
Handling
 2002 Prentice Hall, Inc. All rights reserved.
10.1 Introduction
• String and character processing
–
–
–
–
Class java.lang.String
Class java.lang.StringBuffer
Class java.lang.Character
Class java.util.StringTokenizer
 2002 Prentice Hall, Inc. All rights reserved.
10.2 Fundamentals of Characters and
Strings
• Characters
– “Building blocks” of Java source programs
• String
– Series of characters treated as single unit
– May include letters, digits, etc.
– Object of class String
 2002 Prentice Hall, Inc. All rights reserved.
10.3 String Constructors
• Class String
– Provides nine constructors
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Fig. 10.1: StringConstructors.java
// This program demonstrates the String class constructors.
// Java extension packages
import javax.swing.*;
Outline
StringConstructo
rs.java
public class StringConstructors {
Line 25
// test String constructors
public static void main( String args[] )
String defaultLine
constructor
{
26
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', instantiates empty string
'd', 'a', 'y' };
byte byteArray[] = { ( byte ) 'n', ( byte ) 'e',
Line 27
( byte ) 'w', ( byte ) ' ', ( byte ) 'y',
Constructor copies String
( byte ) 'e', ( byte ) 'a', ( byte ) 'r' };
Line 28
StringBuffer buffer;
Constructor copies character array
String s, s1, s2, s3, s4, s5, s6, s7, output;
Line 29
Constructor copies
s = new String( "hello" );
buffer = new StringBuffer( "Welcome to Java Programming!"
);
Line 30
character-array
subset
//
s1
s2
s3
s4
s5
s6
s7
use String constructors
= new String();
= new String( s );
= new String( charArray );
= new String( charArray, 6, 3 );
= new String( byteArray, 4, 4 );
= new String( byteArray );
= new String( buffer );
Line
31 array
Constructor copies
byte
Constructor copies byte-array subset
Constructor copies StringBuffer
 2002 Prentice Hall, Inc.
All rights reserved.
33
34
35
36
37
38
39
40
41
42
43
44
45
// append Strings to output
output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 +
"\ns4 = " + s4 + "\ns5 = " + s5 + "\ns6 = " + s6 +
"\ns7 = " + s7;
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Constructors",
JOptionPane.INFORMATION_MESSAGE );
Outline
StringConstructo
rs.java
System.exit( 0 );
}
}
// end class StringConstructors
 2002 Prentice Hall, Inc.
All rights reserved.
10.4 String Methods length, charAt and
getChars
• Method length
– Determine String length
• Like arrays, Strings always “know” their size
• Unlike array, Strings do not have length instance variable
• Method charAt
– Get character at specific location in String
• Method getChars
– Get entire set of characters in String
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//
//
//
//
//
//
//
//
Outline
Fig. 10.2: StringMiscellaneous.java
This program demonstrates the length, charAt and getChars
methods of the String class.
Note: Method getChars requires a starting point
and ending point in the String. The starting point is the
actual subscript from which copying starts. The ending point
is one past the subscript at which the copying ends.
// Java extension packages
import javax.swing.*;
StringMiscellane
ous.java
Line 28
Line 33
public class StringMiscellaneous {
// test miscellaneous String methods
public static void main( String args[] )
{
String s1, output;
char charArray[];
s1 = new String( "hello there" );
charArray = new char[ 5 ];
// output the string
output = "s1: " + s1;
// test length method
output += "\nLength of s1: " + s1.length();
// loop through characters in s1 and display reversed
output += "\nThe string reversed is: ";
for ( int count = s1.length() - 1; count >= 0; count-- )
output += s1.charAt( count ) + " ";
Determine number of
characters in String s1
Append s1’s characters
in reverse order to
String
output
 2002 Prentice
Hall, Inc.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// copy characters from string into char array
s1.getChars( 0, 5, charArray, 0 );
output += "\nThe character array is: ";
Copy (some of) s1’s Outline
characters to charArray
for ( int count = 0; count < charArray.length; count++ )
output += charArray[ count ];
StringMiscellane
ous.java
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Constructors",
JOptionPane.INFORMATION_MESSAGE );
Line 37
System.exit( 0 );
}
}
// end class StringMiscellaneous
 2002 Prentice Hall, Inc.
All rights reserved.
10.5 Comparing Strings
• Comparing String objects
–
–
–
–
Method equals
Method equalsIgnoreCase
Method compareTo
Method regionMatches
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//
//
//
//
Outline
Fig. 10.3: StringCompare.java
This program demonstrates the methods equals,
equalsIgnoreCase, compareTo, and regionMatches
of the String class.
StringCompare.ja
va
// Java extension packages
import javax.swing.JOptionPane;
Line 25
public class StringCompare {
// test String class comparison methods
public static void main( String args[] )
{
String s1, s2, s3, s4, output;
s1
s2
s3
s4
=
=
=
=
new
new
new
new
String(
String(
String(
String(
Line 31
"hello" );
"good bye" );
"Happy Birthday" );
"happy birthday" );
output = "s1 = " + s1 + "\ns2 = " + s2 +
"\ns3 = " + s3 + "\ns4 = " + s4 + "\n\n";
// test for equality
if ( s1.equals( "hello" ) )
output += "s1 equals \"hello\"\n";
else
output += "s1 does not equal \"hello\"\n";
Method equals tests two
objects for equality using
lexicographical comparison
Equality operator (==) tests
// test for equality with ==
if both references refer to
if ( s1 == "hello" )
same object in memory
output += "s1 equals \"hello\"\n";
else
output += "s1 does not equal \"hello\"\n";
 2002 Prentice Hall, Inc.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// test for equality (ignore case)
if ( s3.equalsIgnoreCase( s4 ) )
output += "s3 equals s4\n";
else
output += "s3 does not equal s4\n";
// test compareTo
output +=
"\ns1.compareTo(
"\ns2.compareTo(
"\ns1.compareTo(
"\ns3.compareTo(
"\ns4.compareTo(
"\n\n";
s2
s1
s1
s4
s3
)
)
)
)
)
is
is
is
is
is
"
"
"
"
"
+
+
+
+
+
Test two objects for
equality, but ignore case
of letters in String
s1.compareTo(
s2.compareTo(
s1.compareTo(
s3.compareTo(
s4.compareTo(
s2
s1
s1
s4
s3
)
)
)
)
)
+
+
+
+
+
// test regionMatches (case sensitive)
if ( s3.regionMatches( 0, s4, 0, 5 ) )
output += "First 5 characters of s3 and s4 match\n";
else
output +=
"First 5 characters of s3 and s4 do not match\n";
Outline
StringCompare.ja
va
Method
Line 37compareTo
compares String objects
Lines 44-48
Line 52 and 59
Method regionMatches
compares portions of two
String objects for equality
// test regionMatches (ignore case)
if ( s3.regionMatches( true, 0, s4, 0, 5 ) )
output += "First 5 characters of s3 and s4 match";
else
output +=
"First 5 characters of s3 and s4 do not match";
 2002 Prentice Hall, Inc.
All rights reserved.
65
66
67
68
69
70
71
72
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Constructors",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Outline
StringCompare.ja
va
// end class StringCompare
 2002 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
// Fig. 10.4: StringStartEnd.java
// This program demonstrates the methods startsWith and
// endsWith of the String class.
// Java extension packages
import javax.swing.*;
public class StringStartEnd {
// test String comparison methods for beginning and end
// of a String
public static void main( String args[] )
{
String strings[] =
{ "started", "starting", "ended", "ending" };
String output = "";
StringStartEnd.j
ava
Line 21
Line 31
// test method startsWith
for ( int count = 0; count < strings.length; count++ )
if ( strings[ count ].startsWith( "st" ) )
output += "\"" + strings[ count ] +
"\" starts with \"st\"\n";
output += "\n";
// test method startsWith starting from position
// 2 of the string
for ( int count = 0; count < strings.length; count++ )
Method startsWith
determines if String starts
with specified characters
if ( strings[ count ].startsWith( "art", 2 ) )
output += "\"" + strings[ count ] +
"\" starts with \"art\" at position 2\n";
output += "\n";
 2002 Prentice Hall, Inc.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// test method endsWith
for ( int count = 0; count < strings.length; count++ )
if ( strings[ count ].endsWith( "ed" ) )
output += "\"" + strings[ count ] +
"\" ends with \"ed\"\n";
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Comparisons",
JOptionPane.INFORMATION_MESSAGE );
Outline
StringStartEnd.j
ava
Method endsWith
Line 40
determines if String ends
with specified characters
System.exit( 0 );
}
}
// end class StringStartEnd
 2002 Prentice Hall, Inc.
All rights reserved.
10.6 String Method hashCode
• Hash table
– Stores information using calculation on storable object
• Produces hash code
– Used to choose location in table at which to store object
– Fast lookup
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 10.5: StringHashCode.java
// This program demonstrates the method
// hashCode of the String class.
// Java extension packages
import javax.swing.*;
public class StringHashCode {
Outline
StringHashCode.j
ava
Line 17 and 19
// test String hashCode method
public static void main( String args[] )
{
String s1 = "hello", s2 = "Hello";
String output =
"The hash code for \"" + s1 + "\" is " +
s1.hashCode() +
"\nThe hash code for \"" + s2 + "\" is " +
s2.hashCode();
Method hashCode performs
hash-code calculation
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Method hashCode",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class StringHashCode
 2002 Prentice Hall, Inc.
All rights reserved.
10.7 Locating Characters and Substrings in
Strings
• Search for characters in String
– Method indexOf
– Method lastIndexOf
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Fig. 10.6: StringIndexMethods.java
// This program demonstrates the String
// class index methods.
// Java extension packages
import javax.swing.*;
public class StringIndexMethods {
// String searching methods
public static void main( String args[] )
{
String letters = "abcdefghijklmabcdefghijklm";
// test indexOf to locate a character in a string
String output = "'c' is located at index " +
letters.indexOf( 'c' );
output += "\n'a' is located at index " +
letters.indexOf( 'a', 1 );
Outline
StringIndexMetho
ds.java
Lines 16-23
Lines 26-33
Method indexOf finds first
occurrence of character in String
output += "\n'$' is located at index " +
letters.indexOf( '$' );
// test lastIndexOf to find a character in a string
output += "\n\nLast 'c' is located at index " +
letters.lastIndexOf( 'c' );
output += "\nLast 'a' is located at index " +
letters.lastIndexOf( 'a', 25 );
Method lastIndexOf
finds last occurrence of
character in String
output += "\nLast '$' is located at index " +
letters.lastIndexOf( '$' );
 2002 Prentice Hall, Inc.
All rights reserved.
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// test indexOf to locate a substring in a string
output += "\n\n\"def\" is located at index " +
letters.indexOf( "def" );
output += "\n\"def\" is located at index " +
letters.indexOf( "def", 7 );
output += "\n\"hello\" is located at index " +
letters.indexOf( "hello" );
// test lastIndexOf to find a substring in a string
output += "\n\nLast \"def\" is located at index " +
letters.lastIndexOf( "def" );
Outline
StringIndexMetho
ds.java
Methods indexOf and
lastIndexOf can also find
occurrences of substrings
output += "\nLast \"def\" is located at index " +
letters.lastIndexOf( "def", 25 );
output += "\nLast \"hello\" is located at index " +
letters.lastIndexOf( "hello" );
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class \"index\" Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class StringIndexMethods
 2002 Prentice Hall, Inc.
All rights reserved.
Outline
StringIndexMetho
ds.java
 2002 Prentice Hall, Inc.
All rights reserved.
10.8 Extracting Substrings from Strings
• Create Strings from other Strings
– Extract substrings
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Outline
// Fig. 10.7: SubString.java
// This program demonstrates the
// String class substring methods.
// Java extension packages
import javax.swing.*;
public class SubString {
// test String substring methods
public static void main( String args[] )
{
String letters = "abcdefghijklmabcdefghijklm";
// test substring methods
String output = "Substring from index 20 to end is " +
"\"" + letters.substring( 20 ) + "\"\n";
output += "Substring from index 0 up to 6 is " +
"\"" + letters.substring( 0, 6 ) + "\"";
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Substring Methods",
JOptionPane.INFORMATION_MESSAGE );
SubString.java
Line 17
Line 20
Beginning at index 20,
extract characters from
String letters
Extract characters from index 0
to 6 from String letters
System.exit( 0 );
}
}
// end class SubString
 2002 Prentice Hall, Inc.
All rights reserved.
10.9 Concatenating Strings
• Method concat
– Concatenate two String objects
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//
//
//
//
Fig.
This
Note
does
10.8: StringConcatenation.java
program demonstrates the String class concat method.
that the concat method returns a new String object. It
not modify the object that invoked the concat method.
// Java extension packages
import javax.swing.*;
public class StringConcatenation {
// test String method concat
public static void main( String args[] )
{
String s1 = new String( "Happy " ),
s2 = new String( "Birthday" );
Outline
StringConcatenat
ion.java
Line 20
Line 22
String output = "s1 = " + s1 + "\ns2 = " + s2;
output += "\n\nResult of s1.concat( s2 ) = " +
s1.concat( s2 );
output += "\ns1 after concatenation = " + s1;
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Method concat",
JOptionPane.INFORMATION_MESSAGE );
Concatenate String s2
to String s1
However, String s1 is not
modified by method concat
System.exit( 0 );
}
}
// end class StringConcatenation
 2002 Prentice Hall, Inc.
All rights reserved.
10.10 Miscellaneous String Methods
• Miscellaneous String methods
– Return modified copies of String
– Return character array
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Outline
// Fig. 10.9: StringMiscellaneous2.java
// This program demonstrates the String methods replace,
// toLowerCase, toUpperCase, trim, toString and toCharArray
StringMiscellane
ous2.java
// Java extension packages
import javax.swing.*;
public class StringMiscellaneous2 {
// test miscellaneous String methods
public static void main( String args[] )
{
String s1 = new String( "hello" ),
s2 = new String( "GOOD BYE" ),
s3 = new String( "
spaces
" );
String output = "s1 = " + s1 + "\ns2 = " + s2 +
"\ns3 = " + s3;
// test method replace
output += "\n\nReplace 'l' with 'L' in s1: " +
s1.replace( 'l', 'L' );
Line 22
Line 26
Use method replace to return s1
copy in whichLine
every27occurrence of
‘l’ is replaced with ‘L’
Line 30
Use method toUpperCase to
return s1 Line
copy 33
in which every
character is uppercase
Use method toLowerCase to
return s2 copy in which every
character is uppercase
// test toLowerCase and toUpperCase
output +=
"\n\ns1.toUpperCase() = " + s1.toUpperCase() +
"\ns2.toLowerCase() = " + s2.toLowerCase();
// test trim method
output += "\n\ns3 after trim = \"" + s3.trim() + "\"";
// test toString method
output += "\n\ns1 = " + s1.toString();
Use method trim to
return s3 copy in which
whitespace is eliminated
Use method toString to return s1
 2002 Prentice Hall, Inc.
All rights reserved.
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// test toCharArray method
char charArray[] = s1.toCharArray();
Use method toCharArray to
return character array of s1
output += "\n\ns1 as a character array = ";
for ( int count = 0; count < charArray.length; ++count )
output += charArray[ count ];
JOptionPane.showMessageDialog( null, output,
"Demonstrating Miscellaneous String Methods",
JOptionPane.INFORMATION_MESSAGE );
Outline
StringMiscellane
ous2.java
Line 36
System.exit( 0 );
}
}
// end class StringMiscellaneous2
 2002 Prentice Hall, Inc.
All rights reserved.
10.11 Using String Method valueOf
• String provides static class methods
– Method valueOf
• Returns String representation of object, data type, etc.
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Fig. 10.10: StringValueOf.java
// This program demonstrates the String class valueOf methods.
// Java extension packages
import javax.swing.*;
Outline
StringValueOf.ja
va
public class StringValueOf {
// test String valueOf methods
public static void main( String args[] )
{
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
boolean b = true;
char c = 'Z';
int i = 7;
long l = 10000000;
float f = 2.5f;
double d = 33.333;
Object o = "hello";
String output;
Lines 26-32
// assign to an Object reference
output = "char array = " + String.valueOf( charArray ) +
"\npart of char array = " +
String.valueOf( charArray, 3, 3 ) +
"\nboolean = " + String.valueOf( b ) +
"\nchar = " + String.valueOf( c ) +
static method valueOf of
"\nint = " + String.valueOf( i ) +
class String returns String
"\nlong = " + String.valueOf( l ) +
representation of various types
"\nfloat = " + String.valueOf( f ) +
"\ndouble = " + String.valueOf( d ) +
"\nObject = " + String.valueOf( o );
 2002 Prentice Hall, Inc.
All rights reserved.
34
35
36
37
38
39
40
41
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class valueOf Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Outline
StringValueOf.ja
va
// end class StringValueOf
 2002 Prentice Hall, Inc.
All rights reserved.
10.12 String Method intern
• String comparisons
– Slow operation
– Method intern improves this performance
• Returns reference to String
• Guarantees reference has same contents as original String
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
// Fig. 10.11: StringIntern.java
// This program demonstrates the intern method
// of the String class.
StringIntern.jav
a
// Java extension packages
import javax.swing.*;
public class StringIntern {
Lines 15-20
// test String method intern
public static void main( String args[] )
{
String s1, s2, s3, s4, output;
s1 = new String( "hello" );
s2 = new String( "hello" );
Line 26
Lines 33-34
String s1 and String s2
occupy different memory locations
// test strings to determine if they are same
// String object in memory
if ( s1 == s2 )
output = "s1 and s2 are the same object in memory";
else
output = "s1 and s2 are not the same object in memory";
// test strings for equality of contents
if ( s1.equals( s2 ) )
output += "\ns1 and s2 are equal";
else
output += "\ns1 and s2 are not equal";
//
//
s3
s4
String s1 and String s2
have same content
use String intern method to get a unique copy of
"hello" referred to by both s3 and s4
= s1.intern();
= s2.intern();
Reference returned by
s1.intern() is same as that
returned by s2.intern()
 2002 Prentice Hall, Inc.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// test strings to determine if they are same
// String object in memory
if ( s3 == s4 )
output += "\ns3 and s4 are the same object in memory";
else
output +=
"\ns3 and s4 are not the same object in memory";
Outline
StringIntern.jav
a
// determine if s1 and s3 refer to same object
if ( s1 == s3 )
output +=
"\ns1 and s3 are the same object in memory";
else
output +=
"\ns1 and s3 are not the same object in memory";
// determine if s2 and s4 refer to same object
if ( s2 == s4 )
output += "\ns2 and s4 are the same object in memory";
else
output +=
"\ns2 and s4 are not the same object in memory";
// determine if s1 and s4 refer to same object
if ( s1 == s4 )
output += "\ns1 and s4 are the same object in memory";
else
output +=
"\ns1 and s4 are not the same object in memory";
 2002 Prentice Hall, Inc.
All rights reserved.
66
67
68
69
70
71
72
73
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Method intern",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Outline
StringIntern.jav
a
// end class StringIntern
 2002 Prentice Hall, Inc.
All rights reserved.
10.13 StringBuffer Class
• Class StringBuffer
– When String object is created, its contents cannot change
– Used for creating and manipulating dynamic string data
• i.e., modifiable Strings
– Can store characters based on capacity
• Capacity expands dynamically to handle additional characters
– Uses operators + and += for String concatenation
 2002 Prentice Hall, Inc. All rights reserved.
10.14 StringBuffer Constructors
• Three StringBuffer constructors
– Default creates StringBuffer with no characters
• Capacity of 16 characters
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 10.12: StringBufferConstructors.java
// This program demonstrates the StringBuffer constructors.
// Java extension packages
import javax.swing.*;
public class StringBufferConstructors {
// test StringBuffer constructors
public static void main( String args[] )
{
StringBuffer buffer1, buffer2, buffer3;
Default constructor creates
StringBufferCons
empty StringBuffertructors.java
with
capacity of 16 characters
Line 14
Second constructor creates empty
StringBuffer with capacity of
15
specified (10)Line
characters
buffer1 = new StringBuffer();
buffer2 = new StringBuffer( 10 );
buffer3 = new StringBuffer( "hello" );
String output
"buffer1 =
"\nbuffer2
"\nbuffer3
Outline
=
\"" + buffer1.toString() + "\"" +
= \"" + buffer2.toString() + "\"" +
= \"" + buffer3.toString() + "\"";
JOptionPane.showMessageDialog( null, output,
"Demonstrating StringBuffer Class Constructors",
JOptionPane.INFORMATION_MESSAGE );
Line 16 creates
Third constructor
StringBuffer with
Lines
19-21 and
String
“hello”
capacity of 16 characters
Method toString returns
String representation of
StringBuffer
System.exit( 0 );
}
}
// end class StringBufferConstructors
 2002 Prentice Hall, Inc.
All rights reserved.
10.15 StringBuffer Methods length, capacity,
setLength and ensureCapacity
• Method length
– Return StringBuffer length
• Method capacity
– Return StringBuffer capacity
• Method setLength
– Increase or decrease StringBuffer length
• Method ensureCapacity
– Set StringBuffer capacity
– Guarantee that StringBuffer has minimum capacity
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Outline
// Fig. 10.13: StringBufferCapLen.java
// This program demonstrates the length and
// capacity methods of the StringBuffer class.
// Java extension packages
import javax.swing.*;
public class StringBufferCapLen {
// test StringBuffer methods for capacity and length
public static void main( String args[] )
{
StringBuffer buffer =
new StringBuffer( "Hello, how are you?" );
String output = "buffer = " + buffer.toString() +
"\nlength = " + buffer.length() +
"\ncapacity = " + buffer.capacity();
buffer.ensureCapacity( 75 );
output += "\n\nNew capacity = " + buffer.capacity();
buffer.setLength( 10 );
output += "\n\nNew length = " + buffer.length() +
"\nbuf = " + buffer.toString();
JOptionPane.showMessageDialog( null, output,
"StringBuffer length and capacity Methods",
JOptionPane.INFORMATION_MESSAGE );
StringBufferCapL
en.java
Line 17
Line 18
Method length returns
StringBuffer
Line 20length
Line 23 returns
Method capacity
StringBuffer capacity
Use method ensureCapacity
to set capacity to 75
Use method setLength
to set length to 10
System.exit( 0 );
}
}
// end class StringBufferCapLen
 2002 Prentice Hall, Inc.
All rights reserved.
Outline
StringBufferCapL
en.java
Only 10 characters
from StringBuffer
are printed
Only 10 characters from
StringBuffer are printed
 2002 Prentice Hall, Inc.
All rights reserved.
10.16 StringBuffer Methods charAt,
setCharAt, getChars and reverse
• Manipulating StringBuffer characters
– Method charAt
• Return StringBuffer character at specified index
– Method setCharAt
• Set StringBuffer character at specified index
– Method getChars
• Return character array from StringBuffer
– Method reverse
• Reverse StringBuffer contents
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Outline
// Fig. 10.14: StringBufferChars.java
// The charAt, setCharAt, getChars, and reverse methods
// of class StringBuffer.
StringBufferChar
s.java
// Java extension packages
import javax.swing.*;
public class StringBufferChars {
Lines 16-17
// test StringBuffer character methods
public static void main( String args[] )
{
StringBuffer buffer = new StringBuffer( "hello there" );
String output = "buffer = " + buffer.toString() +
"\nCharacter at 0: " + buffer.charAt( 0 ) +
"\nCharacter at 4: " + buffer.charAt( 4 );
Line
20
Return
StringBuffer
characters at indices 0
Lines
26-27
and
4, respectively
Line 30
char charArray[] = new char[ buffer.length() ];
buffer.getChars( 0, buffer.length(), charArray, 0 );
output += "\n\nThe characters are: ";
Return character array
from StringBuffer
for ( int count = 0; count < charArray.length; ++count )
output += charArray[ count ];
buffer.setCharAt( 0, 'H' );
buffer.setCharAt( 6, 'T' );
output += "\n\nbuf = " + buffer.toString();
buffer.reverse();
output += "\n\nbuf = " + buffer.toString();
Replace characters at
indices 0 and 6 with ‘H’
and ‘T,’ respectively
Reverse characters in
StringBuffer
 2002 Prentice Hall, Inc.
All rights reserved.
33
34
35
36
37
38
39
40
JOptionPane.showMessageDialog( null, output,
"Demonstrating StringBuffer Character Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Outline
StringBufferChar
s.java
// end class StringBufferChars
 2002 Prentice Hall, Inc.
All rights reserved.
10.17 StringBuffer append Methods
• Method append
– Allow data-type values to be added to StringBuffer
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Outline
// Fig. 10.15: StringBufferAppend.java
// This program demonstrates the append
// methods of the StringBuffer class.
StringBufferAppe
nd.java
// Java extension packages
import javax.swing.*;
public class StringBufferAppend {
Line 24
// test StringBuffer append methods
public static void main( String args[] )
{
Object o = "hello";
String s = "good bye";
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
boolean b = true;
char c = 'Z';
int i = 7;
long l = 10000000;
float f = 2.5f;
double d = 33.333;
StringBuffer buffer = new StringBuffer();
buffer.append( o );
buffer.append( " " );
Append String “hello”
to StringBuffer
 2002 Prentice Hall, Inc.
All rights reserved.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 }
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
s );
" " );
charArray );
" " );
charArray, 0, 3 );
" " );
b );
" " );
c );
" " );
i );
" " );
l );
" " );
f );
" " );
d );
Outline
Append String “good bye”
Append “a b c d e f”
Append “a b c”
StringBufferAppe
nd.java
Line 27
Append boolean, char, int,
Line 29
long, float and double
Line 31
Lines 33-43
JOptionPane.showMessageDialog( null,
"buffer = " + buffer.toString(),
"Demonstrating StringBuffer append Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
// end StringBufferAppend
 2002 Prentice Hall, Inc.
All rights reserved.
10.18 StringBuffer Insertion and Deletion
Methods
• Method insert
– Allow data-type values to be inserted into StringBuffer
• Methods delete and deleteCharAt
– Allow characters to be removed from StringBuffer
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Fig. 10.16: StringBufferInsert.java
// This program demonstrates the insert and delete
// methods of class StringBuffer.
// Java extension packages
import javax.swing.*;
Outline
StringBufferInse
rt.java
public class StringBufferInsert {
// test StringBuffer insert methods
public static void main( String args[] )
{
Object o = "hello";
String s = "good bye";
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
boolean b = true;
char c = 'K';
int i = 7;
long l = 10000000;
float f = 2.5f;
double d = 33.333;
StringBuffer buffer = new StringBuffer();
 2002 Prentice Hall, Inc.
All rights reserved.
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
o );
" " );
s );
" " );
charArray );
" " );
b );
" " );
c );
" " );
i );
" " );
l );
" " );
f );
" " );
d );
Outline
Use method insert to insert StringBufferInse
rt.java
data types in beginning of
StringBuffer
Lines 24-40
String output =
"buffer after inserts:\n" + buffer.toString();
buffer.deleteCharAt( 10 );
buffer.delete( 2, 6 );
Line 45
Line 46
Use method deleteCharAt to
remove character from index 10 in
StringBuffer
// delete 5 in 2.5
// delete .333 in 33.333
output +=
"\n\nbuffer after deletes:\n" + buffer.toString();
Remove characters from
indices 2 through 5 (inclusive)
JOptionPane.showMessageDialog( null, output,
"Demonstrating StringBufferer Inserts and Deletes",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class StringBufferInsert
 2002 Prentice Hall, Inc.
All rights reserved.
Outline
StringBufferInse
rt.java
 2002 Prentice Hall, Inc.
All rights reserved.
10.19 Character Class Examples
• Treat primitive variables as objects
– Type wrapper classes
• Boolean
• Character
• Double
• Float
• Byte
• Short
• Integer
• Long
– We examine class Character
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//
//
//
//
Fig. 10.17: StaticCharMethods.java
Demonstrates the static character testing methods
and case conversion methods of class Character
from the java.lang package.
// Java core packages
import java.awt.*;
import java.awt.event.*;
Outline
StaticCharMethod
s.java
// Java extension packages
import javax.swing.*;
public class StaticCharMethods extends JFrame {
private char c;
private JLabel promptLabel;
private JTextField inputField;
private JTextArea outputArea;
// set up GUI
public StaticCharMethods()
{
super( "Static Character Methods" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
promptLabel =
new JLabel( "Enter a character and press Enter" );
container.add( promptLabel );
inputField = new JTextField( 5 );
inputField.addActionListener(
 2002 Prentice Hall, Inc.
All rights reserved.
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// anonymous inner class
new ActionListener() {
// handle text field event
public void actionPerformed( ActionEvent event )
{
String s = event.getActionCommand();
c = s.charAt( 0 );
buildOutput();
}
}
Outline
StaticCharMethod
s.java
// end anonymous inner class
); // end call to addActionListener
container.add( inputField );
outputArea = new JTextArea( 10, 20 );
container.add( outputArea );
setSize( 300, 250 );
show();
// set the window size
// show the window
}
// display character info in outputArea
public void buildOutput()
{
 2002 Prentice Hall, Inc.
All rights reserved.
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
outputArea.setText(
"is defined: " + Character.isDefined( c ) +
"\nis digit: " + Character.isDigit( c ) +
"\nis Java letter: " +
Character.isJavaIdentifierStart( c ) +
"\nis Java letter or digit: " +
Character.isJavaIdentifierPart( c ) +
"\nis letter: " + Character.isLetter( c ) +
"\nis letter or digit: " +
Character.isLetterOrDigit( c ) +
"\nis lower case: " + Character.isLowerCase(
"\nis upper case: " + Character.isUpperCase(
"\nto upper case: " + Character.toUpperCase(
"\nto lower case: " + Character.toLowerCase(
Outline
Determine whether c is
defined Unicode digit
StaticCharMethod
Determine whether
c can be used
s.java
as first character in identifier
Line 63
Determine whether c can be
c ) +
used as Line
identifier
66 character
c ) +
c ) +
c ) );
Determine whether c is a letter
Line 68
}
// execute application
public static void main( String args[] )
{
StaticCharMethods application = new StaticCharMethods();
application.addWindowListener(
Determine whether
Lineor69digit
c is letter
Linewhether
71
Determine
c is
uppercase or lowercase
Lines 72-73
// anonymous inner class
new WindowAdapter() {
// handle event when user closes window
public void windowClosing( WindowEvent windowEvent )
{
System.exit( 0 );
}
 2002 Prentice Hall, Inc.
All rights reserved.
93
94
95
96
97
98
99
100
}
// end anonymous inner class
); // end call to addWindowListener
}
}
// end method main
Outline
StaticCharMethod
s.java
// end class StaticCharMethods
 2002 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Fig. 10.18: StaticCharMethods2.java
// Demonstrates the static character conversion methods
// of class Character from the java.lang package.
// Java core packages
import java.awt.*;
import java.awt.event.*;
Outline
StaticCharMethod
s2.java
// Java extension packages
import javax.swing.*;
public class StaticCharMethods2 extends JFrame {
private char c;
private int digit, radix;
private JLabel prompt1, prompt2;
private JTextField input, radixField;
private JButton toChar, toInt;
public StaticCharMethods2()
{
super( "Character Conversion Methods" );
// set up GUI and event handling
Container container = getContentPane();
container.setLayout( new FlowLayout() );
prompt1 = new JLabel( "Enter a digit or character " );
input = new JTextField( 5 );
container.add( prompt1 );
container.add( input );
prompt2 = new JLabel( "Enter a radix " );
radixField = new JTextField( 5 );
container.add( prompt2 );
container.add( radixField );
 2002 Prentice Hall, Inc.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
toChar = new JButton( "Convert digit to character" );
toChar.addActionListener(
Outline
StaticCharMethod
s2.java
// anonymous inner class
new ActionListener() {
// handle toChar JButton event
public void actionPerformed( ActionEvent actionEvent )
{
digit = Integer.parseInt( input.getText() );
radix =
Integer.parseInt( radixField.getText() );
JOptionPane.showMessageDialog( null,
"Convert digit to character: " +
Character.forDigit( digit, radix ) );
}
}
// end anonymous inner class
); // end call to addActionListener
Use method forDigit to convert
int digit to number-system
character specified by int radix
container.add( toChar );
toInt = new JButton( "Convert character to digit" );
toInt.addActionListener(
// anonymous inner class
new ActionListener() {
 2002 Prentice Hall, Inc.
All rights reserved.
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// handle toInt JButton event
public void actionPerformed( ActionEvent actionEvent )
{
String s = input.getText();
c = s.charAt( 0 );
radix =
Integer.parseInt( radixField.getText() );
JOptionPane.showMessageDialog( null,
"Convert character to digit: " +
Character.digit( c, radix ) );
}
}
// end anonymous inner class
); // end call to addActionListener
Outline
StaticCharMethod
s2.java
Line 77
Use method digit to convert
char c to number-system
integer specified by int radix
container.add( toInt );
setSize( 275, 150 );
show();
// set the window size
// show the window
}
// execute application
public static void main( String args[] )
{
StaticCharMethods2 application = new StaticCharMethods2();
application.addWindowListener(
// anonymous inner class
new WindowAdapter() {
 2002 Prentice Hall, Inc.
All rights reserved.
100
101
102
103
104
105
106
107
108
109
110
111
112
// handle event when user closes window
public void windowClosing( WindowEvent windowEvent )
{
System.exit( 0 );
}
}
Outline
StaticCharMethod
s2.java
// end anonymous inner class
); // end call to addWindowListener
}
}
// end method main
// end class StaticCharMethods2
 2002 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Fig. 10.19: OtherCharMethods.java
// Demonstrate the non-static methods of class
// Character from the java.lang package.
// Java extension packages
import javax.swing.*;
public class OtherCharMethods {
Outline
OtherCharMethods
.java
Lines 18-23
// test non-static Character methods
public static void main( String args[] )
{
Character c1, c2;
c1 = new Character( 'A' );
c2 = new Character( 'a' );
String output = "c1 = " + c1.charValue() +
"\nc2 = " + c2.toString() +
"\n\nhash code for c1 = " + c1.hashCode() +
"\nhash code for c2 = " + c2.hashCode();
Characters non-static methods
charValue, toString,
hashCode and equals
if ( c1.equals( c2 ) )
output += "\n\nc1 and c2 are equal";
else
output += "\n\nc1 and c2 are not equal";
JOptionPane.showMessageDialog( null, output,
"Demonstrating Non-Static Character Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class OtherCharMethods
 2002 Prentice Hall, Inc.
All rights reserved.
Outline
OtherCharMethods
.java
 2002 Prentice Hall, Inc.
All rights reserved.
10.20 Class StringTokenizer
• Tokenizer
– Partition String into individual substrings
– Use delimiter
– Java offers java.util.StringTokenizer
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
// Fig. 10.20: TokenTest.java
// Testing the StringTokenizer class of the java.util package
// Java core packages
import java.util.*;
import java.awt.*;
import java.awt.event.*;
TokenTest.java
Line 29
// Java extension packages
import javax.swing.*;
public class TokenTest extends JFrame {
private JLabel promptLabel;
private JTextField inputField;
private JTextArea outputArea;
// set up GUI and event handling
public TokenTest()
{
super( "Testing Class StringTokenizer" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
promptLabel =
new JLabel( "Enter a sentence and press Enter" );
container.add( promptLabel );
inputField = new JTextField( 20 );
inputField contains String to
be parsed by StringTokenizer
inputField.addActionListener(
// anonymous inner class
new ActionListener() {
 2002 Prentice Hall, Inc.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Outline
// handle text field event
Useevent
StringTokenizer
to parse
public void actionPerformed( ActionEvent
)
{
String stringToTokenize with
String stringToTokenize =
default delimiter “ \n\t\r”
TokenTest.java
event.getActionCommand();
StringTokenizer tokens =
new StringTokenizer( stringToTokenize );
Lines 41-42
Count number of tokens
outputArea.setText( "Number of elements: " +
tokens.countTokens() + "\nThe tokens are:\n" );
Line 45
while ( tokens.hasMoreTokens() )
outputArea.append( tokens.nextToken() + "\n" );
Lines 47-48
}
}
// end anonymous inner class
Append next token to outputArea,
as long as tokens exist
); // end call to addActionListener
container.add( inputField );
outputArea = new JTextArea( 10, 20 );
outputArea.setEditable( false );
container.add( new JScrollPane( outputArea ) );
setSize( 275, 260 );
show();
// set the window size
// show the window
}
// execute application
public static void main( String args[] )
{
TokenTest application = new TokenTest();
 2002 Prentice Hall, Inc.
All rights reserved.
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
application.addWindowListener(
// anonymous inner class
new WindowAdapter() {
Outline
TokenTest.java
// handle event when user closes window
public void windowClosing( WindowEvent windowEvent )
{
System.exit( 0 );
}
}
// end anonymous inner class
); // end call to addWindowListener
}
}
// end method main
// end class TokenTest
 2002 Prentice Hall, Inc.
All rights reserved.
10.21 Card Shuffling and Dealing Simulation
• Develop DeckOfCards application
– Create deck of 52 playing cards using Card objects
– User deals card by clicking “Deal card” button
– User shuffles deck by clicking “Shuffle cards” button
– Use random-number generation
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
// Fig. 10.21: DeckOfCards.java
// Card shuffling and dealing program
// Java core packages
import java.awt.*;
import java.awt.event.*;
DeckOfCards.java
Lines 19 and 29
// Java extension packages
import javax.swing.*;
Line 30
public class DeckOfCards extends JFrame {
private Card deck[];
private int currentCard;
private JButton dealButton, shuffleButton;
private JTextField displayField;
private JLabel statusLabel;
// set up deck of cards and GUI
public DeckOfCards()
{
super( "Card Dealing Program" );
Lines 33-35
Deck of 52 Cards
String faces[] = { "Ace", "Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Jack", "Queen", "King" };
String suits[] =
{ "Hearts", "Diamonds", "Clubs", "Spades" };
deck = new Card[ 52 ];
currentCard = -1;
Most recently dealt Cards in deck array
(-1 if not Cards have been dealt)
// populate deck with Card objects
for ( int count = 0; count < deck.length; count++ )
deck[ count ] = new Card( faces[ count % 13 ],
suits[ count / 13 ] );
Fill deckarray
with Cards
2002 Prentice
Hall, Inc.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Outline
// set up GUI and event handling
Container container = getContentPane();
container.setLayout( new FlowLayout() );
dealButton = new JButton( "Deal card" );
dealButton.addActionListener(
// anonymous inner class
new ActionListener() {
DeckOfCards.java
Line 50
When user presses Deal Card
button, method dealCard
Line 53
gets next card in deck array
// deal one card
public void actionPerformed( ActionEvent actionEvent )
{
Card dealt = dealCard();
Display Card in JTextField
if ( dealt != null ) {
displayField.setText( dealt.toString() );
statusLabel.setText( "Card #: " + currentCard );
}
else {
displayField.setText(
"NO MORE CARDS TO DEAL" );
statusLabel.setText(
"Shuffle cards to continue" );
}
}
}
// end anonymous inner class
); // end call to addActionListener
container.add( dealButton );
 2002 Prentice Hall, Inc.
All rights reserved.
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
shuffleButton = new JButton( "Shuffle cards" );
shuffleButton.addActionListener(
// anonymous inner class
new ActionListener() {
Outline
DeckOfCards.java
// shuffle deck
Line 80
public void actionPerformed( ActionEvent actionEvent )
{
displayField.setText( "SHUFFLING ..." );
When user presses Shuffle
shuffle();
Cards button, method
displayField.setText( "DECK IS SHUFFLED" );
shuffle shuffles cards
}
}
// end anonymous inner class
); // end call to addActionListener
container.add( shuffleButton );
displayField = new JTextField( 20 );
displayField.setEditable( false );
container.add( displayField );
statusLabel = new JLabel();
container.add( statusLabel );
setSize( 275, 120 );
show();
// set window size
// show window
}
 2002 Prentice Hall, Inc.
All rights reserved.
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
Outline
// shuffle deck of cards with one-pass algorithm
public void shuffle()
{
currentCard = -1;
DeckOfCards.java
// for each card, pick another random card and swap them
for ( int first = 0; first < deck.length; first++ ) {
int second = ( int ) ( Math.random() * 52 );
Card temp = deck[ first ];
deck[ first ] = deck[ second ];
deck[ second ] = temp;
}
Lines 102-115
Shuffle cards by swapping
each Card
with
randomly
Lines
118-126
selected Card
Lines 114 and 123
dealButton.setEnabled( true );
}
// deal one card
public Card dealCard()
{
if ( ++currentCard < deck.length )
return deck[ currentCard ];
else {
dealButton.setEnabled( false );
return null;
}
}
If deck is not empty, a Card
object reference is returned;
otherwise, null is returned
Method setEnabled enables
and disables JButton
// execute application
public static void main( String args[] )
{
DeckOfCards app = new DeckOfCards();
app.addWindowListener(
 2002 Prentice Hall, Inc.
All rights reserved.
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
Outline
// anonymous inner class
new WindowAdapter() {
// terminate application when user closes window
public void windowClosing( WindowEvent windowEvent )
{
System.exit( 0 );
}
}
DeckOfCards.java
Lines 154-155
// end anonymous inner class
); // end call to addWindowListener
}
}
// end method main
// end class DeckOfCards
// class to represent a card
class Card {
private String face;
private String suit;
Store face name and suit for
specific Card, respectively
// constructor to initialize a card
public Card( String cardFace, String cardSuit )
{
face = cardFace;
suit = cardSuit;
}
 2002 Prentice Hall, Inc.
All rights reserved.
164
165
166
167
168
169
170
// return String represenation of Card
public String toString()
{
return face + " of " + suit;
}
}
Outline
DeckOfCards.java
// end class Card
 2002 Prentice Hall, Inc.
All rights reserved.
10.22 (Optional Case Study) Thinking About
Objects: Event Handling
• How objects interact
– Sending object sends message to receiving object
– We discuss how elevator-system objects interact
• Model system behavior
 2002 Prentice Hall, Inc. All rights reserved.
10.22 Thinking About Objects (cont.)
• Event
– Message that notifies an object of an action
• Action: Elevator arrives at Floor
• Consequence: Elevator sends elevatorArrived event
to Elevator’s Door
– i.e., Door is “notified” that Elevator has arrived
• Action: Elevator’s Door opens
• Consequence: Door sends doorOpened event to Person
– i.e., Person is “notified” that Door has opened
– Preferred naming structure
• Noun (“elevator”) preceded by verb (“arrived”)
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
// ElevatorModelEvent.java
// Basic event packet holding Location object
package com.deitel.jhtp4.elevator.event;
ElevatorModelEve
nt.java
// Deitel packages
import com.deitel.jhtp4.elevator.model.*;
public class ElevatorModelEvent {
Represents an event
in elevator simulation
// Location that generated ElevatorModelEvent
private Location location;
// source of generated ElevatorModelEvent
private Object source;
// ElevatorModelEvent constructor sets Location
public ElevatorModelEvent( Object source,
Location location )
{
setSource( source );
setLocation( location );
}
Line 8
Location object
Line reference
11
represents location where even
was generated
Line 14
Object object reference represents
object that generated event
// set ElevatorModelEvent Location
public void setLocation( Location eventLocation )
{
location = eventLocation;
}
// get ElevatorModelEvent Location
public Location getLocation()
{
return location;
}
 2002 Prentice Hall, Inc.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
// set ElevatorModelEvent source
private void setSource( Object eventSource )
{
source = eventSource;
}
Outline
ElevatorModelEve
nt.java
// get ElevatorModelEvent source
public Object getSource()
{
return source;
}
}
 2002 Prentice Hall, Inc.
All rights reserved.
10.22 Thinking About Objects (cont.)
• Every object sends ElevatorModelEvent
– This may become confusing
• Door sends ElevatorModelEvent to Person upon
opening
• Elevator sends ElevatorModelEvent to Door upon
arrival
– Solution:
• Create several ElevatorModelEvent subclasses
– Each subclass better represents action
– e.g., BellEvent when Bell rings
 2002 Prentice Hall, Inc. All rights reserved.
Fig. 10.23 Class diagram that models the generalization between
ElevatorModelEvent and its subclasses.
Eleva torM ode lEv ent
BellEv ent
Doo rEv ent
LightEve nt
Perso nMov eEve nt
 2002 Prentice Hall, Inc. All rights reserved.
ButtonEv ent
Elev atorM ove Eve nt
Fig. 10.24 Triggering actions of the ElevatorModelEvent subclass
events.
Event
Sent when (triggering action)
Sent by object of class
BellEvent
the Bell has rung
Bell
ButtonEvent
a Button has been pressed
a Button has been reset
Button
Button
DoorEvent
a Door has opened
a Door has closed
Door
Door
LightEvent
a Light has turned on
a Light has turned off
Light
PersonMoveEvent
a Person has been created
a Person has arrived at the Elevator
a Person has entered the Elevator
a Person has exited the Elevator
a Person has pressed a Button
a Person has exited the simulation
Person
ElevatorMoveEvent
the Elevator has arrived at a Floor
the Elevator has departed from a Floor
Elevator
Fig. 10.24 Triggering actions of the
ElevatorModelEvent subclass events.
 2002 Prentice Hall, Inc. All rights reserved.
10.22 Thinking About Objects (cont.)
• Event handling
– Similar to collaboration
– Object sends message (event) to objects
• However, receiving objects must be listening for event
– Called event listeners
– Listeners must register with sender to receive event
 2002 Prentice Hall, Inc. All rights reserved.
10.22 Thinking About Objects (cont.)
• Modify collaboration diagram of Fig. 7.20
– Incorporate event handling (Fig. 10.25)
– Three changes
• Include notes
– Explanatory remarks about UML graphics
– Represented as rectangles with corners “folded over”
• All interactions happen on first Floor
– Eliminates naming ambiguity
• Include events
– Elevator informs objects of action that has happened
• Elevator notifies object of arrival
 2002 Prentice Hall, Inc. All rights reserved.
Fig. 10.25 Modified collaboration diagram for passengers entering and
exiting the Elevator on the first Floor.
<<p aram et er>>
(DoorEvent )
3.2. 1 d oorO pened ( )
3.2 : op enDoor( )
f irst Floo rDoor : Do or
4.1.1 : reset But t on( )
4.2. 1 : turnO nLight ( )
: Elev at orShaf t
f irstFloorBut t on : But to n
4. 1 : eleva to rArriv ed( )
firstFloorLight : Light
4.2 : e lev at orArrive d( )
4 : eleva to rArriv ed( )
wa it ing Passeng er : Perso n
rid ingPa ssenger : Person
: Elev at or
3.2.1. 1 : ent erElev at or( )
3. 3.1 : e xit Eleva to r( )
3.3 : doo rO pe ne d( )
1 : eleva to rArriv ed( )
2 : eleva to r
Arriv ed( )
3 : eleva to r
Arriv ed( )
e lev at orBut t on: Butt on
ele vat orDoor: Doo r
: Bell
1.1: reset But t on( )
3.1: op enDoor( )
2.1: ring Bell( )
<<p aram et er>>
(Eleva to rMo veEvent )
 2002 Prentice Hall, Inc. All rights reserved.
<<p aram et er>>
(Lo c at ion)
10.22 Thinking About Objects (cont.)
• Event listeners
– Elevator sends ElevatorMoveEvent
• All event classes (in our simulation) have this structure
– Door must implement interface that “listens” for this event
– Door implements interface ElevatorMoveListener
• Method elevatorArrived
– Invoked when Elevator arrives
• Method elevatorDeparted
– Invoked when Elevator departs
 2002 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ElevatorMoveEvent.java
// Indicates on which Floor the Elevator arrived or departed
package com.deitel.jhtp4.elevator.event;
// Deitel package
import com.deitel.jhtp4.elevator.model.*;
Outline
ElevatorMoveEven
t.java
public class ElevatorMoveEvent extends ElevatorModelEvent {
// ElevatorMoveEvent constructor
public ElevatorMoveEvent( Object source, Location location )
{
super( source, location );
}
}
 2002 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
// ElevatorMoveListener.java
// Methods invoked when Elevator has either departed or arrived
package com.deitel.jhtp4.elevator.event;
public interface ElevatorMoveListener {
Outline
ElevatorMoveList
ener.java
// invoked when Elevator has departed
public void elevatorDeparted( ElevatorMoveEvent moveEvent );
// invoked when Elevator has arrived
public void elevatorArrived( ElevatorMoveEvent moveEvent );
}
 2002 Prentice Hall, Inc.
All rights reserved.
10.22 Thinking About Objects (cont.)
• Class diagram revisited
– Modify class diagram of Fig. 9.19 to include
• Signals (events)
– e.g., Elevator signals arrival to Light
• Self associations
– e.g., Light turns itself on and off
 2002 Prentice Hall, Inc. All rights reserved.
Fig. 10.28 Class diagram of our simulator (including event handling).
C re at es
1
1
Light
Turns
1 on/ off
2
1
Elev at orShaft
1
Sig na ls
arriva l
1
O p ens/
C lo ses
Do or
Reset s
1
Signals
a rriv al
1
1
1
Floo r
1
1
1
2
1
Signals
a rriv al
2
1
Eleva to rMo del
2
Butt on
1
0.. *
Pre sses
1
1
Perso n
1
1
1
Info rms of
o pening
Signals
a rriv al
1
1
Signalst o
m ove
Elev at or
1
1
Signals
a rriv al
Rings
1
2
1
Lo c at ion
1
Bell
1
1
 2002 Prentice Hall, Inc. All rights reserved.
O c c up ies
Sig na ls
arriva l