Chap 9 Notes
Chap 9 Notes
Text
Processing
and More
about Wrapper
Classes
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-2
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.
• A wrapper class is a class that is “wrapped around” a primitive
data type.
• The wrapper classes are part of java.lang so to use them,
there is no import statement required.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-3
Wrapper Classes
• Wrapper classes allow you to create objects to
represent a primitive.
• Wrapper classes are immutable, which means that
once you create an object, you cannot change the
object’s value.
• To get the value stored in an object you must call a
method.
• Wrapper classes provide static methods that are very
useful
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-4
Character Testing and Conversion With The
Character Class
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-5
The Character Class
Method Description
boolean isDigit( Returns true if the argument passed into ch is a
char ch) digit from 0 through 9. Otherwise returns false.
boolean isLetter( Returns true if the argument passed into ch is an
char ch) alphabetic letter. Otherwise returns false.
Returns true if the character passed into ch
boolean isLetterOrDigit(
char ch) contains a digit (0 through 9) or an alphabetic
letter. Otherwise returns false.
boolean isLowerCase( Returns true if the argument passed into ch is a
char ch) lowercase letter. Otherwise returns false.
boolean isUpperCase( Returns true if the argument passed into ch is an
char ch) uppercase letter. Otherwise returns false.
boolean isSpaceChar( Returns true if the argument passed into ch is a
char ch) space character. Otherwise returns false.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-6
Character Testing and Conversion
With The Character Class
• Example:
CharacterTest.java
CustomerNumber.java
• The Character class provides two methods that will
change the case of a character.
Method Description
char toLowerCase( Returns the lowercase equivalent of the
char ch) argument passed to ch.
char toUpperCase( Returns the uppercase equivalent of the
char ch) argument passed to ch.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-8
public static void main(String[] args)
{
String input; // To hold the user's input
input = JOptionPane.showInputDialog("Enter " +
"a customer number in the form LLLNNNN\n" +
"(LLL = letters and NNNN = numbers)");
if (isValid(input))
JOptionPane.showMessageDialog(null,
"That's a valid customer number.");
else
JOptionPane.showMessageDialog(null,
"That is not the proper format of a " +
"customer number.\nHere is an " +
"example: ABC1234");
System.exit(0);
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-9
private static boolean isValid(String custNumber)
{
boolean goodSoFar = true; // Flag
int i = 0; // Control variable
if (custNumber.length() != 7)
goodSoFar = false;
while (goodSoFar && i < 3)
{
if (!Character.isLetter(custNumber.charAt(i)))
goodSoFar = false;
i++;
}
while (goodSoFar && i < 7)
{
if (!Character.isDigit(custNumber.charAt(i)))
goodSoFar = false;
i++;
}
return goodSoFar;
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-10
Substrings
• The String class provides several methods that search for a
string inside of a string.
• A substring is a string that is part of another string.
• Some of the substring searching methods provided by the
String class:
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-11
Searching Strings
• The startsWith method determines whether a
string begins with a specified substring.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-12
Searching Strings
• The endsWith method determines whether a string
ends with a specified substring.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-13
Searching Strings
• The String class provides methods that will if
specified regions of two strings match.
– regionMatches(int start, String str, int start2,
int n)
• returns true if the specified regions match or false if they
don’t
• Case sensitive comparison
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-14
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-15
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);
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-16
String Methods For Getting Character Or
Substring Location
See Table 9-4
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-17
String Methods For Getting Character Or
Substring Location
See Table 9-4
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-18
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);
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-19
Extracting Substrings
Address “Smith”
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-20
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
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-21
String input; // To hold input
char[] array; // Array for input
int letters = 0, digits = 0, whitespaces = 0;
input = JOptionPane.showInputDialog("Enter a string:");
array = input.toCharArray();
for (int i = 0; i < array.length; i++)
if (Character.isLetter(array[i]))
letters++;
else if (Character.isDigit(array[i]))
digits++;
else if (Character.isWhitespace(array[i]))
whitespaces++;
JOptionPane.showMessageDialog(null,
"That string contains "
+ letters + " letters, " +
digits + " digits, and " +
whitespaces +
" whitespace characters.");
System.exit(0);
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-22
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-23
The valueOf Methods
• The String class provides several overloaded valueOf
methods.
• They return a String object representation of
– a primitive value or
– a character array.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-24
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));
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-25
The StringBuilder Class
• The StringBuilder class is similar to the String class.
• However, you may change the contents of StringBuilder
objects.
– You can change specific characters,
– insert characters,
– delete characters, and
– perform other operations.
• A StringBuilder object will grow or shrink in size, as
needed, to accommodate the changes.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-26
StringBuilder Constructors
• StringBuilder()
– This constructor gives the object enough storage space to hold 16
characters.
• 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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-27
Other StringBuilder Methods
• The String and StringBuilder also have common
methods:
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-28
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);
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-29
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);
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-30
Appending to a StringBuilder Object
• The StringBuilder class also has several overloaded
versions of a method named insert
• These methods accept two arguments:
– an int that specifies the position to begin insertion, and
– the value to be inserted.
• The value to be inserted may be
– a primitive literal or variable.
– a char array, or
– a String literal or object.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-31
Appending 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
– a String literal or object.
• Example:
Telephone.java
TelephoneTester.java
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-32
public class Telephone
{
public final static int FORMATTED_LENGTH = 13;
public final static int UNFORMATTED_LENGTH = 10;
public static boolean isFormatted(String str)
{
return str.length() == FORMATTED_LENGTH &&
str.charAt(0) == '(‘ && str.charAt(4) == ')' &&
str.charAt(8) == ‘-’ ;
}
public static String unformat(String str)
{
StringBuilder strb = new StringBuilder(str);
if (isFormatted(str))
{
strb.deleteCharAt(0);
strb.deleteCharAt(3);
strb.deleteCharAt(6);
}
return strb.toString();
}
...
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-33
public class Telephone
{
...
public static String format(String str)
{
StringBuilder strb = new StringBuilder(str);
if (str.length() == UNFORMATTED_LENGTH)
{
strb.insert(0, "(");
strb.insert(4, ")");
strb.insert(8, "-");
}
return strb.toString();
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-34
public class TelephoneTester
{
public static void main(String[] args)
{
String phoneNumber; // To hold a phone number
Scanner keyboard = new Scanner(System.in);
S.o.p("Enter an unformatted telephone number: ");
phoneNumber = keyboard.nextLine();
S.o.p ("Formatted: " + Telephone.format(phoneNumber));
S.o.println("Enter a telephone number formatted as");
System.out.print("(XXX)XXX-XXXX : ");
phoneNumber = keyboard.nextLine();
S.o.p ("Unformatted: " + Telephone.unformat(phoneNumber));
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-35
Replacing a Substring in a StringBuilder Object
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-36
Replacing a Substring in a StringBuilder Object
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-37
Other StringBuilder Methods
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-38
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);
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-40
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
©2016 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:
Wrapper Numeric Primitive
Class Type It Applies To
Byte byte
Double double
Float float
Integer int
Long long
Short short
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-43
Creating a Wrapper Object
• To create objects from these wrapper classes, you can
pass a value to the constructor:
Integer number = new Integer(7);
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-44
The Parse Methods
• Recall from Chapter 2, we converted String input (from
JOptionPane) into numbers. Any String containing a
number, such as “127.89”, can be converted to a numeric
data type.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-46
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);
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-47
The toBinaryString, toHexString, and
toOctalString Methods
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-48
MIN_VALUE and MAX_VALUE
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-49
Autoboxing and Unboxing
• You can declare a wrapper class variable and assign a value:
Integer number;
number = 7;
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-50
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!
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-51
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.)
• Solution: TestScoreReader.java, TestAverages.java
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9-52