120 likes | 250 Views
Chapter 7:. Strings and Characters. Objectives. The String Class String Processing The StringBuffer Class Program Design and Development: Program Performance Measures and Object-Oriented Technology (OOT) Common Programming Errors. The String Class.
E N D
Chapter 7: Strings and Characters
Objectives • The String Class • String Processing • The StringBuffer Class • Program Design and Development: Program Performance Measures and Object-Oriented Technology (OOT) • Common Programming Errors
The String Class • A string literal is a sequence of characters enclosed in double quotation marks • A string value is created as an object of: • String • StringBuffer • The main difference between the two classes: • Strings created as String objects cannot be modified • StringBuffer objects can be modified
Creating a String • Syntax: String identifier = new String(string-value); e.g. String s1 = new String(“Yikes!”); String identifier; identifier = new String(string-value); e.g. String s1; s1 = new String(“Wassup?”); String identifier = string-value; e.g. String s1 = “I just love this Java stuff.”;
Creating a String (continued) • Storage for a string is created in memory when a string is created • Location of where the string is stored is placed in a variable • Called a reference variable
Creating a String (continued) • When a data value such as a string is created from a class: • A variable is declared • An object of the correct data type is created • The location of the object created in step 2 is stored in the reference variable declared in step 1
Constructors • Instantiating an object is the process of using the new operator to create an object • The name of the constructor method must be the same name as the class • The String class provides nine different constructors for creating String objects – two of these methods have been depricated.
String Input and Output • Output: • print() • println() • Input: • read()
Immutability • String objects of the String class are always created as immutable objects – i.e. one whose stored values cannot be altered. • This means that any characters comprising the string are specified when the string is created, and these characters cannot be changed afterwards. • OK – then what about string concatenation?
Example • // create a string and declare its value • String message = “old fart”; • // oops! • String message = message + “hing”; • The concatenation operator actually creates a new string and changes the location info stored in the reference variable to access the string.
Task • Pages 350 • # 1 & 2