Ch09 - ComSciGate

Download Report

Transcript Ch09 - ComSciGate

Java
Methods
TM
Maria Litvin
Gary Litvin
An Introduction
to Object-Oriented Programming
"Chapter 9"
Strings
Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
Objectives:

Learn about literal strings

Learn about String constructors and
commonly used methods

Understand immutability of strings

Learn to convert strings into numbers and
numbers into strings

Learn several useful methods of the
Character class
9-2
The String class

An object of the String class represents a
string of characters.

The String class belongs to the java.lang
package, which is built into Java.

Like other classes, String has constructors
and methods.

Unlike other classes, String has two
operators, + and += (used for concatenation).
9-3
Literal Strings


Literal strings are anonymous constant
objects of the String class that are defined as
text in double quotes.
The string text may include “escape”
characters, as described in Chapter 6 (p.
146); for example:
\\ stands for \
\n stands for the newline character
"Biology”, "C:\\jdk1.4\\docs”, "Hello\n"
9-4
Literal Strings (cont’d)

don’t have to be constructed: they are “just
there.”

can be assigned to String variables.

can be passed to methods and constructors
as arguments.

have methods you can call:
String fileName = "fish.dat";
button = new JButton("Next slide");
if (”Start".equals(cmd)) ...
9-5
Immutability

Once created, a string cannot be changed:
none of its methods changes the string.

Such types of objects are called immutable.

Immutable objects are convenient because
two references can point to the same object
safely.

There is no danger of changing an object
through one reference without the others
being aware of the change.
9-6
Immutability (cont’d)

Advantage: more efficient, no need to copy.
String s1 = "Sun";
String s2 = s1;
s1
String s1 = "Sun";
String s2 = new String(s1);
s1
"Sun"
s2
"Sun"
"Sun"
s2
OK
Less efficient
and wasteful
9-7
Immutability (cont’d)

Disadvantage: less efficient — you need to
create a new string and throw away the old
one for every small change.
String s = "sun";
char ch = Character.toUpper(s.charAt (0));
s = ch + s.substring (1);
s
"sun"
'S'
+ "un"
9-8
Empty Strings

An empty string has no characters; its
length is 0.
String s1 = "";
String s2 = new String();

Empty strings
Not to be confused with an uninitialized
string:
private String errorMsg;
errorMsg
is null
9-9
Constructors


String’s no-args and copy constructors are
not used much.
String s1 = new String ();
String s1 = "";
String s2 = new String (s1);
String s2 = s1;
Other constructors convert arrays into strings
(used in a lab in Chapter 10).
9-10
Methods — length, charAt
int length ();

Returns the number of
characters in the string
char charAt (k);

Returns the k-th char
Character positions in strings
are numbered starting from 0
Returns:
”Flower".length();
6
”Wind".charAt (2);
’n'
9-11
Methods — substring
String s2 = s.substring (i, k);
– returns the substring of chars in
positions from i to k-1
strawberry
i k
String s2 = s.substring (i);
– returns the substring from the i-th char to the
end
Returns:
”raw"
”strawberry".substring (2,5);
"happy"
"unhappy".substring (2);
"" (empty string)
"emptiness".substring (9);
9-12
Methods — Concatenation
String result = s1 + s2;
– concatenates s1 and s2
String result = s1.concat (s2);
– the same as s1 + s2
result += s3;
– concatenates s3 to result
result += num;
– converts num to String and concatenates
it to result
9-13
Methods — Find (indexOf)
0
8
11
15
String date ="July 5, 2012 1:28:19 PM";
date.indexOf ('J');
date.indexOf ('2');
date.indexOf ("2012");
date.indexOf ('2', 9);
Returns:
0
8
8
(starts searching
11
at position 9)
date.indexOf ("2020");
-1
date.lastIndexOf ('2');
15
(not found)
9-14
Methods — Comparisons
boolean b = s1.equals(s2);
– returns true if the string s1 is equal to s2
boolean b = s1.equalsIgnoreCase(s2);
– returns true if the string s1 matches s2, caseblind
int diff = s1.compareTo(s2);
– returns the “difference” s1 - s2
int diff = s1.compareToIgnoreCase(s2);
– returns the “difference” s1 - s2, case-blind
9-15
Methods — Replacements
String s2 = s1.trim ();
– returns a new string formed from s1 by
removing white space at both ends
String s2 = s1.replace(oldCh, newCh);
– returns a new string formed from s1 by
replacing all occurrences of oldCh with newCh
String s2 = s1.toUpperCase();
String s2 = s1.toLowerCase();
– returns a new string formed from s1 by
converting its characters to upper (lower) case
9-16
Replacements (cont’d)

Example: how to convert s1 to upper case
s1 = s1.toUpperCase();

A common bug:
s1.toUpperCase();
s1 remains
unchanged
9-17
Methods — toString

It is customary to provide a toString
method for your class.

toString converts an object into a String
(for printing it out, for debugging, etc.).
System.out.print (obj);
is the same as
System.out.print (obj.toString());
9-18
Numbers to Strings and
Strings to Numbers


Integer and Double are “wrapper” classes
from java.lang that represent numbers as
objects.
Integer and Double provide useful static
methods for conversions:
String s1 = Integer.toString (i);
String s2 = Double.toString (d);
int i;
double d;
int n = Integer.parseInt (s1);
double x = Double.parseDouble (s2);
9-19
Numbers to Strings

Three ways to convert a number into a string:
1.
String s = "" + num;
2.
String s = Integer.toString (i);
String s = Double.toString (d);
int i;
double d;
3.
String s = String.valueOf (num);
9-20
Numbers to Strings (cont’d)

The DecimalFormat class can be used
for more controlled conversions of
numbers into strings:
import java.text.DecimalFormat;
...
DecimalFormat money =
new DecimalFormat("0.00");
...
double amt = …;
...
String s = money.format (amt);
56.7899
"56.79"
9-21
Strings to Numbers
int n = Integer.parseInt(s);
double x = Double.parseDouble(s);

These methods throw a
NumberFormatException if s does not
represent a valid number.

Older versions of SDK (before 1.2) did not
have Double.parseDouble; you had to use
double x = Double.valueOf(s).doubleValue();
9-22
Character Methods

java.lang.Character is a class that
represents characters as objects.

Character has several useful static
methods that determine the type of a
character.

Character also has methods that convert
a letter to the upper or lower case.
9-23
Character Methods (cont’d)
if (Character.isDigit (ch)) ...
.isLetter...
.isLetterOrDigit...
.isUpperCase...
.isLowerCase...
.isWhitespace...
Whitespace is
space, tab,
newline, etc.
– return true if ch belongs to the
corresponding category
9-24
Character methods (cont’d)
char ch2 = Character.toUpperCase (ch1);
.toLowerCase (ch1);
– if ch1 is a letter, returns its upper (lower)
case; otherwise returns ch1
int d = Character.digit (ch, radix);
– returns the int value of the digit ch in the
given int radix
char ch = Character.forDigit (d, radix);
– returns a char that represents int d in a
given int radix
9-25
StringTokenizer

java.util.StringTokenizer is used to extract
“tokens” from a string.

Tokens are separated by delimiters (e.g.,
whitespace).

A tokenizer object is constructed with a given
string as an argument.

The second optional argument is a string that
lists all delimiters (default is whitespace).
9-26
StringTokenizer (cont’d)
import java.util.StringTokenizer;
Delimiters are
...
whitespace
String str = input.readLine();
StringTokenizer q =
new StringTokenizer (str);
All delimiters
// or:
// new StringTokenizer (str, ";+ \t, ");
int n = q.countTokens ();
while ( q.hasMoreTokens() )
{
String word = q.nextToken();
...
The number of
found tokens
9-27
EquationSolver Applet
9-28
EquationSolver (cont’d)

Uses many techniques discussed earlier:
– trim, substring, and other String methods clean the
input, surround operation signs with spaces
– StringTokenizer extracts tokens
– Character.isDigit, and other Character methods
identify tokens
– Integer.parseInt converts tokens to numbers
– String's + operator combines strings and numbers
to generate output
9-29
Review:





What makes the String class unusual?
How can you include a double quote
character into a literal string?
Is "length".length() allowed syntax? If so,
what is the returned value?
Define immutable objects.
Does immutability of Strings make Java
more efficient or less efficient?
9-30
Review (cont’d):





How do you declare an empty string?
Why are String constructors not used very
often?
If the value of String city is "Boston", what
is returned by city.charAt (2)?
By city.substring (2, 4)?
How come String doesn’t have a
setCharAt method?
Is s1 += s2 the same as s1 = s1 + s2 for
strings?
9-31
Review (cont’d):





What do the indexOf methods do? Name
a few overloaded versions.
What is more efficient for strings: == and
other relational operators or equals and
compareTo methods?
What does the trim method do?
What does s.toUpperCase() do to s?
What does the toString method return for
a String object?
9-32
Review (cont’d):




Name a simple way to convert a number
into a string.
Which class has a method for converting
a String into an int?
Name a few Character methods that help
identify the category to which a given
character belongs.
What is the StringTokenizer class used
for?
9-33