Chapter 8

advertisement
Chapter 8
Characters and Strings
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 1
Chapter 8 Objectives
After you have read and studied this chapter, you
should be able to
Declare and manipulate data of the char data type.
Write string processing programs using String and
StringBuffer objects.
Differentiate the String and StringBuffer classes and use
the correct class in solving a given task.
Distinguish the primitive and reference data types and
show how the memory allocation between the two is
different.
Tell the difference between equality and equivalence
testings for String objects.
Show, by using the state-of-memory diagrams, how
objects are passed to methods and returned from
methods.
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 2
Characters
In Java single characters are represented using the
data type char. Character constants are written as
symbols enclosed in single quotes, for example, 'a', 'X',
and '5'.
To represent characters in computer, U. S. computer
manufacturers devised several coding schemes.
One coding scheme widely used today is ASCII
(American Standard Code for Information
Interchange).
To accommodate the character symbols of nonEnglish languages, the Unicode Consortium
established the Unicode Worldwide Character
Standard, commonly known as Unicode.
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 3
ASCII Table
9
O
70
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
For example,
character 'O' is
79 (row value
70 + col value 9
= 79).
Chapter 8 - 4
Character Processing
Declaration and
initialization
char ch1, ch2 = ‘X’;
messageBox.show("ASCII code of character X is " +
(int) 'X' );
message.show("Character with ASCII code 88 is " +
(char)88 );
This comparison returns
true because ASCII
value of 'A' is 65 while
that of 'c' is 99.
‘A’ < ‘c’
© 2000 McGraw-Hill
Type conversion
between int and char.
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 5
Let's Try
#1, page 358
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 6
Strings
A string is a sequence of characters that is treated as
a single value.
The String data type is used to represent strings in
Java.
We have been using String objects all along. For
example, to display a text with messageBox, we write
messageBox.show( “Hello, how are you?” );
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 7
String is an Object
String is a class in the java.lang package.
Because String is a class, we need to create an instance of
String in Java for string processing. Like any other objects, we
need a declaration and object creation for the instances of the
String class. For example,
String name1;
name1 = new String( “Latte” );
But we normally use a shorthand, instead, treating
String objects much like primitive data. For example,
Only works
for String
© 2000 McGraw-Hill
These two
statements
are equivalent.
String name1;
name1 = “Latte”;
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 8
Accessing Individual Elements
Individual characters in a String accessed with the
charAt method.
String name = “Sumatra”;
0
1
2
3
4
5
6
S
u
m
a
t
r
a
name
This variable refers to the
whole string.
© 2000 McGraw-Hill
name.charAt( 3 )
The method returns the
character at position # 3.
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 9
Determining the Size
We determine the number of characters in a String
with the length method.
String name = “Sumatra”,
str1 = “one”,
str2 = “”,
str3;
© 2000 McGraw-Hill
name.length( );
7
str1.length( );
3
Error because no
object is created for
str3, so it is a null.
str2.length( );
0
str3.length( );
Error!
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 10
Example: Counting Vowels
char
letter;
String
name
int
numberOfCharacters = name.length();
int
vowelCount
= inputBox.getString("What is your name?");
= 0;
Here’s the code to
count the number of
vowels in the input
string.
for (int i = 0; i < numberOfCharacters; i++) {
letter = name.charAt(i);
if (
letter == 'a' || letter == 'A' ||
letter == 'e' || letter == 'E' ||
letter == 'i' || letter == 'I' ||
letter == 'o' || letter == 'O' ||
letter == 'u' || letter == 'U'
) {
vowelCount++;
}
}
messageBox.show(name + ", your name has " + vowelCount + " vowels");
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 11
Example: Counting Words
String sentence
= inputBox.getString("Enter a sentence:");
int
numberOfCharacters
= sentence.length();
int
index
= 0;
int
wordCount
= 0;
while (index < numberOfCharacters ) {
//ignore blank spaces
while (sentence.charAt(index) == ' ') {
index++;
Problem:
Inner loops could cause
index to become equal
to numberOfCharacters,
which is an error.
}
//now locate the end of the word
while (sentence.charAt(index) != ' ') {
index++;
}
wordCount++;
//another word found, so increment the counter
}
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 12
Example: Counting Words - 2
String sentence
= inputBox.getString("Enter a sentence:");
int
numberOfCharacters
= sentence.length();
int
index
= 0;
int
wordCount
= 0;
while (index < numberOfCharacters ) {
//ignore blank spaces
Problem:
wordCount will be one more
than the actual count if the
sentence ends with one or
more spaces.
while (index < numberOfCharacters && sentence.charAt(index) == ' ') {
index++;
}
//now locate the end of the word
while (index < numberOfCharacters && sentence.charAt(index) != ' ') {
index++;
}
wordCount++;
//another word found, so increment the counter
}
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 13
Example: Counting ‘Java’
int
javaCount
= 0;
boolean
repeat
= true;
String
word;
Continue reading words
and count how many times
the word Java occurs in the
input, ignoring the case.
while ( repeat ) {
word = inputBox.getString("Next word:");
if ( word.equals("STOP") )
repeat = false;
}
{
Notice how the comparison
is done. We are not using
the == operator.
else if ( word.equalsIgnoreCase("Java") ) {
javaCount++;
}
}
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 14
Other Useful String Operators
Method
Meaning
compareTo
Compares the two strings.
str1.compareTo( str2 )
substring
Extracts the a substring from a string.
str1.substring( 1, 4 )
trim
Removes the leading and trailing spaces.
str1.trim( )
valueOf
Converts a given primitive data value to a string.
String.valueOf( 123.4565 )
startsWith
Returns true if a string starts with a specified prefix string.
str1.startsWith( str2 )
endsWith
Returns true if a string ends with a specified suffix string.
str1.endsWith( str2 )
• See the String class documentation for details.
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 15
Let's Try
#1, page 369
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 16
Primitive versus Reference Types
Data Type
primitive
long
byte
int
String
short
char
reference
MessageBox Applet
double
InputBox
HiLo
float
boolean
etc.
Data types are classified into two groups: primitive and
reference.
Nonnumerical data types char and boolean and all of the
numerical data types ae primitive.
All of the objects you have learned so far are reference data
types.
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 17
Effect of Assignment on Primitives
Code
A
B
num1 += 5;
State
of
Memory
int num1, num2;
num1 = 14;
num2 = num1;
int num1, num2;
num1 = 14;
num2 = num1;
num1 += 5;
num1
14
num1
19
num2
14
num2
14
After A is executed
© 2000 McGraw-Hill
After B is executed
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 18
Memory Allocation for Reference Data Type
Code
String str;
str = “Jakarta”;
str is a variable of type
String, a reference data
type, so the content is an
address (i.e. reference).
State
of
Memory
© 2000 McGraw-Hill
str
This value 2036 is the
address where the
string is actually
stored.
2036
2036
J
a
2040
k
a
2044
r
t
2048
a
Introduction to Object-Oriented Programming with Java--Wu
We assume four
bytes to a row, so
each row has two
characters (16 bits
per char).
Chapter 8 - 19
Effect of Assignment on References - 1
Code
A
String
word1, word2;
word1 = new String( “Java” );
word2 = word1;
Both word1 and word2
are allocated memory
(to store references),
but the objects
themselves are not yet
created, so they both
contain null.
word1
State
of
Memory
word2
After A is executed
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 20
Effect of Assignment on References - 2
Code
String
B
word1, word2;
One String object is
created and assigned
to word1, so word1
contains the address of
this object.
word1 = new String( “Java” );
word2 = word1;
word1
String
Java
State
of
Memory
word2
After B is executed
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 21
Effect of Assignment on References - 3
Code
String
word1, word2;
Content of word1,
which is an address, is
assigned to word2,
making word2 refer to
the same object.
word1 = new String( “Java” );
C
word2 = word1;
word1
String
Java
State
of
Memory
word2
After C is executed
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 22
Equality (==) vs. equals—Case 1
word1
String
Java
word2
word1 == word2
word1.equals( word2 )
© 2000 McGraw-Hill
true
word1 and word2
point to the same
object.
true
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 23
Equality (==) vs. equals—Case 2
String
Java
word1
String
word2
Java
word1 == word2
word1.equals( word2 )
© 2000 McGraw-Hill
false
true
Introduction to Object-Oriented Programming with Java--Wu
word1 and word2
point to different
objects having
the same string.
Chapter 8 - 24
Equality (==) vs. equals—Case 3
String
Java
word1
String
word2
Bali
word1 == word2
word1.equals( word2 )
© 2000 McGraw-Hill
false
false
Introduction to Object-Oriented Programming with Java--Wu
word1 and word2
point to different
objects with
different strings.
Chapter 8 - 25
StringBuffer
A String object is immutable, which means that once a String
object is created, we cannot change it.
We can read individual characters in a string, but we cannot
add, delete, or modify characters of a String object.
Remember that the methods of the String class, such as
toUpperCase and substring, do not modify the original string;
they return a new string.
Java adopts this immutability restriction to implement an
efficient memory allocation scheme for managing String objects.
Creating a new string from the old one will work for most cases,
but sometimes manipulating the content of a string directly is
more convenient.
Manipulation here means operations such as replacing a
character, appending a string with another string, deleting a
portion of a string, and so forth.
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 26
Sample StringBuffer Processing - 1
Replace all vowels in the sentence with ‘X’.
char
letter;
String
inSentence
StringBuffer tempStringBuffer
int
= inputBox.getString("Enter a sentence:");
= new StringBuffer(inSentence);
numberOfCharacters = tempStringBuffer.length();
for (int index = 0; index < numberOfCharacters; index++) {
letter = tempStringBuffer.charAt(index);
if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' ||
letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' ||
letter == 'u' || letter == 'U'
) {
tempStringBuffer.setCharAt(index,'X');
}
}
messageBox.show( tempStringBuffer );
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 27
Sample StringBuffer Processing - 2
Creates a sentence with words having even number of letters. Stop
when the input word is STOP.
boolean
repeat = true;
String
word;
StringBuffer tempStringBuffer = new StringBuffer("");
while ( repeat ) {
word = inputBox.getString("Next word:");
if ( word.equals("STOP") ) {
}
repeat = false;
else if ( word.length() % 2 == 0 ) {
}
tempStringBuffer.append(word + " ");
Append word and a
space to
tempStringBuffer.
}
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 28
Let's Try
#1, page 384
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 29
Passing Objects to Methods - 1
Code
A
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf
{
)
strBuf.setCharAt( 0, ‘Y’ );
}
At A before myMethod
word
A. Local variables do
StringBuffer
State of
Memory
© 2000 McGraw-Hill
not exist before the
method execution
Java
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 30
Passing Objects to Methods - 2
Code
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf
)
{
B
strBuf.setCharAt( 0, ‘Y’ );
}
A are
Values
At
before
copied
myMethod
at B
word
strBuf
StringBuffer
State of
Memory
© 2000 McGraw-Hill
Java
Introduction to Object-Oriented Programming with Java--Wu
B. The value of the
argument, which is an
address, is copied to the
parameter.
Chapter 8 - 31
Passing Objects to Methods - 3
Code
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf
{
strBuf.setCharAt( 0, ‘Y’ );
)
C
}
After C
is executed
word
strBuf
StringBuffer
State of
Memory
© 2000 McGraw-Hill
C. The content of the
object referenced by
strBuf is changed.
Yava
Java
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 32
Passing Objects to Methods - 4
Code
//StringBuffer word is
//created here
tester.myMethod( word );
D
public void myMethod( StringBuffer
strBuf
{
)
strBuf.setCharAt( 0, ‘Y’ );
}
At D after myMethod
word
strBuf
StringBuffer
State of
Memory
© 2000 McGraw-Hill
Yava
Introduction to Object-Oriented Programming with Java--Wu
D. The parameter is
erased. The argument
still points to the same
(now modified) object.
Chapter 8 - 33
Returning an Object from Methods
“Passing an object as an argument to a method”
means passing the address of the object to the
method.
The previous four slides illustrate the effect of
passing an object to a method.
The same rule applies when we “return an object
from a method.” It means the address of the object is
passed back from the method.
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 34
Exercise #5
Write a loop that prints out a user's input string
in reverse. If someone enters
Hello
Your program outputs
olleH
Just use the System.out for your output. No
need to get fancy.
© 2000 McGraw-Hill
Introduction to Object-Oriented Programming with Java--Wu
Chapter 8 - 35
Download