Upload
noel-weaver
View
219
Download
2
Embed Size (px)
Citation preview
1
String Class
The primitive data types provide only the char for dealing with alpha-numeric data.
2
String Class
The problem arises when we are required to maintain and process data that, by its nature, exceeds a single character
3
String Class
One Way to resolve this problem is to create our own string of characters
4
String Class
While this is within our ability, maintaining such structures would be burdensome
We can quickly see that every developer would begin to write their own solutions to handle a series of related characters
5
String Class
Well, we have:
A common problem in handling an array/string of characters
A set of generic functions that will be used to manipulate these characters…
6
String Class
What can be done to provide a practical solution ?
Bundle all of these common functions that manipulate a string of related characters
Create a String class !!!
7
String Class
Java provides two classes, the String and the StringBuffer to handle a series of characters or words
8
Our Objective:
Examine Java’s String class and StringBuffer Class
We will work with Java Docs to understand the methods within each class
We will look at the actual Java code to analyze HOW the String methods are implemented
We will implement these classes in our projects
9
What is Available OnLine:
Class Lecture NotesThis Powerpoint PresentationJava’s String class codeStringExamples.javaStringConstructors.javaStringBufferConstructors.javaStringBufferCapLen.javaStringBufferInsert.java
10
The String and StringBuffer classes provide a means for maintaining alpha-numeric data such as words or other text.
11
We will examine these classes and their methods. We will also look into the code for these classes to get a better idea of how to design and develop useful classes for ourselves.
12
The String and StringBuffer Classes are defined in the following Java API:
java.lang.String
java.lang.StringBuffer
13
Strings:
The Java String is a class and as such it has constructors and methods
Actually, the String class has 9 constructor methods !!!
14
There are literal Strings like “Hello World” that Java knows how to handle and there are the + and += operators that can be used (in their overloaded state) to concatenate strings with numbers or with other strings
15
We will learn how to:
Declare and use string literals
Instantiate Strings by way of the various class constructors
Convert strings to and from numbers
16
Work with the immutable property of a String
Use Various String methods
17
Literal Strings:
These kind of string objects are
not instantiated as the Java compiler simply treats them as a reference to a String object that is stored in the runtime stack.
They are really unreferenced variables
18
Example:
// string literal using a method
int litLength = 0;
litLength = "My String Literal".length();
System.out.println("length of \"My String Literal\" is: " +
litLength); // Answer is 17
19
You can also explicitly declare an instance of the String class (an object of):
// declare string literal
String myString = "Hello World";
20
TPS
There are many ways to create an instance of a String
Write out as many different ways you can think of…
Lets look at Java Docs list of constructors…..\..\..\Desktop\JAVA DOCS.lnk
21
TPSString MyString1 = new String();
String myString2 = "Hello World";
String myString3 = new String("Hello Wabbit") ;
String myString4 = new String(myString2);
22
String’s Immutability:
We can initialize a String object / variable using a literal or by a using the return of a String method
For example, we can initialize an empty string one of 2 ways:
String myString = “ “ ; // instantiates a //string object with no value, empty string
23
String myString = new String(); // instantiates a string object with no // value, empty string
An uninitialized String:
String myString; // myString is set to null
NOTE: null and empty string are very different !!!
24
You may execute String methods on an EMPTY string but if you attempt to Execute them against a NULL String, you will get a runtime error (NULL OBJECT REFERENCE)
Another way to initialize a String:
String myString = new String(“Hello Wabbit”) ; // invokes string constructor
25
A String, once constructed, can not be modified (there are no modifier methods, sets, in the String class there are only accessor, gets, methods)
NONE of the String methods MODIFY the private attributes of the String !!!
This means that the String class is immutable
26
The only way to “change” a String is to change the REFERENCE of the string with a new series of characters
Example:
String myString3 = new String("The Jets Stink !!!");
System.out.println(myString3);
myString3 = ("The Giants Rule !!!");
System.out.println(myString3);
27
The place in memory, reference point associated with the variable, String instance/ object, has been modified to point to the new String “The Giants Rule !!!”
Java’s garbage collector ( explicitly called with System.gc(0); ) will destroy the old literal “The Jets Stink !!!”
28
You can (copy constructor) have ONE String variable (object) COPIED into another variable:
// have 1 string get a COPY of another string
// different references or memory locations
String myString4 = new String(myString3);
System.out.println(myString4);
myString4 = ("Changed MyString4");
// now strings 3 and 4 are different
System.out.println(myString4);
System.out.println(myString3);
29
These variables have two different memory locations or references
You can have TWO String variables (objects) refer to the same string object:
30
// have 2 strings REFER to the same String //object reference
// SHARED reference or memory location
String myString5 = myString4;
System.out.println(myString5);
myString5 = (“Yankees Stink");
// now strings 4 and 5 refer to different // references
System.out.println(myString5);
System.out.println(myString4);
31
String Class Methods:
Review the Java API java.lang.String to review the various constructors and methods
We will review some of the more common String methods but is up to the Student to understand and get familiar with the other methods as you are responsible for knowing about and how to use ANY published method !!!
32
TPS
Using the StringExamples.Java as a guide, create a program that uses the String class
Create String class objects using the different methods
Copy 1 String to another, print out the values
Then, look through the Java Doc and work with some of the other methods
33
String Class Methods:
We will also examine the actual Java String class code to see how some of these methods are implemented
We will look at a few of the String class constructors
Lets look at the String Class Subset (handout) and review how some of the String methods are written…
34
Common Methods:
length()
charAt()
substring()
concat()
35
Common Methods:
compareTo()
compareToIgnoreCase()
equals()
equalsIgnoreCase()
36
Common Methods:
indexOf()
lastIndexOf()
trim()
replace()
37
Common Methods:
toUpperCase()
toLowerCase()
38
length( ) returns the number of characters in the string
System.out.println("The length of myString5 is: " +
myString5.length()); // ANS 13
The string is “Yankees Stink”
39
charAt( ) Returns a character of a String
// length minus 2 gets next to last char as // "charat" starts at element ZERO and // NOT 1
char c = myString5.charAt(myString5.length() - 2);
System.out.println(" the next to last character is: " + c); //n
The last example returns ‘n’ and NOT ‘i’ because charAt(0) starts at position ZERO And NOT ONE
40
If we were to just say:
char c = myString5.charAt (myString5.length());
We would get an IndexOutOfBounds exception error (more on exception handling in a later Lecture)
41
substring( ) overloaded methods returns portions of a string (as a string)
// substring
String myString6 = myString5.substring(3);
System.out.println(myString6);
// kees Stink
42
myString6 = myString5.substring(8, 12); // [from, to) positions
// to position is EXCLUSIVE
System.out.println(myString6);
// Stin
"hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile"
Note in the second substring method, the from position is INCLUSIVE and the to position is EXCLUSIVE (as it represents the position FOLLOWING the substring)
43
TPSWork with the string methods just reviewed
Length charAt substring
Ask the user for a wordDisplay the length of the wordDisplay the middlemost character of the
wordSplit the word into 2 separate strings and
display each new string
44
Concatenation:
The concat( ) method snaps together 2 strings and works exactly the same way as the overloaded operator+ method
45
// concat
String myString7 = "Millburn ";
String myString8 = "High School";
String myString9 = myString7.concat(myString8);
System.out.println(myString9); // Millburn High School
String myString10 = myString7 + myString8;
System.out.println(myString10); //Millburn High School
46
Both produce the same results
You can also use the operator+= overloaded operator, however it is MOST inefficient
String S = “2*2”;
S += “=4”;S is now “2*2 = 4” however it is inefficient
because the RVALUE is a temp string that is used to reassign variable S’s reference point to now refer to “2*2=4”
47
You can also concatenate Strings and numbers as long as Java understands you are working with strings
String S = “Year “;
S += 2002;
Results in S being = to “Year 2002”
48
HOWEVER, if you write:
String S = “Year “;
S += ‘ ‘ + 2003;
The compiler thinks you are performing math on ‘ ‘ and 2003 and will in effect perform S += (‘ ‘ + 2003) which will find the ASCII or Unicode for a space, which is 32, and add that to 2003 giving S the value “Year 2035”
49
If you had modified the code to concatenate a space AS A STRING
S += “ “ + 2003;Then you would get the intended result as “
“ is understood as a string
IMPORTANT NOTE: String concatenation with + (operator+) actually invokes the toString( ) method for the particular class and converts any numbers to Strings
50
Finding characters and substrings:
indexOf( char c) returns the position of the first occurance of the character c in the string
Remember that indicies begin at ZERO
There are several overloaded indexOf methods
A NOT FOUND condition results in a –1
51
Examples:
int pos = myString7.indexOf('b');
// Millburn
System.out.println(pos); // 4
int pos = myString7.indexOf('x');
System.out.println(pos); // -1
You can also start searching form any point within the string
52
Example:
pos = myString8.indexOf('h', 4);
// High School
System.out.println(pos);
// 7
Here, you search for an ‘h’ but start your search after element 4
53
You can perform a search starting at the end of the string
Example:
// High School
pos = myString8.lastIndexOf('h', 8);
System.out.println(pos); // 7
pos = myString8.lastIndexOf('h', 2);
System.out.println(pos); // -1
54
Here, the second parameter is the STARTING POINT from the END of the string
There methods are also overloaded to allow a search for a specific SUBSTRING
The methods are similar except that instead of a character variable or literal you add in a string literal or a String variable
55
int pos = myString7.indexOf('bur');
// Millburn
System.out.println(pos); // 4
pos = myString8.indexOf('hoo', 4);
// High School
System.out.println(pos); // 7
String myStr = “ch”
pos = myString8.lastIndexOf(mySr, 8);
System.out.println(pos); // 6
56
TPSWork with the string methods just
reviewed concat += + indexOf
Read in a series of words from a file (4 or 5 words)
Add these words to a single stringAsk the user to search for a character and
display each position the character is found
57
Comparisons:
You CAN NOT use relational operators ( == != >= , etc) to compare Strings (unlike C++ which overloads those operators o work with strings, Java however does not allow for operators to be overloaded)
58
Comparisons:
AS previously discussed, these operators, when applied against objects, compare REFERENCES to those objects (their memory address) and NOT THEIR STATE (values of their attributes)
59
Comparisons:
Relational Operators work on primitive data types because there they compare the VALUES in these variables
60
Comparisons:
To compare the STATE of a String, use the following methods:
equals( )
equalsIgnoreCase()
compareTo()
61
Comparisons:
equals() and equalsIgnoreCase() are boolean methods and return simply TRUE or FALSE
True if the strings have the same length and characters (case matters) otherwise it returns false
62
Examples:
boolean TF = myString7.equals(myString8);
System.out.println(TF); // FALSE
TF = myString7.equals("MIllburn ");
System.out.println(TF); // FALSE
TF = mStr.equalsIgnoreCase("Millburn ");
System.out.println(TF); // TRUE
63
What will happen here:
String s;
Boolean TF = s.equals(“OK”);
64
What will happen here:
String s;
Boolean TF = s.equals(“OK”);
Answer is a runtime error as s has yet to be instantiated, so it is NULL Object Reference
65
One method for first checking to see if an object is indeed instantiated (resident in memory) you can do the following:
Boolean TF = ( s != null && s.equals(“OK”));
66
I guess I lied when I said that you can not use relational operators
You can but they only EVALUATE THE REFERENCE (memory)
Here we are first checking to see if the string object s is resident, if it is not then the first part of the if is FALSE, and because of short circuit evaluation, the second part of the if is NEVER evaluated
Cool, huh !!!
67
CompareTo() returns an integer that describes the RESULT of the comparison
S1.compareTo(s2) RETURNS:
A negative integer if s1 PRECEEDES s2
ZERO if they are equalPositive integer if s1 POSTCEDES s2
(comes later)
68
He comparison begins at the first character and proceeds LEFT to RIGHT until different characters are encountered in corresponding positions OR until one of the strings end
When a difference occurs, the method returns the difference of the Unicodes (ASCII values) of the different characters
69
The string with the “SMALLER” character , the one with he lower ASCII code , is deemed smaller
With strings of different lengths , the method returns the difference in lengths, so he shorter string is deemed SMALLER
Remember that UPPER CASE letters come BEFORE lower case letters
70
This process is called LEXICOGRAPHIC ORDERING
71
Examples:
String s = "ABC";
int result = s.compareTo("abc");
System.out.println(result);
72
Examples:
String s = "ABC";
int result = s.compareTo("abc");
System.out.println(result);
//NEGATIVE 32, ABC smaller than abc
result = s.compareTo("ABCD");
System.out.println(result);
73
Examples:
result = s.compareTo("ABCD");
System.out.println(result);
//NEGATIVE 1, ABC smaller than ABCD
result = s.compareTo("Amuh");
System.out.println(result);
74
Examples:
result = s.compareTo("Amuh");
System.out.println(result);
//NEGATIVE 43
s = "adset";
result = s.compareTo("ADSET");
System.out.println(result);
75
Examples:
s = "adset";
result = s.compareTo("ADSET");
System.out.println(result);
//POSITIVE 32, adset GT ADSET
result = s.compareTo("aDsetf");
System.out.println(result);
76
Examples:
result = s.compareTo("aDsetf");
System.out.println(result);
//NEGATIVE 32
77
There is also a compareToIgnoreCase( ) that works in the same manner except it ignores case differences
78
Remember that Strings are OBJECTS and their variable names are REFERENCES to those objects
Therefore using the == to compare Strings will merely compare their REFERENCES
79
String i = new String("21");String y = new String("21");
// compares REFERENCESif (i == y)
System.out.println("The Strings are EQUAL !!!"); else System.out.println("The Strings are NOT EQUAL !!!");
// compares STATE if (i.equals(y))
System.out.println("The Strings are EQUAL !!!"); else System.out.println("The Strings are NOT EQUAL !!!");
80
String i = new String("21");String y = new String("21");
// compares REFERENCESi = y;if (i == y)
System.out.println("The Strings are EQUAL !!!");
else System.out.println("The Strings are
NOT EQUAL !!!");
RETURNS TRUE
81
TPS
Try this out by writing code that evaluates 2 strings for equality using the = = and then usin g the String methods
See that = = compares references and the String methods compare STATE
82
Conversions:toUpperCase() returns a new string in
all UPPER CASE
toLowerCase() returns a new string in all lower case
replace(c1, c2) builds and returns a new string in which all occurances of rthe character c1 are REPLACED with c2
83
Conversions:
trim() builds and returns a new string in which all the “whitespace” characters (spaces, tabs, newline) are trimmed from the beginning and the end of the string
84
Examples:
String s1 = “ modify This onE “
String s2;
s2 = s1.trim();
s2 = s1.toUpperCase();
85
Examples:
String s1 = “ modify This onE “
String s2;
s2 = s1.trim();
// s2 = “modify This onE”
s2 = s1.toUpperCase();
// s2 = “ MODIFY THIS ONE “
86
Examples:
String s1 = “ modify This onE “
String s2;
s2 = s1.toLowerCase();
s2 = s1.replace(‘o’, ‘x’);
87
Examples:
String s1 = “ modify This onE “
String s2;
s2 = s1.toLowerCase();
// s2 = “ modify this one “
s2 = s1.replace(‘o’, ‘x’);
// s2 = “ mxdify This xnE “
88
Remember that String s1 REMAINS UNCHANGED !!!
What does this code do ?
S1.trim();
89
Remember that String s1 REMAINS UNCHANGED !!!
What does this code do ?
S1.trim();
// ANSWER is nothing as there is no placeholder, string, to accept the returned string from the trim method
See handouts 1 and 2 for Code examples using String
90
TPSWork with the string methods just
reviewed trim toUpperCase toLowerCase replace
Read in a series of words from a file (4 or 5 words)
Remove whitespaceConvert every other word to UC & LCReplace all vowels with X
91
Converting Strings to Numbers and Numbers into Strings:
There are 2 ways to convert an int into a String of digits
(including a minus sign iff)
92
1. use the static method (remember what a static method is/ means ?) toString() of the Integer class(as mentioned before, we will discuss the Integer as well as the ofther Number classes in the second semester)
int n = -123;
String s1 = Integer.toString(n);
// s1 now has the value “-123”
93
Now, notice that we did not create an instance of the Integer class !
Well, I thought that in order to work with the methods of a class you have to create an instance of that class ?
94
The answer, obviously, is that Integer’s toString() method is a STATIC method
Static methods can be executed without having an instance (object) of that class declared as there is only one version of the static method for ANY instance of the particular class
95
Remember, however, that STATIC mathods MAY NOT CALL non Static Methods as non Static methods are tied to an instance of the class (object)
96
The Integer class (called a wrapper class as it “wraps” around the int primitive data type) is part of the java.lang package that is AUTOMATICALLY imported into all programs
97
2. Use the Static method of the String class valueOf()
int n = -123;
String s2 = String.valueOf(n);
// s2 now has the value “-123”
98
Even though we said there are 2 ways, can you think of a third ?
99
Even though we said there are 2 ways, can you think of a third ?
How about using concatenation !!!
int n = -123;
String s2 = “” + n;
// s2 now has the value “-123”
100
You can perform the same type of operations on doubles (there is also a Double wrapper class)
double n = 123.5;
String s1 = Double.toString(n);
// s1 now has the value “123.5”
101
However, with doubles the resulting String value may not display cleanly, depending on the value in the double
To properly present the double in a String use a specified FORMAT
There is a class called DecimalFormat
102
Create an instance of this class that describes the desired format
Then use that format for the conversion into a string
Example:
103
import java.text.DecimalFormat;
DecimalFormat moneyFormat = new DecimalFormat("0.00");
double totalSales = 123.5;
String s1 = moneyFormat.format(totalSales);
System.out.println("total Sales Are $" + s1); // 123.50
104
Converting a String into an Integer can be accomplished by using the parseInt( ) method of the Integer class
Example:
String s2 = “-123”;
int n = Integer.parseInt(s2);
// n = -123
105
The same works for doubles
String s2 = “123.56”;
double n = Double.parseDouble(s2);
// n = 123.56
These methods throw NumberFormatExceprion error if the string is not in the proper format
106
TPSWork with the various ways to convert a
number into a string
Then try converting a string into a number
Work with ALL the different ways to accomplish this
107
Character Methods:
These methods can help to identify a specific character (in a String) is a digit, a letter or something else
The Character wrapper has several static boolean methods
They all take a char as an argument and return TRUE or FALSE
108
Example:
Char c = ‘2’;
Boolean anwr = Character.isDigit( c );
char c1 = Character.toUpperCase(‘a’);
char c2 = Character.toLowerCase(‘A’);
109
Char c = ‘2’;
Boolean anwr = Character.isDigit( c );
// TRUE
char c1 = Character.toUpperCase(‘a’); // c1 = ‘A’
char c2 = Character.toLowerCase(‘A’);
// c1 = ‘a’
110
Java API String Search:
TPS Find the method that compares PORTIONS of 2 string objects for equality
111
Java API String Search:
TPS Find the method that compares PORTIONS of 2 string objects for equality
ANS regionMatches( )
112
S3.regionMatches( 0, s4, 0 ,5);
0 is the starting index of the string s3 s4 is the comparison string 0 the starting index of the
comparison string s4 5 is the number of characters to
compare between the 2 strings Returns TRUE or FALSE
113
S3.regionMatches(true, 0, s4, 0 ,5);
Overloaded method, first argument, if true IGNORES case
114
TPS Find the method(s) that tests a string to see if it starts with or ends with a particular set of characters
115
TPS Find the method(s) that tests a string to see if it starts with or ends with a particular set of characters
ANS startsWith( ) endsWith( )
116
String s3 = “started”;
s3.startsWith(“st”);
If s3 starts with the letters “st” returns TRUE
117
s3.startsWith(“st”, 2);
If s3 starts AT INDEX 2 (3rd element) with the letters “st” returns TRUE
S3.endsWith(“ed”);
If s3 ends with the letters “ed” returns TRUE
118
StringBuffer Class:
Unlike the Sring class, the StringBuffer class in NOT immutable as there are modifier, set, methods that allow you to alter the private attributes (state) of an instance of the SringBuffer class
StringBuffer attributes’ STATE is dynamic
119
StringBuffer stores the characters of the string along with a capacity
This class has THREE constructors
B1 = new StringBuffer(); empty string with a default capacity of 16 characters
120
B1 = new StringBuffer( 10 ); empty string with an initial capacity of 10 characters
121
Example:
StringBuffer mySB = new StringBuffer(“Kerry Collins Rules”);
char c = mySB.charAt(0);
mySB = setCharAt(0, Chatacter.toLower( c ) );
mySB is now = kerry Collins
122
Unlike the String class , which would have necessitated a NEW reference, StringBuffer maintains the original reference and only 1 character is modified
More efficient to use than String class when you will be constantly modifying the state of a “string”
123
Some Methods of this class are :
length( )capacity( )setLength( )ensureCapacity( )charAt( )
124
Some Methods of this class are :
setCharAt( )getChars( )reverse( )append( )insert( )delete( )
125
StringBuffer sb = new StringBuffer(“Hello there”);
sb.charAt(4);
sb.setCharAt(6, ‘T’);
126
StringBuffer sb = new StringBuffer(“Hello there”);
sb.charAt(4);
// returns the character at the index specified ANS = ‘o’
sb.setCharAt(6, ‘T’);
// sets the char at the index sb now = “Hello There”
127
int a = 7;
sb.append(“ “);
sb.append(a);
128
int a = 7;
sb.append(“ “);
sb.append(a);
// sb now = “Hello There 7”
129
See handouts 3, 4, and 5 for Code examples using StringBuffer
Review the Java API java.lang.StringBuffer to review the various constructors and methods
130
Projects...
Backwords
Letters and Digits
Occurrences
Name Flip
Encode / Decode
Palindrome
Count Words
Dictionary
Find Names
GREP
131
...Projects:
Text Analysis
Using Classes
Add A StringBuffer vs String project to examine efficiency
NOTE: Read ALL projects, find common elements, plan, create a CLASS of common methods !!!
132
TEST IS THE DAY AFTER THE PROJECT IS
DUE !!!