Chapter 16 Slides - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

Chapter 16 Slides

Description:

The characters in a string include upper-case and lower-case letters, numerical ... public static void main (String args[]) throws IOException ... – PowerPoint PPT presentation

Number of Views:56
Avg rating:3.0/5.0
Slides: 44
Provided by: johns380
Category:

less

Transcript and Presenter's Notes

Title: Chapter 16 Slides


1
Exposure Java
Chapter 16 Slides
String Classes and Methods
PowerPoint Presentation created by Mr. John L.
M. Schram
From Materials Created by Mr. Leon Schram
2
String Definition
A string is a set of characters that behaves as
a single unit. The characters in a string
include upper-case and lower-case letters,
numerical characters and a large set of
characters for a variety of purposes like ! _at_
( ) _
3
String Literal Definition
A string literal is a set of characters
delimited with double quotations like "Seymour
Snodgrass" and "SSN 123-45-6789"
4
// Java1601.java // This program demonstrates how
to declare five String objects. // Note that all
five string objects store the same
information. public class Java1601
public static void main (String args)
String s1 "Tango"
System.out.println("s1 " s1)
String s2 s2 "Tango"
System.out.println("s2 " s2)
String s3 new String("Tango")
System.out.println("s3 " s3)
String s4 new String() s4
"Tango" System.out.println("s4 "
s4) char Dance
'T','a','n','g','o' String s5
new String(Dance)
System.out.println("s5 " s5)
System.out.println()
Java1601.java Output s1 Tango s2 Tango s3
Tango s4 Tango s5 Tango
5
Mathematical Addition
100 200 300 int x 100 x 200
6
String Concatenation
100 200 100200 String x 100 x
200
7
// Java1602.java // This program shows how to
concatenate strings using the // operator and
the ltconcatgt method. public class Java1602
public static void main (String args)
String s1 "Argentine"
String s2 "Tango" String s3
s1 " " s2 System.out.println(
"s3 " s3) String s4
"Argentine" s4 s4.concat("
Tango") System.out.println("s4 "
s4) System.out.println()

Java1602.java Output s3 Argentine Tango s4
Argentine Tango
8
String method concat
s1 s2.concat("hiss") concat concatenates the
method argument to the object string. If s2
"boo" then s1 will become "boohiss"
9
// Java1603.java // This program demonstrates the
use of the ltlengthgt method. public class
Java1603 public static void main
(String args) String
s1 "Argentine" String s2
"Tango" String s3 s1 " "
s2 System.out.println(s1 " has "
s1.length() " characters.")
System.out.println(s2 " has " s2.length() "
characters.") System.out.println(s3
" has " s3.length() " characters.")
System.out.println()
Java1603.java Output Argentine has 9
characters. Tango has 5 characters. Argentine
Tango has 15 characters.
10
// Java1604.java // This program demonstrates how
to access individual characters of // a String
object with the ltcharAtgt method. public class
Java1604 public static void main (String
args) String s1 "Madam
I'm Adam" String s2 ""
int N s1.length() - 1 for
(int K N K gt 0 K--) s2
s1.charAt(K) System.out.println(
"s1 " s1) System.out.println("s
2 " s2) System.out.println()

Java1604.java Output s1 Madam I'm Adam s2
madA m'I madaM
11
String method charAt
letter s.charAt(k) Method charAt returns the
character stored at the kth index location of the
string object s. The first character is at
index 0. If s "Aardvark" and k 4 then
letter becomes v
12
// Java1605.java // This program demonstrates how
to access specified characters of // a string
with the ltsubstring(SI,EI)gt method, where SI is
the StartIndex // and EI is one less than the
EndIndex. public class Java1605
public static void main (String args)
String s "Racecar"
int n s.length() for (int k
1 k lt n k)
System.out.println(s.substring(0,k))
System.out.println() for (int k
0 k lt n-3 k)
System.out.println(s.substring(k,k3))
System.out.println()
Java1605.java Output R Ra Rac Race Racec Raceca R
acecar Rac ace cec eca car
13
String method substring
s2 s1.substring(0,k) Method substring
returns a set of consecutive characters from
string s1, starting at index 0, and ending at
index k-1. If s1 "Aardvark" and k 4 then
s2 becomes "Aard"
14
// Java1606.java // This program shows the
ltindexOfgt method, which returns the index of the
// first occurrence of the string argument, and
the ltlastIndexOfgt method, which returns the //
index of the last occurrence of the string
argument. public class Java1606 public
static void main (String args)
String s1 "racecar" String
s2 "racecar in the carport"
String s3 "car" int index1
s1.indexOf(s3) int index2
s1.lastIndexOf(s3) int index3
s2.indexOf(s3) int index4
s2.lastIndexOf(s3) int index5
s1.indexOf("qwerty")
System.out.println("With \"" s1 "\" car
starts at " index1 " and last shows up at "
index2) System.out.println("With
\"" s2 "\" car starts at " index3 " and
last shows up at " index4)
System.out.println("With \"" s3 "\" Qwerty
shows up at " index5)
System.out.println()
Java1606.java Output With "racecar" car starts at
4 and last shows up at 4 With "racecar in the
carport" car starts at 4 and last shows up at
15 With "racecar" Qwerty shows up at -1
15
// Java1607.java // This program demonstrates the
ltreplace(Old,New)gt String // method, which
replaces all occurrences of the Old character //
with the New character. // This method creates a
new String object with the replaced characters.
public class Java1607 public static
void main (String args)
String s1 "racecar" String s2
s1.replace('r','l')
System.out.println("s1 " s1)
System.out.println("s2 " s2)
System.out.println()
Java1607.java Output s1 racecar s2 lacecal
16
String method replace
String s2 s1.replace('m','b') Method replace
returns a string such that every occurrence of
the Old character ('m') is replaced by the New
character ('b') . If s1 "madam" then s
becomes "badab
17
// Java1608.java // This program demonstrates the
String lttoUpperCasegt and // lttoLowerCasegt
methods. public class Java1608 public
static void main (String args)
String s1 "racecar"
String s2 "RaCeCaR" String s3
"RACECAR100" String s4
s1.toUpperCase() String s5
s2.toUpperCase() String s6
s3.toUpperCase()
System.out.println("s1 --gt s4 " s4)
System.out.println("s2 --gt s5 " s5)
System.out.println("s3 --gt s6 "
s6) System.out.println()
s1 s4.toLowerCase() s2
s5.toLowerCase() s3
s6.toLowerCase()
System.out.println("s4 --gt s1 " s1)
System.out.println("s5 --gt s2 " s2)
System.out.println("s6 --gt s3 "
s3) System.out.println()

Java1608.java Output s1 --gt s4 RACECAR s2 --gt
s5 RACECAR s3 --gt s6 RACECAR100 s4 --gt s1
racecar s5 --gt s2 racecar s6 --gt s3 racecar100
18
String methods toUpperCaseand toLowerCase
s1 s2.toLowerCase s3 s1.toUpperCase Method
toLowerCase returns a string with lower-case
letters. Method toUpperCase returns a string
with upper-case letters. Any characters that are
not letters will be ignored by both methods and
returned in their same relative string
position.
19
// Java1609.java // This program demonstrates the
ltvalueOfgt method of the String class, // which is
shown to convert four data types to a string.
// Note that ltvalueOfgt is a static method and
must be called using ltString.valueOfgt. public
class Java1609 public static void main
(String args) String s1
String.valueOf(1000) String s2
String.valueOf(123.321) String s3
String.valueOf(true) String s4
String.valueOf('A')
System.out.println("s1 " s1)
System.out.println("s2 " s2)
System.out.println("s3 " s3)
System.out.println("s4 " s4)
System.out.println()
Java1609.java Output s1 1000 s2 123.321 s3
true s4 A
20
String static method valueOf
String s1 String.valueOf(1000) String
s2 String.valueOf(123.321) String s3
String.valueOf(true) String s4
String.valueOf('A') Method valueOf converts the
provided parameter and returns a string. Four
overloaded valueOf methods are displayed. Note
that the valueOf method is a static method that
is called with the String class identifier.
21
Integer methods parseInt and parseDouble
int n1 Integer.parseInt(s1) double n2
Double.parseDouble(s2) Method parseInt
converts a string into an integer. Method
parseDouble converts a string into a
double. Parameters that include non-numerical
characters will compile, but will cause a
run-time error.
22
// Java1610.java // This program converts string
values to integer and double values // using the
ltparseIntgt and ltparseDoublegt methods of the
ltIntegergt // and ltDoublegt classes. public class
Java1610 public static void main (String
args) String s1
"12345" String s2 "123.321"
int n1 Integer.parseInt(s1)
double n2 Double.parseDouble(s2)
System.out.println(n1 " " n1 " "
(n1 n1)) System.out.println(n2
" " n2 " " (n2 n2))
System.out.println()
Java1610.java Output 12345 12345
24690 123.321 123.321 246.642
23
// Java1611.java // This program checks the
equality of two strings with the operator. //
The program executes as you might expect. public
class Java1611 public static void main
(String args) String s1
"Foxtrot" String s2 "Waltz"
String s3 "Foxtrot"
if (s1 s2)
System.out.println(s1 " " s2)
else System.out.println(s1
" ! " s2) if (s1 s3)
System.out.println(s1 " "
s3) else
System.out.println(s1 " ! " s3)
System.out.println()
Java1611.java Output Foxtrot ! Waltz Foxtrot
Foxtrot
24
// Java1612.java // This program checks equality
of strings, but this time a string entered at the
keyboard // is used for comparison. This program
has unexpected results. import java.io. public
class Java1612 public static void main
(String args) throws IOException
BufferedReader input new
BufferedReader(new InputStreamReader(System.in))
String s1 "Foxtrot"
String s2 "Waltz"
System.out.print("Enter a string gtgt ")
String s3 input.readLine()
if (s1 s2)
System.out.println(s1 " " s2)
else System.out.println(s1
" ! " s2) if (s1 s3)
System.out.println(s1 " "
s3) else
System.out.println(s1 " ! " s3)
System.out.println()
Java1612.java Output Enter a string gtgt
Foxtrot Foxtrot ! Waltz Foxtrot ! Foxtrot
25
// Java1613.java // This program uses the lttrimgt
method, which removes "white space" from both
ends of the // string argument. This method is
used to try and solve the problem of the previous
program. import java.io. public class
Java1613 public static void main (String
args) throws IOException
BufferedReader input new BufferedReader(new
InputStreamReader(System.in))
String s1 "Foxtrot" String s2
"Waltz" System.out.print("Enter a
string gtgt ") String s3
input.readLine() if (s1
s2) System.out.println(s1
" " s2) else
System.out.println(s1 " ! " s2)
if (s1 s3.trim())
System.out.println(s1 " " s3)
else System.out.println(s1
" ! " s3) System.out.println()

Java1613.java Output Enter a string gtgt
Foxtrot Foxtrot ! Waltz Foxtrot ! Foxtrot
26
String method trim
s1 s2.trim() String method trim returns a
string with "white space" removed from both ends
of the String object.
27
// Java1614.java // This program demonstrates the
ltequalsgt method, which is capable of // testing
equality of string objects correctly.import
java.io. public class Java1614 public
static void main (String args) throws
IOException BufferedReader
input new BufferedReader(new InputStreamReader(S
ystem.in)) String s1 "Foxtrot"
String s2 "Waltz"
System.out.print("Enter a string gtgt ")
String s3 input.readLine()
if (s1.equals(s2))
System.out.println(s1 " " s2)
else System.out.println(s1
" ! " s2) if (s1.equals(s3))
System.out.println(s1 "
" s3) else
System.out.println(s1 " ! " s3)
System.out.println()
Java1614.java Output Enter a string gtgt
Foxtrot Foxtrot ! Waltz Foxtrot Foxtrot
28
What is going on?
Figure 16.19 shows that s1 and s3 both reference
a memory location where the value "Foxtrot" is
stored, but the values of s1 and s3 are not
equal.
29
// Java1615.java // This program demonstrates the
ltcompareTogt method, which returns an integer
value. // The value is 0 when the strings are
equal, otherwise a value is returned that //
indicates the relative distance between the
strings. public class Java1615 public
static void main (String args)
String s1 "AARDVARK"
String s2 "ZEBRA" String s3
"AARDVARK" String s4 "BART"
int value1 s1.compareTo(s2)
int value2 s1.compareTo(s3)
int value3 s2.compareTo(s1)
int value4 s1.compareTo(s4)
System.out.println("value1 " value1)
System.out.println("value2 "
value2) System.out.println("value3
" value3) System.out.println("
value4 " value4)
System.out.println()
Java1615.java Output Value1 -25 Value2
0 Value3 25 Value4 -1
30
String methodsequals and compareTo
if (s1.equals(s2)) int distance
s3.compareTo(s4) Method equals returns true is
s1 s2, and false otherwise. Method compareTo
returns 0 if s3 s4, otherwise an integer is
returned based on the difference between s3 and
s4. If s3 lt s4, the returned value is negative.
31
String Objects are Immutable
A mutator is a method that mutates or alters
object values. The character contents of a
string object cannot be altered, which means that
string objects are immutable. You need to
construct a StringBuffer object if it is
necessary to change the character content after
the object is constructed.
32
// Java1616.java // This program introduces the
ltStringBuffergt class. // Three different
approaches are shown to construct a StringBuffer
object. // You cannot assign a String to a
StringBuffer object. class Java1616
public static void main (String args)
// constructs a StringBuffer object
with capacity 16 and no characters
StringBuffer s1 new StringBuffer()
// s1 "This will not compile"
System.out.println("s1 " s1)
// constructs a StringBuffer object with
capacity 50 and no characters
StringBuffer s2 new StringBuffer(50)
System.out.println("s2 " s2)
// constructs a StringBuffer object with
required capacity and stores the string argument
StringBuffer s3 new
StringBuffer("The quick brown fox jumps over the
lazy dog") System.out.println("s3
" s3) System.out.println()

Java1616.java (with comment removed)
Output Java1616.java12 incompatible
types found java.lang.String required
java.lang.StringBuffer s1 "This won't
work" 1 error
Java1616.java Output s1 s2 s3 The quick
brown fox jumps over the lazy dog
33
// Java1617.java // This program demonstrates the
ltinsertgt method, which inserts a new string at
a // specified location. // The ltinsertgt method
automatically allocates the required StringBuffer
space. public class Java1617 public
static void main (String args)
StringBuffer s1 new StringBuffer()
s1.insert(0,"The quick brown fox
jumps over the lazy dog")
System.out.println("s1 " s1)
StringBuffer s2 new StringBuffer(50)
s2.insert(0,"The quick brown fox jumps over
the lazy dog")
System.out.println("s2 " s2)
StringBuffer s3 new StringBuffer("The quick
brown fox jumps over the lazy dog")
s3.insert(4,"ever so ")
System.out.println("s3 " s3)
System.out.println()
Java1617.java Output s1 The quick brown fox
jumps over the lazy dog s2 The quick brown fox
jumps over the lazy dog s3 The ever so quick
brown fox jumps over the lazy dog
34
StringBuffer insert method
s.insert(index,newString) Method insert adds
newString to the existing StringBuffer object s,
at the index character location.
35
// Java1618.java // This program demonstrates the
ltlengthgt, ltcapacitygt and ltsetLengthgt methods. //
Length returns the size of the stored string.
Capacity returns the size of the StringBuffer, //
and setLength alters the size of the
stringBuffer. // Note how 16 extra spaces are
constructed with a string argument
construction. public class Java1618
public static void main (String args)
StringBuffer s1 new
StringBuffer() System.out.println(
"Length " s1.length())
System.out.println("Capacity "
s1.capacity()) s1.insert(0,"The
quick brown fox jumps over the lazy dog")
System.out.println("Length "
s1.length()) System.out.println(
"Capacity " s1.capacity())
System.out.println() StringBuffer
s2 new StringBuffer(50)
System.out.println("Length "
s2.length()) System.out.println(
"Capacity " s2.capacity())
s2.insert(0,"The quick brown fox jumps over the
lazy dog") System.out.println("L
ength " s2.length())
System.out.println("Capacity "
s2.capacity()) System.out.println()
StringBuffer s3 new
StringBuffer("The quick brown fox jumps over the
lazy dog") System.out.println("Leng
th " s3.length())
System.out.println("Capacity "
s3.capacity()) s3.insert(4,"ever
so ") System.out.println("Length
" s3.length())
System.out.println("Capacity "
s3.capacity()) System.out.println()
s1.setLength(1000)
System.out.println("Length "
s1.length()) System.out.println(
"Capacity " s1.capacity())
Java1618.java Output Length 0 Capacity
16 Length 43 Capacity 43 Length
0 Capacity 50 Length 43 Capacity
50 Length 43 Capacity 59 Length
51 Capacity 59 Length 1000 Capacity 1000
Try This! Display the value of s1 at the end of
the program.
36
length, capacity and setLength
int len s.length() int cap
s.capacity() s.setLength(1000) Method length
returns the size of the StringBuffer
object. Method capacity returns buffer capacity
for total characters. Method setLength sets the
size of the StringBuffer object and appends the
string with null characters.
37
// Java1619.java // This program demonstrates how
to use the ltcharAtgt method to // access
individual characters in a StringBuffer
object. public class Java1619 public
static void main (String args)
StringBuffer s1 new StringBuffer( "Madam
I'm Adam") StringBuffer s2 new
StringBuffer(100) int n
s1.length() for (int k 0 k lt
n k) s2.insert(k,
s1.charAt(n-k-1))
System.out.println("s1 " s1)
System.out.println("s2 " s2)
System.out.println()
Java1619.java Output s1 Madam I'm Adam s2
madA m'I madaM
38
// Java1620.java // This program demonstrates how
the ltsetCharAtgt method replaces // characters in
a StringBuffer object. public class Java1620
public static void main (String args)
StringBuffer s new
StringBuffer( "Aardvark")
System.out.println(s)
s.setCharAt(0,'E')
s.setCharAt(1,'e')
s.setCharAt(5,'e')
System.out.println(s)
System.out.println()
Java1620.java Output Aardvark Eerdverk
39
StringBuffer setCharAt method
s.setCharAt(5,'A') Method setCharAt replaces
the character at index 5 of the s object with
character 'A'.
40
// Java1621.java // This program demonstrates the
ltdelete(SI,EI)gt method, which deletes a
substring // from a StringBuffer object from
StartingIndex to EndIndex-1. public class
Java1621 public static void main (String
args) StringBuffer s
new StringBuffer( "The quick brown fox jumps over
the lazy dog") System.out.println(s
) s.delete(9,15)
System.out.println(s)
s.delete(3,9) System.out.println(s)
System.out.println()

Java1621.java Output The quick brown fox jumps
over the lazy dog The quick fox jumps over the
lazy dog The fox jumps over the lazy dog
41
StringBuffer delete method
s.delete(4,7) Method delete removes a
substring from s starting at index 4 and ending
at index 6. If s "Discombobulated" then after
the s.delete(4,7) call s becomes
"Discobulated".
42
// Java1622.java // This program demonstrates the
ltreplace(SI,EI,S)gt method, which replaces a
substring // from a StringBuffer object from
StartingIndex to EndIndex-1 with string
S. public class Java1622 public static
void main (String args)
StringBuffer s new StringBuffer( "The quick
brown fox jumps over the lazy dog")
System.out.println(s)
s.replace(10,15,"red")
System.out.println(s)
s.replace(4,9,"slow")
System.out.println(s)
System.out.println()
Java1620.java Output The quick brown fox jumps
over the lazy dog The quick red fox jumps over
the lazy dog The slow red fox jumps over the lazy
dog
43
StringBuffer replace method
s.replace(0,3,"lear") Method replace deletes a
substring of s from start index 0 to last index
2, and replaces this space with "lear". If s
"burning" then after replace, s "learning"
Write a Comment
User Comments (0)
About PowerShow.com