Download String

Document related concepts
no text concepts found
Transcript
Chapter 7 Strings
Prerequisites for Part II
Chapter 5 Arrays
Chapter 6 Objects and Classes
Chapter 7 Strings
You can cover GUI after Chapter 8
Chapter 8 Inheritance and Polymorphism
Chapter 11 Getting Started with GUI Programming
Chapter 9 Abstract Classes and Interfaces
Chapter 12 Event-Driven Programming
Chapter 10 Object-Oriented Modeling
Chapter 15 Exceptions and Assertions
Some people hear their own inner voices
with great clearness, they live by what
they hear…
You can cover Exceptions and I/O after Chapter 8
Chapter 16 Simple Input and Output
Liang,Introduction to Java Programming,revised by Dai-kaiyu
1
Objectives








To use the String class to process fixed strings (§7.2).
To use the Character class to process a single character (§7.3).
To use the StringBuffer class to process flexible strings (§7.4).
To use the StringTokenizer class to extract tokens from a string
(§7.5).
To know the differences among the String, StringBuffer, and
StringTokenizer classes (§7.2-7.5).
To use the JDK 1.5 Scanner class for console input and scan
tokens using words as delimiters (§7.6).
To input primitive values and strings from the keyboard using the
Scanner class (§7.7).
To learn how to pass strings to the main method from the
command line (§7.8).
Liang,Introduction to Java Programming,revised by Dai-kaiyu
2
Introduction
String and character processing
Class java.lang.String
Class java.lang.StringBuffer
Class java.lang.Character
Class java.util.StringTokenizer
Liang,Introduction to Java Programming,revised by Dai-kaiyu
3
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu
4
The String Class
 Constructing a String:
String message = "Welcome to Java“;
String message = new String("Welcome to Java“);
String s = new String();
 Obtaining String length and Retrieving Individual Characters in a
string String
 String Concatenation (concat)
 Substrings (substring(index), substring(start, end))
 Comparisons (equals, compareTo)
 String Conversions
 Finding a Character or a Substring in a String
 Conversions between Strings and Arrays
 Converting Characters and Numeric Values to Strings
Liang,Introduction to Java Programming,revised by Dai-kaiyu
5
String
+String()
Constructs an empty string
+String(value: String)
Constructs a string with the specified string literal value
+String(value: char[])
Constructs a string with the specified character array
+charAt(index: int): char
Returns the character at the specified index from this string
+compareTo(anotherString: String): int
Compares this string with another string
+compareToIgnoreCase(anotherString: String): int
Compares this string with another string ignoring case
+concat(anotherString: String): String
Concat this string with another string
+endsWith(suffix: String): boolean
Returns true if this string ends with the specified suffix
+equals(anotherString: String): boolean
Returns true if this string is equal to anther string
+equalsIgnoreCase(anotherString: String): boolean
Checks if this string equals anther string ignoring case
+getChars(int srcBegin, int srcEnd, char[] dst, int
dstBegin): void
Copies characters from this string into the destination character
array
+indexOf(ch: int): int
Returns the index of the first occurrence of ch
+indexOf(ch: int, fromIndex: int): int
Returns the index of the first occurrence of ch after fromIndex
+indexOf(str: String): int
Returns the index of the first occurrence of str
+indexOf(str: String, fromIndex: int): int
Returns the index of the first occurrence of str after fromIndex
+lastIndexOf(ch: int): int
Returns the index of the last occurrence of ch
+lastIndexOf(ch: int, fromIndex: int): int
Returns the index of the last occurrence of ch before fromIndex
+lastIndexOf(str: String): int
Returns the index of the last occurrence of str
+lastIndexOf(str: String, fromIndex: int): int
Returns the index of the last occurrence of str before fromIndex
+regionMatches(toffset: int, other: String, offset:
int, len: int): boolean
Returns true if the specified subregion of this string exactly
matches the specified subregion of the string argument
+length(): int
Returns the number of characters in this string
+replace(oldChar: char, newChar: char): String
Returns a new string with oldChar replaced by newChar
+startsWith(prefix: String): boolean
Returns true if this string starts with the specified prefix
+subString(beginIndex: int): String
Returns the substring from beginIndex
+subString(beginIndex: int, endIndex: int): String
Returns the substring from beginIndex to endIndex
+toCharArray(): char[]
Returns a char array consisting characters from this string
+toLowerCase(): String
Returns a new string with all characters converted to lowercase
+toString(): String
Returns a new string with itself
+toUpperCase(): String
Returns a new string with all characters converted to uppercase
+trim(): String
Returns a string with blank characters trimmed on both sides
+copyValueOf(data: char[]): String
Returns a new string consisting of the char array data
+valueOf(c: char): String
Returns a string consisting of the character c
+valueOf(data: char[]): String
Same as copyValueOf(data: char[]): String
+valueOf(d: double): String
Returns a string representing the double value
+valueOf(f: float): String
Returns a string representing the float value
+valueOf(i: int): String
Returns a string representing the int value
+valueOf(l: long): String
Returns a string representing the long value
Liang,Introduction to Java Programming,revised by Dai-kaiyu
6
Constructing Strings
String newString = new String(stringLiteral);
String message = new String("Welcome to Java");
Since strings are used frequently, Java provides a
shorthand initializer for creating a string:
String message = "Welcome to Java";
Liang,Introduction to Java Programming,revised by Dai-kaiyu
7
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
// StringConstructors.java
// This program demonstrates the String class constructors.
// Java extension packages
import javax.swing.*;
public class StringConstructors {
// test String constructors
public static void main( String args[] )
{
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ',
'd', 'a', 'y' };
byte byteArray[] = { ( byte ) 'n', ( byte ) 'e',
( byte ) 'w', ( byte ) ' ', ( byte ) 'y',
( byte ) 'e', ( byte ) 'a', ( byte ) 'r' };
String default constructor
instantiates empty string
Constructor copies String
Constructor copies character array
StringBuffer buffer;
String s, s1, s2, s3, s4, s5, s6, s7, output;
Constructor copies characterarray subset
s = new String( "hello" );
buffer = new StringBuffer( "Welcome to Java Programming!" );
// use String constructors
s1 = new String();
s2 = new String( s );
s3 = new String( charArray );
s4 = new String( charArray, 6, 3 );
s5 = new String( byteArray, 4, 4 );
s6 = new String( byteArray );
s7 = new String( buffer );
Constructor copies byte array
Constructor copies byte-array subset
Constructor copies StringBuffer
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
8
33
// append Strings to output
34
output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 +
35
"\ns4 = " + s4 + "\ns5 = " + s5 + "\ns6 = " + s6 +
36
"\ns7 = " + s7;
37
38
JOptionPane.showMessageDialog( null, output,
39
"Demonstrating String Class Constructors",
40
JOptionPane.INFORMATION_MESSAGE );
41
42
System.exit( 0 );
43
}
44
45 } // end class StringConstructors
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
9
Strings Are Immutable
A String object is immutable; its contents cannot be changed.
Does the following code change the contents of the string?
String s = "Java";
s = "HTML";
After executing
s
s: String
String s = "Java";
After executing
s
: String
s = "HTML";
String object for "Java"
String object for "Java"
This string object is
now unreferenced
Contents cannot be changed
Liang,Introduction to Java Programming,revised by Dai-kaiyu
s: String
String object for "HTML"
10
Trace Code
String s = "Java";
s = "HTML";
After executing s = "HTML";
After executing String s = "Java";
s
: String
s
String object for "Java"
Contents cannot be changed
: String
This string object is
now unreferenced
String object for "Java"
: String
String object for "HTML"
Liang,Introduction to Java Programming,revised by Dai-kaiyu
11
Trace Code
String s = "Java";
s = "HTML";
After executing s = "HTML";
After executing String s = "Java";
s
: String
s
String object for "Java"
Contents cannot be changed
: String
This string object is
now unreferenced
String object for "Java"
: String
String object for "HTML"
Liang,Introduction to Java Programming,revised by Dai-kaiyu
12
Canonical Strings
Since strings are immutable, to improve efficiency and
save memory, the JVM stores two String objects in the
same object if they were created with the same string
literal using the shorthand initializer. Such a string is
referred to as a canonical string. You can also use a String
object’s intern method to return a canonical string, which
is the same string that is created using the shorthand
initializer.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
13
Examples
String s = "Welcome to Java";
String s1 = new String("Welcome to Java");
: String
Canonical string object
for "Welcome to Java"
String s2 = s1.intern();
String s3 = "Welcome to Java";
System.out.println("s1 == s is " + (s1 == s));
System.out.println("s2 == s is " + (s2 == s));
System.out.println("s == s3 is " + (s == s3));
: String
A string object for
"Welcome to Java"
display
s1 == s is false
s2 == s is true
s == s3 is true
Liang,Introduction to Java Programming,revised by Dai-kaiyu
14
Examples
String s = "Welcome to Java";
s
s2
String s1 = new String("Welcome to Java");
s3
: String
Interned string object for
"Welcome to Java"
String s2 = s1.intern();
String s3 = "Welcome to Java";
s1
System.out.println("s1 == s is " + (s1 == s));
System.out.println("s2 == s is " + (s2 == s));
System.out.println("s == s3 is " + (s == s3));
display
s1 == s is false
s2 == s is true
s == s3 is true
: String
A string object for
"Welcome to Java"
A new object is created if you use the new
operator.
If you use the string initializer, no new object
is created if the interned object is already
created.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
15
Trace Code
String s = "Welcome to Java";
s
String s1 = new String("Welcome to Java");
: String
Interned string object for
"Welcome to Java"
String s2 = s1.intern();
String s3 = "Welcome to Java";
Liang,Introduction to Java Programming,revised by Dai-kaiyu
16
Trace Code
String s = "Welcome to Java";
s
: String
Interned string object for
"Welcome to Java"
String s1 = new String("Welcome to Java");
String s2 = s1.intern();
String s3 = "Welcome to Java";
s1
: String
A string object for
"Welcome to Java"
Liang,Introduction to Java Programming,revised by Dai-kaiyu
17
Trace Code
String s = "Welcome to Java";
s
s2
: String
Interned string object for
"Welcome to Java"
String s1 = new String("Welcome to Java");
String s2 = s1.intern();
String s3 = "Welcome to Java";
s1
: String
A string object for
"Welcome to Java"
Liang,Introduction to Java Programming,revised by Dai-kaiyu
18
Trace Code
String s = "Welcome to Java";
s
s2
String s1 = new String("Welcome to Java");
s3
: String
Interned string object for
"Welcome to Java"
String s2 = s1.intern();
String s3 = "Welcome to Java";
s1
: String
A string object for
"Welcome to Java"
Liang,Introduction to Java Programming,revised by Dai-kaiyu
19
String Method intern
String comparisons
Slow operation
Method intern improves this performance
Returns reference to String
Guarantees reference has same contents as original String
To create a constant object in the memory(const pool)
with the same content with the original object. Then it is
enough to just compare their references ,not concret
content.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
20
If the String is changed?
Class String is immutable
The difference between
 String s1 = new String(“I am string”);
String s2 =new String(“I am string”);
 String s1 = “I am string”;
String s2 = “I am string”;
== ?
Equals ?
What about
String s = "Hello";
s = s + " world!";
If we always change the String, then
it will bring bigger memory, change
to StringBuffer
Liang,Introduction to Java Programming,revised by Dai-kaiyu
21
Finding String Length
Finding string length using the length()
method:
message = "Welcome";
message.length() (returns 7)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
22
Retrieving Individual Characters in a
String
Do not use message[0]
Use message.charAt(index)
Index starts from 0
StringIndexOutOfBoundsException
Indices
0
1
2
3
4
5
6
message
W
e
l
c
o
m
e
message.charAt(0)
7
8
9
t
o
message.length() is 15
Liang,Introduction to Java Programming,revised by Dai-kaiyu
10 11 12 13 14
J
a
v
a
message.charAt(14)
23
String Concatenation
String s3 = s1.concat(s2);
String s3 = s1 + s2;
s1 + s2 + s3 + s4 + s5 same as
(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);
Liang,Introduction to Java Programming,revised by Dai-kaiyu
24
Extracting Substrings
String is an immutable class; its values
cannot be changed individually.
String s1 = "Welcome to Java";
String s2 = s1.substring(0, 11) + "HTML";
Indices
0
1
2
3
4
5
6
message
W
e
l
c
o
m
e
7
8
9
t
o
10 11 12 13 14
message.substring(0, 11)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
J
a
v
a
message.substring(11)
25
String Comparisons
 equals
String s1 = new String("Welcome“);
String s2 = "welcome";
if (s1.equals(s2)){
// s1 and s2 have the same contents
}
Demo TestString.java
if (s1 == s2) {
// s1 and s2 have the same reference
}
Liang,Introduction to Java Programming,revised by Dai-kaiyu
26
String Comparisons, cont.
 compareTo(Object object)
String s1 = new String("Welcome“);
String s2 = "welcome";
if (s1.compareTo(s2) > 0) {
// s1 is greater than s2
}
else if (s1.compareTo(s2) == 0) {
// s1 and s2 have the same contents
}
else
// s1 is less thanLiang,Introduction
s2
to Java Programming,revised by Dai-kaiyu
27
String Comparisons, cont.
equalsIgnoreCase
regionMatches: compares portions of two
strings for equality
str.startsWith(prefix)
str.endsWith(suffix)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
28
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
// StringCompare.java
// This program demonstrates the methods equals,
// equalsIgnoreCase, compareTo, and regionMatches
// of the String class.
// Java extension packages
import javax.swing.JOptionPane;
public class StringCompare {
// test String class comparison methods
public static void main( String args[] )
{
String s1, s2, s3, s4, output;
Compare:
s1 = new String(“hello”);
s1 = “hello”
s1 = new String( "hello" );
s2 = new String( "good bye" );
s3 = new String( "Happy Birthday" );
s4 = new String( "happy birthday" );
output = "s1 = " + s1 + "\ns2 = " + s2 +
"\ns3 = " + s3 + "\ns4 = " + s4 + "\n\n";
Method equals tests two
objects for equality using
lexicographical comparison
// test for equality
if ( s1.equals( "hello" ) )
output += "s1 equals \"hello\"\n";
else
output += "s1 does not equal \"hello\"\n";
Equality operator (==) tests if
references refer to same
object in memory
// test for equality with ==
both
if ( s1 == "hello" )
output += "s1 equals \"hello\"\n";
else
output += "s1 does not equal \"hello\"\n";
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
29
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 two objects for
equality, but ignore case
of letters in String
// test compareTo
output +=
"\ns1.compareTo( s2 ) is " + s1.compareTo( s2 ) +
"\ns2.compareTo( s1 ) is " + s2.compareTo( s1 ) +
"\ns1.compareTo( s1 ) is " + s1.compareTo( s1 ) +
"\ns3.compareTo( s4 ) is " + s3.compareTo( s4 ) +
"\ns4.compareTo( s3 ) is " + s4.compareTo( s3 ) +
"\n\n";
// 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";
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
Method compareTo
compares String objects
Method regionMatches
compares portions of two
String objects for equality
Ignore case
30
65
JOptionPane.showMessageDialog( null, output,
66
"Demonstrating String Class Constructors",
67
JOptionPane.INFORMATION_MESSAGE );
68
69
System.exit( 0 );
70
}
71
72 } // end class StringCompare
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
31
String Conversions
The contents of a string cannot be changed once
the string is created. But you can convert a string
to a new string using the following methods:




toLowerCase
toUpperCase
trim
replace(oldChar, newChar)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
32
Finding a Character or a Substring in a
String
"Welcome to Java".indexOf('W') returns 0.
"Welcome to Java".indexOf('x') returns -1.
"Welcome to Java".indexOf('o', 5) returns 9.
"Welcome to Java".indexOf("come") returns 3.
"Welcome to Java".indexOf("Java",5) returns 11.
"Welcome to Java".indexOf("java",5) returns -1.
"Welcome to Java".lastIndexOf('a') returns 14.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
33
Conversion between String and Arrays
toCharArray()
char [] chars = “Java”.toCharArray();
getChars(int srcBegin, int srcEnd, char[] dst,
int dstBegin)
char[] dst = {‘J’, ’A’, ‘V’, ‘A’, ‘1’, ‘3’, ‘0’,
‘1’};
“CS3720”.getChars(2 , 6, dst, 4);
Dst = {‘J’,
’A’, ‘V’, ‘A’, ‘3’, ‘7’, ‘2’, ‘0’}
Liang,Introduction to Java Programming,revised by Dai-kaiyu
34
Convert Character and Numbers to
Strings
The String class provides several static valueOf
methods for converting a character, an array of
characters, and numeric values to strings. These
methods have the same name valueOf with
different argument types char, char[], double, long,
int, and float. For example, to convert a double
value to a string, use String.valueOf(5.44). The
return value is string consists of characters ‘5’, ‘.’,
‘4’, and ‘4’.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
35
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.*;
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"; // assign to an Object reference
String output;
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 );
static method valueOf of class
String returns String
representation of various types
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
36
34
JOptionPane.showMessageDialog( null, output,
35
"Demonstrating String Class valueOf Methods",
36
JOptionPane.INFORMATION_MESSAGE );
37
38
System.exit( 0 );
39
}
40
41 } // end class StringValueOf
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
37
Example 7.1
Finding Palindromes
Objective: Checking whether a string
is a palindrome: a string that reads the
same forward and backward.
CheckPalindrome
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
38
Character Class Examples
 Treat primitive variables as objects
Type wrapper classes
Boolean
Character
Double
Float
Byte
Short
Integer
Long
We examine class Character
Liang,Introduction to Java Programming,revised by Dai-kaiyu
39
Type-Wrapper Classes for Primitive Types
 Type-wrapper class
Each primitive type has one
Character, Byte, Integer, Short, Boolean, Long,
Float, Double, etc.
Enable to represent primitive as Object
Primitive data types can be processed polymorphically
Declared as final,inherited from Number(except for
Boolean, Character)
Many methods are declared static
Liang,Introduction to Java Programming,revised by Dai-kaiyu
40
The Character Class
Character
+Character(value: char)
Constructs a character object with char value
+charValue(): char
Returns the char value from this object
+compareTo(anotherCharacter: Character): int
Compares this character with another
+equals(anotherCharacter: Character): boolean
Returns true if this character equals to another
+isDigit(ch: char): boolean
Returns true if the specified character is a digit
+isLetter(ch: char): boolean
Returns true if the specified character is a letter
+isLetterOrDigit(ch: char): boolean
Returns true if the character is a letter or a digit
+isLowerCase(ch: char): boolean
Returns true if the character is a lowercase letter
+isUpperCase(ch: char): boolean
Returns true if the character is an uppercase letter
+toLowerCase(ch: char): char
Returns the lowercase of the specified character
+toUpperCase(ch: char): char
Returns the uppercase of the specified character
Liang,Introduction to Java Programming,revised by Dai-kaiyu
41
Examples
Character charObject = new Character('b');
charObject.charValue() returns ‘b’;
charObject.compareTo(new Character('a')) returns 1
charObject.compareTo(new Character('b')) returns 0
charObject.compareTo(new Character('c')) returns -1
charObject.compareTo(new Character('d') returns –2
charObject.equals(new Character('b')) returns true
charObject.equals(new Character('d')) returns false
Liang,Introduction to Java Programming,revised by Dai-kaiyu
42
Examples
Suppose c is variable of a char type
• Character.isDefined( c )
• Character.isDigit( c )
Character.isJavaIdentifierStart( c )
Character.isJavaIdentifierPart( c )
• Character.isLetter( c )
• Character.isLetterOrDigit( c )
• Character.isLowerCase( c )
• Character.isUpperCase( c )
• Character.toUpperCase( c )
• Character.toLowerCase( c )
Liang,Introduction to Java Programming,revised by Dai-kaiyu
43
Example 7.2
Counting Each Letter in a String
This example gives a program that counts the
number of occurrence of each letter in a string.
Assume the letters are not case-sensitive.
CountEachLetter
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
44
The StringBuffer Class
The StringBuffer class is an alternative to the
String class. In general, a string buffer can be used
wherever a string is used.
StringBuffer is more flexible than String. You can
add, insert, or append new contents
into a string buffer. However, the value of
a String object is fixed once the string is created.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
45
StringBuffer
+StringBuffer()
Constructs an empty string buffer with capacity 16
+StringBuffer(capacity: int)
Constructs a string buffer with the specified capacity
+StringBuffer(str: String)
Constructs a string buffer with the specified string
+append(data: char[]): StringBuffer
Appends a char array into this string buffer
+append(data: char[], offset: int, len: int): StringBuffer
Appends a subarray in data into this string buffer
+append(v: aPrimitiveType): StringBuffer
Appends a primitive type value as string to this buffer
+append(str: String): StringBuffer
Appends a string to this string buffer
+capacity(): int
Returns the capacity of this string buffer
+charAt(index: int): char
Returns the character at the specified index
+delete(startIndex: int, endIndex: int): StringBuffer
Deletes characters from startIndex to endIndex
+deleteCharAt(int index): StringBuffer
Deletes a character at the specified index
+insert(index: int, data: char[], offset: int, len: int):
StringBuffer
Inserts a subarray of the data in the array to the buffer at
the specified index
+insert(offset: int, data: char[]): StringBuffer
Inserts data to this buffer at the position offset
+insert(offset: int, b: aPrimitiveType): StringBuffer
Inserts a value converted to string into this buffer
+insert(offset: int, str: String): StringBuffer
Inserts a string into this buffer at the position offset
+length(): int
Returns the number of characters in this buffer
+replace(int startIndex, int endIndex, String str):
StringBuffer
Replaces the characters in this buffer from startIndex to
endIndex with the specified string
+reverse(): StringBuffer
Reveres the characters in the buffer
+setCharAt(index: int, ch: char): void
Sets a new character at the specified index in this buffer
+setLength(newLength: int): void
Sets a new length in this buffer
+substring(startIndex: int): String
Returns a substring starting at startIndex
Liang,Introduction to Java Programming,revised by Dai-kaiyu
+substring(startIndex: int, endIndex: int): String
Returns a substring from startIndex to endIndex
46
StringBuffer Constructors
 public StringBuffer()
No characters, initial capacity 16 characters.
 public StringBuffer(int length)
No characters, initial capacity specified by the length
argument.
 public StringBuffer(String str)
Represents the same sequence of characters
as the string argument. Initial capacity 16
plus the length of the string argument.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
47
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 {
Default constructor creates
empty StringBuffer with
capacity of 16 characters
// test StringBuffer constructors
public static void main( String args[] )
{
StringBuffer buffer1, buffer2, buffer3;
Second constructor creates empty
StringBuffer with capacity of
specified (10) characters
buffer1 = new StringBuffer();
buffer2 = new StringBuffer( 10 );
buffer3 = new StringBuffer( "hello" );
Third constructor creates
StringBuffer with
String “hello” and
capacity of 16 characters
String output =
"buffer1 = \"" + buffer1.toString() + "\"" +
"\nbuffer2 = \"" + buffer2.toString() + "\"" +
"\nbuffer3 = \"" + buffer3.toString() + "\"";
JOptionPane.showMessageDialog( null, output,
"Demonstrating StringBuffer Class Constructors",
JOptionPane.INFORMATION_MESSAGE );
Method toString returns
String representation of
StringBuffer
System.exit( 0 );
}
} // end class StringBufferConstructors
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
48
StringBuffer Methods
 Method length
Return StringBuffer length
 Method capacity
Return StringBuffer capacity(the number can further contain)
 Method setLength
Increase or decrease StringBuffer length
 Method toString
Return the number of characters actually stored in the string
buffer.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
49
StringBuffer Methods
 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
Liang,Introduction to Java Programming,revised by Dai-kaiyu
50
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
// StringBufferChars.java
// The charAt, setCharAt, getChars, and reverse methods
// of class StringBuffer.
// Java extension packages
import javax.swing.*;
public class StringBufferChars {
// test StringBuffer character methods
public static void main( String args[] )
{
StringBuffer buffer = new StringBuffer( "hello there" );
Return StringBuffer
characters at indices 0
and 4, respectively
String output = "buffer = " + buffer.toString() +
"\nCharacter at 0: " + buffer.charAt( 0 ) +
"\nCharacter at 4: " + buffer.charAt( 4 );
Return character array
from StringBuffer
char charArray[] = new char[ buffer.length() ];
buffer.getChars( 0, buffer.length(), charArray, 0 );
output += "\n\nThe characters are: ";
for ( int count = 0; count < charArray.length; ++count )
output += charArray[ count ];
Replace characters at
indices 0 and 6 with ‘H’
and ‘T,’ respectively
buffer.setCharAt( 0, 'H' );
buffer.setCharAt( 6, 'T' );
output += "\n\nbuf = " + buffer.toString();
buffer.reverse();
output += "\n\nbuf = " + buffer.toString();
Reverse characters in
StringBuffer
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
51
33
JOptionPane.showMessageDialog( null, output,
34
"Demonstrating StringBuffer Character Methods",
35
JOptionPane.INFORMATION_MESSAGE );
36
37
System.exit( 0 );
38
}
39
40 } // end class StringBufferChars
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
52
Appending New Contents
into a String Buffer
StringBuffer strBuf = new StringBuffer();
strBuf.append("Welcome");
strBuf.append(' ');
strBuf.append("to");
strBuf.append(' ');
strBuf.append("Java");
Liang,Introduction to Java Programming,revised by Dai-kaiyu
53
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
// StringBufferAppend.java
// This program demonstrates the append
// methods of the StringBuffer class.
// Java extension packages
import javax.swing.*;
public class StringBufferAppend {
// 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
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
54
27
buffer.append( s );
28
buffer.append( " " );
29
buffer.append( charArray );
30
buffer.append( " " );
31
buffer.append( charArray, 0, 3 );
32
buffer.append( " " );
33
buffer.append( b );
34
buffer.append( " " );
35
buffer.append( c );
36
buffer.append( " " );
37
buffer.append( i );
38
buffer.append( " " );
39
buffer.append( l );
40
buffer.append( " " );
41
buffer.append( f );
42
buffer.append( " " );
43
buffer.append( d );
44
45
JOptionPane.showMessageDialog( null,
46
"buffer = " + buffer.toString(),
47
"Demonstrating StringBuffer append Methods",
48
JOptionPane.INFORMATION_MESSAGE );
49
50
System.exit( 0 );
51
}
52
53 } // end StringBufferAppend
Append String “good bye”
Append “a b c d e f”
Append “a b c”
Append boolean, char, int,
long, float and double
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
55
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu
56
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.*;
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();
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
57
24
buffer.insert( 0, o );
25
buffer.insert( 0, " " );
26
buffer.insert( 0, s );
27
buffer.insert( 0, " " );
28
buffer.insert( 0, charArray );
Use method insert to insert
29
buffer.insert( 0, " " );
data types in beginning of
30
buffer.insert( 0, b );
31
buffer.insert( 0, " " );
StringBuffer
32
buffer.insert( 0, c );
33
buffer.insert( 0, " " );
34
buffer.insert( 0, i );
35
buffer.insert( 0, " " );
36
buffer.insert( 0, l );
37
buffer.insert( 0, " " );
38
buffer.insert( 0, f );
39
buffer.insert( 0, " " );
40
buffer.insert( 0, d );
Use method deleteCharAt to
41
remove character from index 10 in
42
String output =
43
"buffer after inserts:\n" + buffer.toString();
StringBuffer
44
45
buffer.deleteCharAt( 10 ); // delete 5 in 2.5
46
buffer.delete( 2, 6 );
// delete .333 in 33.333
47
Remove characters from
48
output +=
indices 2 through 5 (inclusive)
49
"\n\nbuffer after deletes:\n" + buffer.toString();
50
51
JOptionPane.showMessageDialog( null, output,
52
"Demonstrating StringBufferer Inserts and Deletes",
53
JOptionPane.INFORMATION_MESSAGE );
54
55
System.exit( 0 );
56
}
57
Liang,Introduction to Java Programming,revised
58
58 } // end class StringBufferInsert Liang,Introduction to Java by
Dai-kaiyu
Programming,revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised
Dai-kaiyu
Liang,Introduction to Java by
Programming,revised
by Dai-kaiyu
59
StringBuilder
 Newly introduced in J2SE 5.0
 Almost the same function with StringBuffer
 Do not deal with Synchronized , so has better
efficiency, compared with StringBuffer
 When frequently concatenate string,
StringBuilder and StringBuffer is more efficient
than String
Demo TestAppendStringTime.java
Liang,Introduction to Java Programming,revised by Dai-kaiyu
60
Example 7.3
Checking Palindromes Ignoring Nonalphanumeric Characters
PalindromeIgnoreNonAlphanumeric
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
61
Class StringTokenizer
Tokenizer
Partition String into individual substrings
Use delimiter
Java offers java.util.StringTokenizer
Liang,Introduction to Java Programming,revised by Dai-kaiyu
62
The StringTokenizer Class
java.util.StringTokenizer
+StringTokenizer(s: String)
Constructs a string tokenizer for the string.
+StringTokenizer(s: String, delimiters: Constructs a string tokenizer for the string
with the specified delimiters.
String)
+StringTokenizer(s: String, delimiters: Constructs a string tokenizer for the string
with the delimiters and returnDelims.
String, returnDelimiters: boolean)
Returns the number of remaining tokens.
+countTokens(): int
+hasMoreTokens(): boolean
Returns true if there are more tokens left.
+nextToken(): String
Returns the next token.
+nextToken(delimiters: String): String Returns the next token using new delimiters.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
63
Examples 1
String s = "Java is cool.";
StringTokenizer tokenizer = new StringTokenizer(s);
System.out.println("The total number of tokens is " +
tokenizer.countTokens());
while (tokenizer.hasMoreTokens())
System.out.println(tokenizer.nextToken());
The code displays
The total number of tokens is 3
Java
is
cool.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
64
Examples 2
String s = "Java is cool.";
StringTokenizer tokenizer = new StringTokenizer(s, "ac");
System.out.println("The total number of tokens is " +
tokenizer.countTokens());
while (tokenizer.hasMoreTokens())
System.out.println(tokenizer.nextToken());
The code displays
The total number of tokens is 4
J
v
is
ool.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
65
Examples 3
String s = "Java is cool.";
StringTokenizer tokenizer = new StringTokenizer(s, "ac", ture);
System.out.println("The total number of tokens is " +
tokenizer.countTokens());
Delimiters counted as
tokens
while (tokenizer.hasMoreTokens())
System.out.println(tokenizer.nextToken());
The code displays
The total number of tokens is 7
J
a
v
a
is
c
ool.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
66
No no-arg Constructor in StringTokenizer
The StringTokenizer class does not have a no-arg
constructor.
 Normally it is a good programming practice to
provide a no-arg constructor for each class.
On rare occasions, however, a no-arg constructor does
not make sense. StringTokenizer is such an example. A
StringTokenizer object must be created for a string,
which should be passed as an argument from a
constructor.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
67
JDK 1.5
Feature
The Scanner Class
The delimiters are single characters in StringTokenizer. You can
use the new JDK 1.5 java.util.Scanner class to specify a word as a
delimiter.
String s = "Welcome to Java! Java is fun! Java is cool!";
Scanner scanner = new Scanner(s);
scanner.useDelimiter("Java");
while (scanner.hasNext())
System.out.println(scanner.next());
Welcome to
!
is fun!
is cool!
Creates an instance of Scanner for the
string.
Sets “Java” as a delimiter.
hasNext() returns true if there are
still more tokens left.
The next() method returns a
token as a string.
Output
Liang,Introduction to Java Programming,revised by Dai-kaiyu
68
JDK 1.5
Feature
Scanning Primitive Type Values
If a token is a primitive data type value, you can use the methods nextByte(),
nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to
obtain it. For example, the following code adds all numbers in the string. Note that
the delimiter is space by default.
String s = "1 2 3 4";
Scanner scanner = new Scanner(s);
int sum = 0;
while (scanner.hasNext())
sum += scanner.nextInt();
System.out.println("Sum is " + sum);
scanner.next().chatAt(0) get the char
Liang,Introduction to Java Programming,revised by Dai-kaiyu
69
JDK 1.5
Feature
Console Input Using Scanner
Another important application of the Scanner class is to read input
from the console.
System.out.print("Please enter an int value: ");
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
NOTE: StringTokenizer can specify several single characters as
delimiters. Scanner can use a single character or a word as the
delimiter. So, if you need to scan a string with multiple single
characters as delimiters, use StringTokenizer. If you need to use a
word as the delimiter, use Scanner.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
70
Command-Line Parameters
In the main method, get the arguments from args[0],
args[1], ..., args[n], which corresponds to arg0, arg1, ...,
argn in the command line.
class TestMain {
public static void main(String[] args) {
...
}
}
java TestMain arg0 arg1 arg2 ... argn
Liang,Introduction to Java Programming,revised by Dai-kaiyu
71
Example 7.4
Using Command-Line Parameters
 Objective: Write a program that will perform
binary operations on integers. The program
receives three parameters: an operator and two
integers.
java Calculator 2 + 3
Calculator
Run
java Calculator 2 - 3
java Calculator 2 / 3
java Calculator 2 “*” 3
Liang,Introduction to Java Programming,revised by Dai-kaiyu
72