Chapter09_Lecture4
Chapter09_Lecture4
Programming
Lecture 4
Chapter 9
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Chapter Topics
Chapter 9 discusses the following main topics:
• Introduction to Wrapper Classes
• Character Testing and Conversion with the Character Class
• More String Methods
• The StringBuilder Class
• Tokenizing Strings
• Wrapper Classes for the Numeric Data Types
• Focus on Problem Solving: The TestScoreReader Class
©20169-2
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Introduction to Wrapper Classes
• Java provides 8 primitive data types.
• They are called “primitive” because they are not created from
classes.
• Java provides wrapper classes for all of the primitive data types.
©20169-3
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Wrapper Classes
• Wrapper classes allow you to create objects to represent a
primitive.
©20169-4
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Character Testing and Conversion With
The Character Class
• The Character class allows a char data type to be
wrapped in an object.
©20169-5
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The Character Class
Method Description
©20169-6
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Character Testing and Conversion
With The Character Class
• Example:
CharacterTest.java
CustomerNumber.java
©20169-12
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Searching Strings
• The String class also provides methods that will
locate the position of a substring.
• indexOf
• returns the first location of a substring or character in the calling
String Object.
• lastIndexOf
• returns the last location of a substring or character in the calling
String Object.
©20169-13
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Searching Strings
String str = "Four score and seven years ago";
int first, last;
first = str.indexOf('r');
last = str.lastIndexOf('r');
System.out.println("The letter r first appears at "
+ "position " + first);
System.out.println("The letter r last appears at "
+ "position " + last);
position = str.indexOf("and");
while (position != -1)
{
System.out.println(position);
position = str.indexOf("and", position + 1);
}
©20169-14
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
String Methods For Getting Character Or
Substring Location
See Table 9-4
©20169-15
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
String Methods For Getting Character Or
Substring Location
See Table 9-4
©20169-16
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Extracting Substrings
• The String class provides methods to extract
substrings in a String object.
• The substring method returns a substring beginning at a
start location and an optional ending location.
String fullName = "Cynthia Susan Smith";
String lastName = fullName.substring(14);
System.out.println("The full name is "
+ fullName);
System.out.println("The last name is "
+ lastName);
©20169-17
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Extracting Substrings
Address “Smith”
©20169-18
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Extracting Characters to Arrays
• The String class provides methods to extract
substrings in a String object and store them in char
arrays.
• getChars
• Stores a substring in a char array
• toCharArray
• Returns the String object’s contents in an array of char values.
• Example: StringAnalyzer.java
©20169-19
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Returning Modified Strings
• The String class provides methods to return
modified String objects.
• concat
• Returns a String object that is the concatenation of two String
objects.
• replace
• Returns a String object with all occurrences of one character being
replaced by another character.
• trim
• Returns a String object with all leading and trailing whitespace
characters removed.
©20169-20
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The valueOf Methods
• The String class provides several overloaded valueOf
methods.
©20169-21
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The valueOf Methods
boolean b = true;
char [] letters = { 'a', 'b', 'c', 'd', 'e' };
double d = 2.4981567;
int i = 7;
System.out.println(String.valueOf(b));
System.out.println(String.valueOf(letters));
System.out.println(String.valueOf(letters, 1, 3));
System.out.println(String.valueOf(d));
System.out.println(String.valueOf(i));
©20169-22
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The StringBuilder Class
• The StringBuilder class is similar to the String class.
• StringBuilder(int length)
• This constructor gives the object enough storage space to hold length
characters.
• StringBuilder(String str)
• This constructor initializes the object with the string in str.
• The object will have at least enough storage space to hold the string in str.
©20169-25
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Other StringBuilder Methods
• The String and StringBuilder also have common
methods:
©20169-26
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Appending to a StringBuilder Object
• The StringBuilder class has several overloaded versions of a
method named append.
• They append a string representation of their argument to the calling
object’s current contents.
• The general form of the append method is:
object.append(item);
where object is an instance of the StringBuilder class and
item is:
• a primitive literal or variable.
• a char array, or
• a String literal or object.
©20169-27
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Appending to a StringBuilder Object
• After the append method is called, a string representation of
item will be appended to object’s contents.
System.out.println(str);
©20169-28
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Inserting to a StringBuilder Object
©20169-29
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Inserting to a StringBuilder Object
• The general form of a typical call to the insert method.
• object.insert(start, item);
• where object is an instance of the StringBuilder class, start
is the insertion location, and item is:
• a primitive literal or variable.
• a char array, or
• Example:
Telephone.java
TelephoneTester.java
©20169-30
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Replacing a Substring in a StringBuilder
Object
• The StringBuilder class has a replace method that
replaces a specified substring with a string.
• The general form of a call to the method:
• object.replace(start, end, str);
• start is an int that specifies the starting position of a substring in
the calling object, and
• end is an int that specifies the ending position of the substring. (The
starting position is included in the substring, but the ending position is
not.)
• The str parameter is a String object.
• After the method executes, the substring will be replaced
with str.
©20169-31
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Replacing a Substring in a StringBuilder
Object
• The replace method in this code replaces the word
“Chicago” with “New York”.
©20169-32
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Other StringBuilder Methods
• The StringBuilder class also provides methods to set and
delete characters in an object.
StringBuilder str = new StringBuilder(
"I ate 100 blueberries!");
// Display the StringBuilder object.
System.out.println(str);
// Delete the '0'.
str.deleteCharAt(8);
// Delete "blue".
str.delete(9, 13);
// Display the StringBuilder object.
System.out.println(str);
// Change the '1' to '5'
str.setCharAt(6, '5');
// Display the StringBuilder object.
System.out.println(str);
©20169-33
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Other StringBuilder Methods
• The toString method
• You can call a StringBuilder's toString method to
convert that StringBuilder object to a regular String
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Tokenizing Strings
• Use the String class’s split method
• Tokenizes a String object and returns an array of String
objects
• Each array element is one token.
// Create a String to tokenize.
String str = "one two three four";
// Get the tokens from the string.
String[] tokens = str.split(" ");
// Display each token.
for (String s : tokens)
System.out.println(s);
©20169-35
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Numeric Data Type Wrappers
• Java provides wrapper classes for all of the primitive
data types.
• The numeric primitive wrapper classes are:
©20169-36
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Creating a Wrapper Object
• To create objects from these wrapper classes, you
can pass a value to the constructor:
Integer number = new Integer(7);
number = 7;
©20169-37
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The Parse Methods
• Any String containing a number, such as “127.89”, can be
converted to a numeric data type.
©20169-38
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The Parse Methods
// Store 1 in bVar.
byte bVar = Byte.parseByte("1");
// Store 2599 in iVar.
int iVar = Integer.parseInt("2599");
// Store 10 in sVar.
short sVar = Short.parseShort("10");
// Store 15908 in lVar.
long lVar = Long.parseLong("15908");
// Store 12.3 in fVar.
float fVar = Float.parseFloat("12.3");
// Store 7945.6 in dVar.
double dVar = Double.parseDouble("7945.6");
©20169-39
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The toString Methods
• Each of the numeric wrapper classes has a static
toString method that converts a number to a string.
• The method accepts the number as its argument and
returns a string representation of that number.
int i = 12;
double d = 14.95;
String str1 = Integer.toString(i);
String str2 = Double.toString(d);
©20169-40
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
The toBinaryString, toHexString, and
toOctalString Methods
• The Integer and Long classes have three additional
methods:
• toBinaryString, toHexString, and
toOctalString
int number = 14;
System.out.println(Integer.toBinaryString(number));
System.out.println(Integer.toHexString(number));
System.out.println(Integer.toOctalString(number));
• This code will produce the following output:
1110
e
16
©20169-41
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
MIN_VALUE and MAX_VALUE
• The numeric wrapper classes each have a set of static final
variables
• MIN_VALUE and
• MAX_VALUE.
©20169-42
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Autoboxing and Unboxing
• You can declare a wrapper class variable and assign a value:
Integer number;
number = 7;
©20169-43
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Autoboxing and Unboxing
• You rarely need to declare numeric wrapper class objects, but
they can be useful when you need to work with primitives in a
context where primitives are not permitted
• Recall the ArrayList class, which works only with objects.
ArrayList<int> list =
new ArrayList<int>(); // Error!
ArrayList<Integer> list =
new ArrayList<Integer>(); // OK!
©20169-44
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Problem Solving
• Dr. Harrison keeps student scores in an Excel file.
This can be exported as a comma separated text file.
Each student’s data will be on one line. We want to
write a Java program that will find the average for each
student. (The number of students changes each year.)
©20169-45
Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.