? 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 1
Chapter 8
Characters and Strings
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 2
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 - 3
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 non-English 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 - 4
ASCII Table
For example,
character 'O' is
79 (row value
70 + col value 9
= 79).
O
9
70
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 5
Character Processing
Declaration and
initializationchar ch1,ch2 =?X?;
Type conversion
between int and char.
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 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,
String name1;
name1 =,Latte”;
These two
statements
are equivalent.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 8
Accessing Individual Elements
Individual characters in a String accessed with the
charAt method.
0 1 2 3 4 5 6
S u m a t r a
String name =,Sumatra”;
name
This variable refers to the
whole string.
name.charAt( 3 )
The method returns the
character at position # 3.
2000 McGraw-Hill 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;
Error because no
object is created for
str3,so it is a null.
name.length( );
str1.length( );
str2.length( );
str3.length( );
7
3
0
Error!
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 10
Example,Counting Vowels
char letter;
String name = inputBox.getString("What is your name?");
int numberOfCharacters = name.length();
int vowelCount = 0;
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");
Here’s the code to
count the number of
vowels in the input
string.
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++;
}
//now locate the end of the word
while (sentence.charAt(index) != ' ') {
index++;
}
wordCount++; //another word found,so increment the counter
}
Problem,
Inner loops could cause
index to become equal
to numberOfCharacters,
which is an error.
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
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
}
Problem,
wordCount will be one more
than the actual count if the
sentence ends with one or
more spaces.
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;
while ( repeat ) {
word = inputBox.getString("Next word:");
if ( word.equals("STOP") ) {
repeat = false;
}
else if ( word.equalsIgnoreCase("Java") ) {
javaCount++;
}
}
Continue reading words
and count how many times
the word Java occurs in the
input,ignoring the case.
Notice how the comparison
is done,We are not using
the == operator.
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
Primitive versus Reference Types
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.
byte short
int double
long
float boolean
String
AppletMessageBox
HiLo InputBox
etc.
char
primitive reference
Data Type
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 16
Effect of Assignment on Primitives
Code
State
of
Memory
int num1,num2;
num1 = 14;
num2 = num1;
num1 += 5;
int num1,num2;
num1 = 14;
num2 = num1;
num1 += 5;
After is executedA
num1
num2
14
14
A
B
After is executedB
num1
num2
19
14
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 17
str
Memory Allocation for Reference Data Type
Code
State
of
Memory
String str;
str =,Jakarta”;
2036 J
2040
2044
2048
a
k a
r t
a
We assume four
bytes to a row,so
each row has two
characters (16 bits
per char).
2036
This value 2036 is the
address where the
string is actually
stored.
str is a variable of type
String,a reference data
type,so the content is an
address (i.e,reference).
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 18
Effect of Assignment on References - 1
Code
State
of
Memory
String word1,word2;
word1 = new String(,Java” );
word2 = word1;
A Both word1 and word2
are allocated memory
(to store references),
but the objects
themselves are not yet
created,so they both
contain null.
word1
word2
After is executedA
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 19
word1
word2
Effect of Assignment on References - 2
Code
State
of
Memory
String word1,word2;
word1 = new String(,Java” );
word2 = word1;
B One String object is created and assigned
to word1,so word1
contains the address of
this object.
After is executedB
String
Java
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 20
word1
word2
String
Java
Effect of Assignment on References - 3
Code
State
of
Memory
String word1,word2;
word1 = new String(,Java” );
word2 = word1;C
Content of word1,
which is an address,is
assigned to word2,
making word2 refer to
the same object.
After is executedC
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 21
Equality (==) vs,equals—Case 1
word1
word2
String
Java
word1 == word2
word1.equals( word2 ) true
true word1 and word2point to the same
object.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 22
Equality (==) vs,equals—Case 2
word1
word2
String
Java
word1 == word2
word1.equals( word2 ) true
false
String
Java
word1 and word2
point to different
objects having
the same string.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 23
Equality (==) vs,equals—Case 3
word1
word2
String
Java
word1 == word2
word1.equals( word2 ) false
false
String
Bali
word1 and word2
point to different
objects with
different strings.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 24
StringBuffer
A String object is immutable,which means that once a Stringobject 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 - 25
Sample StringBuffer Processing - 1
Replace all vowels in the sentence with?X‘,
char letter;
String inSentence = inputBox.getString("Enter a sentence:");
StringBuffer tempStringBuffer = new StringBuffer(inSentence);
int 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 - 26
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 - 27
Passing Objects to Methods - 1
Code
State of
Memory
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf )
{
strBuf.setCharAt( 0,?Y? );
}
A
A,Local variables do
not exist before the
method execution
At before myMethodA
word
StringBuffer
Java
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 28
B,The value of the
argument,which is an
address,is copied to the
parameter.
At before myMethodA
word
StringBuffer
Java
Code
State of
Memory
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf
)
{
strBuf.setCharAt( 0,?Y? );
}
Passing Objects to Methods - 2
B
Values are copied at B
strBuf
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 29
C,The content of the
object referenced by
strBuf is changed.
StringBuffer
Java
word
strBuf
Code
State of
Memory
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf )
{
strBuf.setCharAt( 0,?Y? );
}
Passing Objects to Methods - 3
After is executedC
Y
C
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 30
StringBuffer
Yava
word
strBuf D,The parameter is erased,The argument
still points to the same
(now modified) object.
Code
State of
Memory
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf )
{
strBuf.setCharAt( 0,?Y? );
}
Passing Objects to Methods - 4
D
At after myMethodD
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 31
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 - 32
Sample Program,Eggy-Peggy
Problem Statement
Write an application that will play the Eggy-Peggy word play
with the user,The program will convert a string given by the
user to a new string by placing the word ―egg‖ in front of all
vowels in the given string.
Major Tasks
while ( the user wants to play ) {
Task 1,get a string from the user;
Task 2,generate a new eggy-peggy string;
Task 3,display the result;
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 33
Eggy-Peggy – Design
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 34
Eggy-Peggy – Object Diagram
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 35
Eggy-Peggy Game – Development Steps
1,Start with a program skeleton,Define the
EggyPeggyMain and EggyPeggy classes.
2,Add code to do the input and output routines.
3,Add code to play an Eggy-Peggy game.
4,Finalize the code by removing temporary statements and tying up loose ends.
The End
Chapter 8
Characters and Strings
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 2
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 - 3
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 non-English 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 - 4
ASCII Table
For example,
character 'O' is
79 (row value
70 + col value 9
= 79).
O
9
70
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 5
Character Processing
Declaration and
initializationchar ch1,ch2 =?X?;
Type conversion
between int and char.
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 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,
String name1;
name1 =,Latte”;
These two
statements
are equivalent.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 8
Accessing Individual Elements
Individual characters in a String accessed with the
charAt method.
0 1 2 3 4 5 6
S u m a t r a
String name =,Sumatra”;
name
This variable refers to the
whole string.
name.charAt( 3 )
The method returns the
character at position # 3.
2000 McGraw-Hill 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;
Error because no
object is created for
str3,so it is a null.
name.length( );
str1.length( );
str2.length( );
str3.length( );
7
3
0
Error!
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 10
Example,Counting Vowels
char letter;
String name = inputBox.getString("What is your name?");
int numberOfCharacters = name.length();
int vowelCount = 0;
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");
Here’s the code to
count the number of
vowels in the input
string.
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++;
}
//now locate the end of the word
while (sentence.charAt(index) != ' ') {
index++;
}
wordCount++; //another word found,so increment the counter
}
Problem,
Inner loops could cause
index to become equal
to numberOfCharacters,
which is an error.
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
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
}
Problem,
wordCount will be one more
than the actual count if the
sentence ends with one or
more spaces.
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;
while ( repeat ) {
word = inputBox.getString("Next word:");
if ( word.equals("STOP") ) {
repeat = false;
}
else if ( word.equalsIgnoreCase("Java") ) {
javaCount++;
}
}
Continue reading words
and count how many times
the word Java occurs in the
input,ignoring the case.
Notice how the comparison
is done,We are not using
the == operator.
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
Primitive versus Reference Types
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.
byte short
int double
long
float boolean
String
AppletMessageBox
HiLo InputBox
etc.
char
primitive reference
Data Type
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 16
Effect of Assignment on Primitives
Code
State
of
Memory
int num1,num2;
num1 = 14;
num2 = num1;
num1 += 5;
int num1,num2;
num1 = 14;
num2 = num1;
num1 += 5;
After is executedA
num1
num2
14
14
A
B
After is executedB
num1
num2
19
14
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 17
str
Memory Allocation for Reference Data Type
Code
State
of
Memory
String str;
str =,Jakarta”;
2036 J
2040
2044
2048
a
k a
r t
a
We assume four
bytes to a row,so
each row has two
characters (16 bits
per char).
2036
This value 2036 is the
address where the
string is actually
stored.
str is a variable of type
String,a reference data
type,so the content is an
address (i.e,reference).
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 18
Effect of Assignment on References - 1
Code
State
of
Memory
String word1,word2;
word1 = new String(,Java” );
word2 = word1;
A Both word1 and word2
are allocated memory
(to store references),
but the objects
themselves are not yet
created,so they both
contain null.
word1
word2
After is executedA
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 19
word1
word2
Effect of Assignment on References - 2
Code
State
of
Memory
String word1,word2;
word1 = new String(,Java” );
word2 = word1;
B One String object is created and assigned
to word1,so word1
contains the address of
this object.
After is executedB
String
Java
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 20
word1
word2
String
Java
Effect of Assignment on References - 3
Code
State
of
Memory
String word1,word2;
word1 = new String(,Java” );
word2 = word1;C
Content of word1,
which is an address,is
assigned to word2,
making word2 refer to
the same object.
After is executedC
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 21
Equality (==) vs,equals—Case 1
word1
word2
String
Java
word1 == word2
word1.equals( word2 ) true
true word1 and word2point to the same
object.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 22
Equality (==) vs,equals—Case 2
word1
word2
String
Java
word1 == word2
word1.equals( word2 ) true
false
String
Java
word1 and word2
point to different
objects having
the same string.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 23
Equality (==) vs,equals—Case 3
word1
word2
String
Java
word1 == word2
word1.equals( word2 ) false
false
String
Bali
word1 and word2
point to different
objects with
different strings.
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 24
StringBuffer
A String object is immutable,which means that once a Stringobject 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 - 25
Sample StringBuffer Processing - 1
Replace all vowels in the sentence with?X‘,
char letter;
String inSentence = inputBox.getString("Enter a sentence:");
StringBuffer tempStringBuffer = new StringBuffer(inSentence);
int 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 - 26
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 - 27
Passing Objects to Methods - 1
Code
State of
Memory
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf )
{
strBuf.setCharAt( 0,?Y? );
}
A
A,Local variables do
not exist before the
method execution
At before myMethodA
word
StringBuffer
Java
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 28
B,The value of the
argument,which is an
address,is copied to the
parameter.
At before myMethodA
word
StringBuffer
Java
Code
State of
Memory
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf
)
{
strBuf.setCharAt( 0,?Y? );
}
Passing Objects to Methods - 2
B
Values are copied at B
strBuf
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 29
C,The content of the
object referenced by
strBuf is changed.
StringBuffer
Java
word
strBuf
Code
State of
Memory
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf )
{
strBuf.setCharAt( 0,?Y? );
}
Passing Objects to Methods - 3
After is executedC
Y
C
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 30
StringBuffer
Yava
word
strBuf D,The parameter is erased,The argument
still points to the same
(now modified) object.
Code
State of
Memory
//StringBuffer word is
//created here
tester.myMethod( word );
public void myMethod( StringBuffer
strBuf )
{
strBuf.setCharAt( 0,?Y? );
}
Passing Objects to Methods - 4
D
At after myMethodD
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 31
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 - 32
Sample Program,Eggy-Peggy
Problem Statement
Write an application that will play the Eggy-Peggy word play
with the user,The program will convert a string given by the
user to a new string by placing the word ―egg‖ in front of all
vowels in the given string.
Major Tasks
while ( the user wants to play ) {
Task 1,get a string from the user;
Task 2,generate a new eggy-peggy string;
Task 3,display the result;
}
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 33
Eggy-Peggy – Design
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 34
Eggy-Peggy – Object Diagram
2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 35
Eggy-Peggy Game – Development Steps
1,Start with a program skeleton,Define the
EggyPeggyMain and EggyPeggy classes.
2,Add code to do the input and output routines.
3,Add code to play an Eggy-Peggy game.
4,Finalize the code by removing temporary statements and tying up loose ends.
The End