1.35k likes | 1.56k Vues
String Class. The primitive data types provide only the char for dealing with alpha-numeric data. String Class. The problem arises when we are required to maintain and process data that, by its nature, exceeds a single character. String Class.
E N D
String Class • The primitive data types provide only the char for dealing with alpha-numeric data.
String Class • The problem arises when we are required to maintain and process data that, by its nature, exceeds a single character
String Class • One Way to resolve this problem is to create our own string of characters
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
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…
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 !!!
String Class • Java provides two classes, the String and the StringBuffer to handle a series of characters or words
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
What is Available OnLine: • Class Lecture Notes • This Powerpoint Presentation • Java’s String class code • StringExamples.java • StringConstructors.java • StringBufferConstructors.java • StringBufferCapLen.java • StringBufferInsert.java
The String and StringBuffer classes provide a means for maintaining alpha-numeric data such as words or other text.
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.
The String and StringBuffer Classes are defined in the following Java API: • java.lang.String • java.lang.StringBuffer
Strings: • The Java String is a class and as such it has constructors and methods • Actually, the String class has 9 constructor methods !!!
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
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
Work with the immutable property of a String • Use Various String methods
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
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
You can also explicitly declare an instance of the String class (an object of): // declare string literal String myString = "Hello World";
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
TPS • String MyString1 = new String(); • String myString2 = "Hello World"; • String myString3 = new String("Hello Wabbit") ; • String myString4 = new String(myString2);
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
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 !!!
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
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
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);
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 !!!”
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);
These variables have two different memory locations or references • You can have TWO String variables (objects) refer to the same string object:
// 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);
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 !!!
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
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…
Common Methods: length() charAt() substring() concat()
Common Methods: compareTo() compareToIgnoreCase() equals() equalsIgnoreCase()
Common Methods: indexOf() lastIndexOf() trim() replace()
Common Methods: toUpperCase() toLowerCase()
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”
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
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)
substring( ) overloaded methods returns portions of a string (as a string) // substring String myString6 = myString5.substring(3); System.out.println(myString6); // kees Stink
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)
TPS • Work with the string methods just reviewed • Length • charAt • substring • Ask the user for a word • Display the length of the word • Display the middlemost character of the word • Split the word into 2 separate strings and display each new string
Concatenation: • The concat( ) method snaps together 2 strings and works exactly the same way as the overloaded operator+ method
// 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
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”
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”
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”
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
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