chapter 7:
Post on 30-Dec-2015
25 Views
Preview:
DESCRIPTION
TRANSCRIPT
Chapter 7:
Strings and Characters
2
Objectives
• The String Class
• String Processing
• The StringBuffer Class
• Program Design and Development: Program Performance Measures and Object-Oriented Technology (OOT)
• Common Programming Errors
3
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
4
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.”;
5
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
6
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
7
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.
8
9
String Input and Output
• Output:
– print()
– println()
• Input:
– read()
10
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?
11
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.
12
Task
• Pages 350 • # 1 & 2
top related