Transcript Java set 12

Chapter 10 - Strings and Characters
10.1 Introduction
• In this chapter
– Discuss class String, StringBuffer, and Character
(java.lang)
– Discuss class StringTokenizer (java.util)
– Techniques used here appropriate for making word
processors, text editors, page layout software
10.2 Fundamentals of Characters and
Strings
• Characters
– Character constant - integer represented as a character in
single quotes (Unicode character set)
• 'z' is integer value of z
• Strings
– Group of characters treated as a single unit
– May include letters, digits, special characters (+,- *...)
– Strings are objects of class String
10.2 Fundamentals of Characters and
Strings
• Strings (continued)
– String literal (string constants or anonymous String
objects)
• Sequence of characters written in double quotes
• "John Q. Doe" or "111222333"
• Java treats all anonymous String objects with same contents
as one object with many references
– Assigning strings
• May assign in declaration
String color = "blue";
• color is a String reference
10.3 String Constructors
• Constructors for class String
– s1 = new String()
• s1 is an empty string
– s2 = new String( anotherString )
• s2 is a copy of anotherString
– s3 = new String( charArray )
• s3 contains all the characters in charArray
– s4 = new String( charArray, offset,
numElements )
• s4 contains numElements characters from charArray,
starting at location offset
– s5 = new String( byteArray, offset,
numElements)
• As above, but with a byteArray
10.3 String Constructors
• Constructors for class String
– s6 = new String( byteArray )
• s6 contains copy of entire byteArray
• StringBuffer
– Dynamically resizable, modifiable string (more later)
– StringBuffer buffer = new StringBuffer(
"Hello there" );
– Can initialize Strings with StringBuffers
s7 = new String( myStringBuffer )
1// Fig. 10.1: StringConstructors.java
2// This program demonstrates the String class constructors.
3import javax.swing.*;
4
5public class StringConstructors {
6
public static void main( String args[] )
7
{
8
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ',
9
'd', 'a', 'y' };
10
byte byteArray[] = { (byte) 'n', (byte) 'e', (byte) 'w',
11
(byte) ' ', (byte) 'y', (byte) 'e',
12
(byte) 'a', (byte) 'r' };
13
StringBuffer buffer;
14
String s, s1, s2, s3, s4, s5, s6, s7, output;
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
s = new String( "hello" );
buffer =
new StringBuffer( "Welcome to Java Programming!" );
//
s1
s2
s3
s4
s5
s6
s7
use the 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 );
Class
StringConstructors
1. main
1.1 Initialize arrays
1.2 Declarations
1.3 Constructors
30
31
32
33
34
35
36
output = "s1 =
"\ns2
"\ns3
"\ns4
"\ns5
"\ns6
"\ns7
"
=
=
=
=
=
=
+
"
"
"
"
"
"
s1 +
+ s2 +
+ s3 +
+ s4 +
+ s5 +
+ s6 +
+ s7;
2. Append output
3. GUI
37
38
39
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Constructors",
40
JOptionPane.INFORMATION_MESSAGE );
41
42
43
44 }
System.exit( 0 );
}
Program Output
10.4 String Methods length, charAt and
getChars
• String methods
– s1.length()
• Returns length of string
• Be careful, Strings do not have an instance variable
length like arrays
– s1.length is an error
– s1.charAt( index )
• Returns char at location index
• Numbered like arrays (start at position 0)
– s1.getChars( start, end, charArray,
offset )
• Copies characters in s1 from index start to index end to
location offset in charArray
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.2: StringMisc.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.
import javax.swing.*;
public class StringMisc {
public static void main( String args[] )
{
String s1, output;
char charArray[];
Class StringMisc
1. main
1.1 Initialization
1.2 Output
2. s1.length()
s1 = new String( "hello there" );
charArray = new char[ 5 ];
// output the string
output = "s1: " + s1;
// test the length method
output += "\nLength of s1: " + s1.length();
// loop through the characters in s1 and display reversed
output += "\nThe string reversed is: ";
for ( int i = s1.length() - 1; i >= 0; i-- )
output += s1.charAt( i ) + " ";
3. Loop and print
reversed characters
33
34
35
36
37
38
39
// copy characters from string into char array
s1.getChars( 0, 5, charArray, 0 );
output += "\nThe character array is: ";
40
41
42
43
44
45
46 }
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Constructors",
JOptionPane.INFORMATION_MESSAGE );
for ( int i = 0; i < charArray.length; i++ )
output += charArray[ i ];
4. getChars
5. GUI
System.exit( 0 );
}
Program Output
10.5 Comparing Strings
• Comparing Strings
– All characters represented as numeric codes (Appendix D)
– When computer compares strings, compares numeric codes
• Lexicographical comparison - compare Unicode values
• Lowercase different than uppercase
• Comparison methods
– s1.equals( "Hi" )
• Returns true if s1 equal to "Hi"
• Capitalization (case) matters
– s1.equalsIgnoreCase( otherString )
• Tests for equality, case does not matter
• "hello" equal to "HELLO"
10.5 Comparing Strings
• Comparison methods
– s1.compareTo( otherString )
•
•
•
•
Uses lexicographical comparison
Returns 0 if strings equal
Returns negative number if s1 < otherString
Returns positive number if s1 > otherString
– s1.regionMatches( offset, otherString,
start, end )
• Compares s1 from location offset to otherString from
location start to end
– s1.regionMatches( ignoreCase, offset,
otherString, start, end )
• As above, but if ignoreCase is true, case is ignored
10.5 Comparing Strings
• == operator
– When used with primitive data types, returns true if equal
– When used with references, returns true if point to same
location in memory
– Remember, Java treats all anonymous String objects with
same contents as one object with many references
s1
s2
s1
s2
= "hello";
= new String(
== "hello";
== "hello";
//uses anonymous object
"hello" );
//true
//false
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.3: StringCompare
// This program demonstrates the methods equals,
// equalsIgnoreCase, compareTo, and regionMatches
// of the String class.
import javax.swing.JOptionPane;
public class StringCompare {
public static void main( String args[] )
{
String s1, s2, s3, s4, output;
s1
s2
s3
s4
=
=
=
=
new
new
new
new
String(
String(
String(
String(
"hello" );
"good bye" );
"Happy Birthday" );
"happy birthday" );
Class StringCompare
1. main
1.1 Initialization
1.2 Append output
2. Tests for equality
output = "s1 = " + s1 + "\ns2 = " + s2 +
"\ns3 = " + s3 + "\ns4 = " + s4 + "\n\n";
// test for equality
s1 will fail this test because it was not
if ( s1.equals( "hello" ) )
initialized with an anonymous String
output += "s1 equals \"hello\"\n";
object.
else
output += "s1 does not equal \"hello\"\n";
// test for equality with ==
if ( s1 == "hello" )
output += "s1 equals \"hello\"\n";
else
output += "s1 does not equal \"hello\"\n";
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
59
60
// 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";
2. Tests for equality
3. compareTo
s2
s1
s1
s4
s3
)
)
)
)
)
is
is
is
is
is
"
"
"
"
"
+
+
+
+
+
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";
// 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";
4. regionMatches
61
62
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Constructors",
63
JOptionPane.INFORMATION_MESSAGE );
64
65
66
System.exit( 0 );
5. GUI
}
67 }
Program Output
Using equals, ==, and
equalsIgnoreCase
10.6 String Method hashCode
• Hash table
– Fast access to data
– Stores information using a calculation that makes a hash
code
• Code used to choose location to store object in table
– To retrieve information, use same calculation
• Hash code determined, go to that location of table
• Get original value
– Every object can be stored in a hash table
– Class Object defines method hashCode
• Inherited by all subclasses
• hashCode overridden in class String to provide a good
hash code distribution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 10.5: StringHashCode.java1
// This program demonstrates the method
// hashCode of the String class.
import javax.swing.*;
public class StringHashCode {
public static void main( String args[] )
{
String s1 = "hello",
s2 = "Hello";
Class
StringHashCode
1. main
String output =
"The hash code for \"" + s1 + "\" is " +
s1.hashCode() +
"\nThe hash code for \"" + s2 + "\" is " +
s2.hashCode();
1.1 Initialization
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Method hashCode",
JOptionPane.INFORMATION_MESSAGE );
3. GUI
2. hashCode
System.exit( 0 );
}
}
Program Output
10.7 Locating Characters and Substrings in
Strings
• Search methods
– s1.indexOf( integerRep )
• integerRep - integer representation of a character ('z')
• Returns index of the first occurrence of the character in the
string
– Returns -1 if not found
– s1.indexOf( integerRep, startSearch )
• As above, but begins search at position startSearch
– s1.lastIndexOf( integerRep )
• Returns index of last occurrence of character in string
– s1.lastIndexOf( integerRep, startSearch )
• As above, but searches backwards from position
startSearch
10.7 Locating Characters and Substrings in
Strings
• Search methods (continued)
– Can use indexOf and lastIndexOf with Strings
– Search for substrings within a string
• Identical usage as with characters, i.e.
s1.indexOf( "hi" )
s1.lastIndexOf( "this", 24 )
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
// Fig. 10.6: StringIndexMethods.java
// This program demonstrates the String
// class index methods.
import javax.swing.*;
Class
StringIndexMethods
public class StringIndexMethods {
public static void main( String args[] )
{
String letters = "abcdefghijklmabcdefghijklm";
String output;
// test indexOf to locate a character in a string
output = "'c' is located at index " +
letters.indexOf( 'c' );
output += "\n'a' is located at index " +
letters.indexOf( 'a', 1 );
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 );
1. main
1.1 Initialization
2. indexOf (two
versions)
3. lastIndexOf (two
versions)
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
59 }
60
output += "\nLast '$' is located at index " +
letters.lastIndexOf( '$' );
// 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" );
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 );
}
4. indexOf (two
versions)
5. lastIndexOf (two
versions)
6. GUI
Program Output
10.8 Extracting Substrings from Strings
• substring methods
– Return a String object
– s1.substring( startIndex )
• Returns a substring from startIndex to the end of the
string
– s1.substring( start, end )
• Returns a substring from location start up to, but not
including, location end
– If index out of bounds,
StringIndexOutOfBoundsException generated
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
// Fig. 10.7: SubString.java
// This program demonstrates the
// String class substring methods.
import javax.swing.*;
public class SubString {
public static void main( String args[] )
{
String letters = "abcdefghijklmabcdefghijklm";
String output;
// test substring methods
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 ) + "\"";
Class Substring
1. main
1.1 Initialization
2. substring methods
3. GUI
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Substring Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Program Output
10.9 Concatenating Strings
• Method concat
– Concatenates two Strings, returns new String object
– Original Strings are not modified
– s1.concat( s2 )
• Returns concatenation of s1 and s2
• If no argument, returns s1
1
2
// Fig. 10.8: StringConcat.java
// This program demonstrates the String class concat method.
3
4
// Note that the concat method returns a new String object. It
// does not modify the object that invoked the concat method.
5
6
7
import javax.swing.*;
Class StringConcat
public class StringConcat {
1. main
8
9
10
public static void main( String args[] )
{
String s1 = new String( "Happy " ),
11
12
s2 = new String( "Birthday" ),
output;
13
14
15
output = "s1 = " + s1 +
"\ns2 = " + s2;
16
17
18
output += "\n\nResult of s1.concat( s2 ) = " +
s1.concat( s2 );
19
20
output += "\ns1 after concatenation = " + s1;
21
22
23
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Method concat",
24
25
26
27
28 }
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
1.1 Initialization
2. concat
3. GUI
Program Output
10.10 Miscellaneous String Methods
• Miscellaneous methods
– s1.replace( char1, char2 )
• Returns a new String, replacing all instances of char1 with
char2
– Use integer representations: 'z', '1', etc.
– Original String not changed
• If no instances of char1, original string returned
– s1.toUpperCase()
• Returns new String object with all letters capitalized
– If no changes needed, original string returned
• Original string unchanged
• s1.toLowerCase() similar
10.10 Miscellaneous String Methods
• Miscellaneous methods (continued)
– s1.trim()
• Returns new String, removing all whitespace characters at
beginning or end
• Original unchanged
– s1.toString()
• All objects can be converted to Strings with toString
– s1.toCharArray()
• Creates a new character array containing copy of characters in
s1
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
// Fig. 10.9: StringMisc2.java
// This program demonstrates the String methods replace,
// toLowerCase, toUpperCase, trim, toString and toCharArray
import javax.swing.*;
Class StringMisc2
public class StringMisc2 {
public static void main( String args[] )
{
String s1 = new String( "hello" ),
s2 = new String( "GOOD BYE" ),
s3 = new String( "
spaces
" ),
output;
1. main
1.1 Initialization
2. replace
output = "s1 = " + s1 +
"\ns2 = " + s2 +
"\ns3 = " + s3;
// test method replace
output += "\n\nReplace 'l' with 'L' in s1: " +
s1.replace( 'l', 'L' );
// test toLowerCase and toUpperCase
output +=
"\n\ns1.toUpperCase() = " + s1.toUpperCase() +
"\ns2.toLowerCase() = " + s2.toLowerCase();
// test trim method
output += "\n\ns3 after trim = \"" + s3.trim() + "\"";
3. toUpperCase and
toLowerCase
4. trim
30
31
32
33
34
// test toString method
output += "\n\ns1 = " + s1.toString();
// test toCharArray method
char charArray[] = s1.toCharArray();
5. toString
35
36
output += "\n\ns1 as a character array = ";
6. toCharArray
37
38
for ( int i = 0; i < charArray.length; ++i )
39
output += charArray[ i ];
40
41
JOptionPane.showMessageDialog( null, output,
42
"Demonstrating Miscellaneous String Methods",
43
JOptionPane.INFORMATION_MESSAGE );
44
45
46
47 }
System.exit( 0 );
}
7. GUI
Program Output
10.11 Using String Method valueOf
• static methods of class String
– Take arguments and convert them to Strings
– String.valueOf( charArray )
• Returns new String object containing characters in
charArray
– String.valueOf( charArray, startIndex,
numChars )
• As above, but starts from position startIndex and copies
numChars characters
– Other versions of valueOf take boolean, char, int,
long, float, double, and Object
• Objects converted to Strings with toString
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
// Fig. 10.10: StringValueOf.java
// This program demonstrates the String class valueOf methods.
import javax.swing.*;
public class StringValueOf {
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;
// 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 ) +
"\nint = " + String.valueOf( i ) +
"\nlong = " + String.valueOf( l ) +
"\nfloat = " + String.valueOf( f ) +
"\ndouble = " + String.valueOf( d ) +
"\nObject = " + String.valueOf( o );
Class StringValueOf
1. main
1.1 Initialization
2. valueOf
30
JOptionPane.showMessageDialog( null, output,
31
"Demonstrating String Class valueOf Methods",
32
JOptionPane.INFORMATION_MESSAGE );
33
34
35
System.exit( 0 );
3. GUI
}
36 }
Program Output
10.12 String Method intern
• Method intern
– Improves string comparison performance
– Returns reference guaranteed to have same contents
• Multiple interns generate references to same object
– Strings can be compared with == (same location in
memory) instead of equals
• Much faster than comparing character by character
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.11: StringIntern.java
// This program demonstrates the intern method
// of the String class.
import javax.swing.*;
public class StringIntern {
public static void main( String args[] )
{
String s1, s2, s3, s4, output;
Class StringIntern
1. main
1.1 Initialization
s1 = new String( "hello" );
s2 = new String( "hello" );
// Test strings to determine if they are the 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";
2. Comparisons using
==
2.1 Comparisons using
equals
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
59
//
//
s3
s4
Use String intern method to get a unique copy of
"hello" referred to by both s3 and s4.
= s1.intern();
= s2.intern();
intern
Because s1 and s2 have the same 3.
contents,
s3
s4are
are references
ifand
they
the same to the same object in
memory.
// Test strings to determine
// 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";
// Determine if s1 and s3 refer to the 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 the 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";
4. Comparisons using
==
60
// Determine if s1 and s4 refer to the same object
61
if ( s1 == s4 )
62
output +=
63
"\ns1 and s4 are the same object in memory";
64
4. Comparisons using
==
else
65
output +=
66
67
"\ns1 and s4 are not the same object in memory";
68
JOptionPane.showMessageDialog( null, output,
69
"Demonstrating String Method intern",
70
JOptionPane.INFORMATION_MESSAGE );
71
72
73
74 }
75
System.exit( 0 );
}
5. GUI
s1 and s2 both contain "hello" but are not the
same object.
s3 and s4 were interned from s1 and s2, and
are the same object in memory.
Program Output
10.13 StringBuffer Class
• Class String
– Once a String is created, it cannot be changed
• Class StringBuffer
– Can create modifiable Strings
– Capable of storing number of characters specified by
capacity
• If capacity exceeded, automatically expands to hold new
characters
– Can use + and += operators
10.14 StringBuffer Constructors
• StringBuffer constructors
– buf1 = new StringBuffer();
• Creates empty StringBuffer, capacity of 16 characters
– buf2 = new StringBuffer( capacity );
• Creates empty StringBuffer with specified capacity
– but3 = new StringBuffer( myString );
• Creates a StringBuffer containing myString, with
capacity myString.length() + 16
1
// Fig. 10.12: StringBufferConstructors.java
2 // This program demonstrates the StringBuffer constructors.
3
import javax.swing.*;
4
5
public class StringBufferConstructors {
6
public static void main( String args[] )
7
{
8
StringBuffer buf1, buf2, buf3;
Class StringBuffer
Constructors
1. main
9
10
buf1 = new StringBuffer();
11
buf2 = new StringBuffer( 10 );
12
buf3 = new StringBuffer( "hello" );
1.1 Initialization (note
use of constructors)
String output =
2. Output
13
14
15
"buf1 = " + "\"" + buf1.toString() + "\"" +
16
"\nbuf2 = " + "\"" + buf2.toString() + "\"" +
17
"\nbuf3 = " + "\"" + buf3.toString() + "\"";
18
19
JOptionPane.showMessageDialog( null, output,
20
"Demonstrating StringBuffer Class Constructors",
21
JOptionPane.INFORMATION_MESSAGE );
22
23
24
25 }
System.exit( 0 );
}
3. GUI
Program Output
10.15 StringBuffer Methods length,
capacity, setLength and
ensureCapacity
• StringBuffer methods
– length - returns length
– capacity - returns capacity
– setLength( newLength )
• Changes length of StringBuffer to newLength
• If too long, truncates excess characters
• If too short, fills with null character (numeric representation of
0)
– ensureCapacity( size )
• Expands capacity to a minimum of size
• If size less than current capacity, then capacity is unchanged
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.13: StringBufferCapLen.java
// This program demonstrates the length and
// capacity methods of the StringBuffer class.
import javax.swing.*;
public class StringBufferCapLen {
public static void main( String args[] )
{
StringBuffer buf =
new StringBuffer( "Hello, how are you?" );
String output = "buf = " + buf.toString() +
"\nlength = " + buf.length() +
"\ncapacity = " + buf.capacity();
buf.ensureCapacity( 75 );
output += "\n\nNew capacity = " + buf.capacity();
buf.setLength( 10 );
output += "\n\nNew length = " + buf.length() +
"\nbuf = " + buf.toString();
JOptionPane.showMessageDialog( null, output,
"StringBuffer length and capacity Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Class
StringBufferCapLen
1. main
1.1 Initialization
2. length
2.1 capacity
3. ensureCapacity
3.1 setLength
4. GUI
Program Output
10.16StringBuffer Methods charAt,
setCharAt, getChars and reverse
• StringBuffer methods
– charAt( index ) - returns character at position index
– setCharAt( index, char )
• Sets character at position index to char
– getChars( start, end, charArray, loc )
• Copies from position start up to (not including) end into
location loc in charArray
– reverse - reverses contents of StringBuffer
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.14: StringBufferChars.java
// The charAt, setCharAt, getChars, and reverse methods
// of class StringBuffer.
import javax.swing.*;
public class StringBufferChars {
public static void main( String args[] )
{
StringBuffer buf = new StringBuffer( "hello there" );
String output = "buf = " + buf.toString() +
"\nCharacter at 0: " + buf.charAt( 0 ) +
"\nCharacter at 4: " + buf.charAt( 4 );
Class
StringBufferChars
1. main
1.1 Initialization
2. charAt
char charArray[] = new char[ buf.length() ];
buf.getChars( 0, buf.length(), charArray, 0 );
output += "\n\nThe characters are: ";
for ( int i = 0; i < charArray.length; ++i )
output += charArray[ i ];
buf.setCharAt( 0, 'H' );
buf.setCharAt( 6, 'T' );
output += "\n\nbuf = " + buf.toString();
buf.reverse();
output += "\n\nbuf = " + buf.toString();
3. getChars
4. setCharAt
5. reverse
29
30
31
32
33
34
35
36 }
JOptionPane.showMessageDialog( null, output,
"Demonstrating StringBuffer Character Methods",
JOptionPane.INFORMATION_MESSAGE );
6. GUI
System.exit( 0 );
}
Program Output
10.17 StringBuffer append Methods
• 10 overloaded append methods
– Versions for each of the primitive data types, character arrays,
Strings, and Objects (using toString)
– StringBuffers and append used by compiler to concatenate
Strings
String s = "BC" + 22;
actually performed as
new StringBuffer( "BC").append(22).toString();
• StringBuffer created with String "BC" as contents
• Integer 22 appended to StringBuffer
• StringBuffer converted to a String (toString)
• Result assigned to s
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.15: StringBufferAppend.java
// This program demonstrates the append
// methods of the StringBuffer class.
import javax.swing.*;
public class StringBufferAppend {
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 buf = new StringBuffer();
buf.append( o );
buf.append( " " );
buf.append(
buf.append(
buf.append(
buf.append(
buf.append(
buf.append(
buf.append(
buf.append(
s );
" " );
charArray );
" " );
charArray, 0, 3 );
" " );
b );
" " );
Class
StringBufferAppend
1. main
1.1 Initialization
2. append
31
32
33
34
35
36
37
38
39
buf.append(
buf.append(
buf.append(
buf.append(
buf.append(
buf.append(
buf.append(
buf.append(
buf.append(
40
41
42
43
44
45
46
47
48 }
c
"
i
"
l
"
f
"
d
);
"
);
"
);
"
);
"
);
);
);
2. append
);
);
3. GUI
JOptionPane.showMessageDialog( null,
"buf = " + buf.toString(),
"Demonstrating StringBuffer append Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
Program Output
10.18 StringBuffer Insertion and Deletion
Methods
• Nine overloaded insert methods
– Insert various data at any position in StringBuffer
– insert( index, data )
• Inserts data right before position index
• index must be greater than or equal to 0
• delete methods
– delete( start, end )
• Deletes from start up to (not including) end
– deleteCharAt( index )
• Deletes character at index
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.16: StringBufferInsert.java
// This program demonstrates the insert and delete
// methods of class StringBuffer.
import javax.swing.*;
public class StringBufferInsert {
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 buf = new StringBuffer();
buf.insert(
buf.insert(
buf.insert(
buf.insert(
buf.insert(
buf.insert(
buf.insert(
0,
0,
0,
0,
0,
0,
0,
o );
" " );
s );
" " );
charArray );
" " );
b );
buf.insert( 0, " " );
buf.insert( 0, c );
buf.insert( 0, " " );
Class
StringBufferInsert
1. main
1.1 Initialization
2. insert
31
32
33
34
buf.insert(
buf.insert(
buf.insert(
buf.insert(
0,
0,
0,
0,
i );
" " );
l );
" " );
35
buf.insert( 0, f );
36
buf.insert( 0, "
37
buf.insert( 0, d );
2. insert
" );
3. deleteCharAt
38
39
String output = "buf after inserts:\n" + buf.toString();
4. delete
40
41
buf.deleteCharAt( 10 );
// delete 5 in 2.5
42
buf.delete( 2, 6 );
// delete .333 in 33.333
43
44
output += "\n\nbuf after deletes:\n" + buf.toString();
45
46
JOptionPane.showMessageDialog( null, output,
47
"Demonstrating StringBufferer Inserts and Deletes",
48
JOptionPane.INFORMATION_MESSAGE );
49
50
51
52 }
System.exit( 0 );
}
Program Output
10.19 Character Class Examples
• Classes to treat primitive variables as objects
– type wrappers: Boolean, Character, Double, Float,
Byte, Short, Integer and Long
• All but Boolean and Character derive from Number
• Objects of these classes can be used anywhere an Object or
Number is expected
– In this section, study class Character (for information on
all type-wrappers see java.lang package in API)
• Class Character
10.19 Character Class Examples
• Class Character static methods
– Let c be a char
– Character.isDefined( c )
• Returns true if character defined in Unicode character set
– Character.isJavaIdentifierStart ( c )
• Returns true if character can be used as first letter of an
identifier (letter, underscore ( _ ) or dollar sign ( $ ) )
– Character.isJavaIdentifierPart( c )
• Returns true if character can be used in an identifier (letter,
digit, underscore, or dollar sign)
– Character.isDigit( c )
– Character.isLetter( c )
• Character.isLetterOrDigit( c )
10.19 Character Class Examples
• Class Character static methods
– Character.isLowerCase( c )
• Character.toLowerCase( c )
– Returns converted character
– Returns original if no change needed
– Character.isUpperCase( c )
• Character.toUpperCase( c )
– Character.digit( c, radix )
• Converts character c into a digit of base radix
– Character.forDigit( digit, radix )
• Converts integer digit into a character using base radix
10.19 Character Class Examples
• Non-static methods of class Character
– c1.charValue()
• Returns char value stored in Character object c1
– c1.toString()
• Returns String representation of c1
– c1.hashCode()
• Performs hashCode calculations
• Remember, used to store objects in hash tables for fast lookup
– c1.equals( c2 )
• Determines if c1 has same contents as c2
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
// Fig. 10.17: StaticCharMethods.java
// Demonstrates the static character testing methods
// and case conversion methods of class Character
// from the java.lang package.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class StaticCharMethods extends JFrame {
private char c;
private JLabel prompt;
private JTextField input;
private JTextArea outputArea;
public StaticCharMethods()
{
super( "Static Character Methods" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
prompt =
new JLabel( "Enter a character and press Enter" );
container.add( prompt );
input = new JTextField( 5 );
input.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
Class
StaticCharMethods
1. main
1.1 Declarations
2. Constructor
2.1 GUI
30
31
{
String s = e.getActionCommand();
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
59
c = s.charAt( 0 );
buildOutput();
}
2.2 Event handler
}
);
container.add( input );
2.3 GUI
outputArea = new JTextArea( 10, 20 );
container.add( outputArea );
3. buildOutput
setSize( 300, 250 );
show();
3.1 static method
calls
// set the window size
// show the window
}
public void buildOutput()
{
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( c ) +
60
61
62
63
64
65
66
67
"\nis upper case: " + Character.isUpperCase( c ) +
"\nto upper case: " + Character.toUpperCase( c ) +
"\nto lower case: " + Character.toLowerCase( c ) );
}
public static void main( String args[] )
{
StaticCharMethods application = new StaticCharMethods();
4. main
68
69
application.addWindowListener(
70
new WindowAdapter() {
71
public void windowClosing( WindowEvent e )
72
{
73
System.exit( 0 );
74
}
75
}
76
77
3.1 static method
calls
);
}
Program Output
10.20 Class StringTokenizer
• Tokenization
– Breaking statements into pieces
– Class StringTokenizer breaks a String into
component tokens
• Tokens separated by delimiters, typically whitespace characters
• Other characters may be used
• Class StringTokenizer
– One constructor: StringTokenizer( myString )
• Initialize StringTokenizer with a String
• Default delimiter " \n\t\r" (space, newline, tab, carriage
return)
• Other constructors allow you to specify delimiter
10.20 Class StringTokenizer
• Methods
– countTokens()
• Determines number of tokens in String
– nextToken()
• Returns next token as a String
– nextToken( delimiterString )
• Changes delimiter while tokenizing a String
– hasMoreTokens()
• Determines if there are more tokens to be tokenized
1
// Fig. 10.20: TokenTest.java
2
// Testing the StringTokenizer class of the java.util package
3
import javax.swing.*;
4
5
import java.util.*;
import java.awt.*;
6
7
import java.awt.event.*;
8
public class TokenTest extends JFrame {
9
10
private JLabel prompt;
private JTextField input;
11
private JTextArea output;
12
13
14
15
public TokenTest()
{
super( "Testing Class StringTokenizer" );
16
17
18
Container c = getContentPane();
c.setLayout( new FlowLayout() );
19
20
prompt =
21
22
new JLabel( "Enter a sentence and press Enter" );
c.add( prompt );
23
24
input = new JTextField( 20 );
25
input.addActionListener(
26
27
28
new ActionListener() {
Class TokenTest
1. Constructor
1.1 GUI
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
59
60
public void actionPerformed( ActionEvent e )
{
String stringToTokenize = e.getActionCommand();
StringTokenizer tokens =
new StringTokenizer( stringToTokenize );
output.setText( "Number of elements: " +
tokens.countTokens() +
"\nThe tokens are:\n" );
while ( tokens.hasMoreTokens() )
output.append( tokens.nextToken() + "\n" );
1.2 Event handler
1.2.1 Tokenize String
1.3 GUI
}
}
);
c.add( input );
Notice loop to tokenize the 2.
string
main
output = new JTextArea( 10, 20 );
output.setEditable( false );
c.add( new JScrollPane( output ) );
setSize( 275, 260 );
show();
// set the window size
// show the window
}
public static void main( String args[] )
{
TokenTest app = new TokenTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
61
{
62
System.exit( 0 );
63
}
64
}
65
66
);
}
67 }
Program Output
10.21 A Card Shuffling and Dealing
Simulation
• Create card shuffling/dealing simulation
– Create class Card with variables face and suit
– Create deck, an array of Cards
– To shuffle cards
• Loop through deck array
• Generate random number (0-51) and swap current card with
that card
– To deal cards, walk through deck array
• After all cards are dealt, ask user to shuffle again
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.21: DeckOfCards.java
// Card shuffling and dealing program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DeckOfCards extends JFrame {
private Card deck[];
private int currentCard;
private JButton dealButton, shuffleButton;
private JTextField displayCard;
private JLabel status;
public DeckOfCards()
{
super( "Card Dealing Program" );
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;
for ( int i = 0; i < deck.length; i++ )
deck[ i ] = new Card( faces[ i % 13 ],
suits[ i / 13 ] );
Class DeckOfCards
1. Instance variables
1.1 Constructor
1.2 Initialize arrays
1.3 Create deck array
1.4 Initialize deck
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
59
60
Container c = getContentPane();
c.setLayout( new FlowLayout() );
dealButton = new JButton( "Deal card" );
dealButton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
Card dealt = dealCard();
if ( dealt != null ) {
displayCard.setText( dealt.toString() );
status.setText( "Card #: " + currentCard );
}
else {
displayCard.setText(
"NO MORE CARDS TO DEAL" );
status.setText(
"Shuffle cards to continue" );
}
}
}
);
c.add( dealButton );
shuffleButton = new JButton( "Shuffle cards" );
shuffleButton.addActionListener(
new ActionListener() {
2. GUI
2.1 Event handlers
3. GUI
61
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
}
public void actionPerformed( ActionEvent e )
{
displayCard.setText( "SHUFFLING ..." );
shuffle();
displayCard.setText( "DECK IS SHUFFLED" );
}
);
c.add( shuffleButton );
3.1 Event handler
4. GUI
displayCard = new JTextField( 20 );
displayCard.setEditable( false );
c.add( displayCard );
5. shuffle
status = new JLabel();
c.add( status );
setSize( 275, 120 );
show();
// set the window size
// show the window
}
public void shuffle()
{
currentCard = -1;
Swap current Card with random Card.
for ( int i = 0; i < deck.length; i++ ) {
int j = ( int ) ( Math.random() * 52 );
Card temp = deck[ i ];
// swap
deck[ i ] = deck[ j ];
// the
deck[ j ] = temp;
// cards
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120 }
}
dealButton.setEnabled( true );
}
6. dealCard
public Card dealCard()
{
if ( ++currentCard < deck.length )
return deck[ currentCard ];
else {
dealButton.setEnabled( false );
return null;
}
}
public static void main( String args[] )
{
DeckOfCards app = new DeckOfCards();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
7. main
121
122 class Card {
123
private String face;
124
private String suit;
125
126
public Card( String f, String s )
127
{
128
face = f;
129
suit = s;
130
}
131
132
public String toString() { return face + " of " + suit; }
133 }
Class Card
Program Output