STUDENT OUTLINE

Lesson 11 - String Class


INTRODUCTION:

Strings are needed in many large programming tasks. Much of the information which identifies a person must be stored as a string: name, address, city, social security number, etc.

A standard String class has been provided for your use. Your job in this lesson is to learn the specifications of the String class and use it to solve string-processing questions.


The key topics for this lesson are:

A. The String Class
B. String Constructors
C. String Query Methods
D. String Translate Methods
E. Comparing Strings
F. Strings and Characters


VOCABULARY:

none

 

DISCUSSION:

A. The String Class

1.Character strings in Java are not represented by a primitive types as are integers (int) or single characters (char). Strings are represented as objects of the String class. The String class is defined in java.lang.String, which is automatically imported for use in every program you write. We've used character string literals, such as "Enter a value" in earlier examples. Now we can begin to explore the String class and the capabilities that it offers.

2. A String is the only Java reference data type that has a built-in syntax for constants. These constants, referred to as string literals, consists of any sequence of characters enclosed within double quotations. For example:

"This is a string"
"Hello World!"
"\tHello World!\n"

The characters that a String object contains can include control characters. The last example contains a tab (\t) and a linefeed (\n) character, specified with escape sequences.

3. A second unique characteristic of the String type is that it supports the "+" operator to concatenate two String expressions. For example:

sentence = "I " + "want " + "to be a " + "Java programmer.";

The "+" operator can be used to combine a String expression with any other expression of primitive type. When this occurs, the primitive expression is converted to a String representation and concatenated with the string. For example, consider the following instruction sequence:

PI = 3.14159;
System.out.println("The value of PI is " + PI);

Run output:

The value of PI is 3.14159

4. String objects are immutable. This means that after construction, they cannot be altered. Once a String object has been constructed, the characters it contains will always be the same. None of its methods will change those characters, and there is no other way to change them. The characters can be used for various purposes (such as in constructing new String objects), and can be inspected. But never altered.

5. String shares some of the characteristics with the primitive types, However, String is a reference type, not a primitive type. As a result, assigning one String to another copies the reference to the same String object. Similarly, each String method returns a new String object.

6. The rest of the student outline details a partial list of the constructors, and methods, provided by the Java String class. For a detailed listing of all of the capabilities of the class, please refer to the appropriate Sun Java Documentation.


B. String Constructors

1. You create a String object by using the keyword new and the String constructor method, just as you would create an object of any other type.

Constructor Sample Syntax
String(); // emptyString is a reference to an empty string
String emptyString = new String();
String(String value);

String aGreeting;

// aGreeting is reference to a String
aGreeting = new String("Hello world");

// Shortcut for constructing String objects.
aGreeting = "Hello world";
// anotherGreeting is a copy of aGreeting
String anotherGreeting = new String(aGreeting);

 

2. Though they are not primitive types, strings are so important and frequently used that Java provides an addition syntax for declaration:

String aGreeting = "Hello world";

A String created in this short-cut way is called a String literal. Only Strings have a short-cut like this. All other objects are constructed by using the new operator

C. String Query Methods

Query Method Sample syntax
int length(); String str1 = "Hello!"
int len = str1.length(); //len == 6
char charAt(int index);

String str1 = "Hello!"
char ch = str1.charAt(0); // ch == 'H'

int indexOf(String str);

String str2 = "Hi World!"
int n = str2.indexOf("World"); // n == 3
int n = str2.indexOf("Sun"); // n == -1

int indexOf(char ch); String str2 = "Hi World!"
int n = str2.indexOf('!'); // n == 8
int n = str2.indexOf('T'); // n == -1

1. The method int length(); returns the number of characters in the String object.

2. The method charAt method is a tool for extracting a character from within a String. The charAt parameter specifies the position of the desired char (0 for the leftmost character, 1 for the second from the left, etc.). For example, executing the following two instructions, prints the char value 'X'.

String stringVar = "VWXYZ"
System.out.println(stringVar.charAt(2);

3. The method int indexOf(String str); will find the first occurrence of str within this String and return the index of the first character. If str does not occur in this String, the method returns -1.

4. The method int indexOf(int ch); is identical in function and output to the other indexOf function except it is looking for a single character.

D. String Translate Methods

Translate Method Sample syntax
String toLowerCase(); String greeting = "Hi World!";
greeting.toLowerCase();
// returns "hi world!"
String toUpperCase(); String greeting = "Hi World!";
greeting.toUpperCase();
// returns "HI WORLD!"
String trim(); String needsTrim = " trim me! ";
needsTrim.trim();
// returns "trim me!"
String substring(int beginIndex) String sample = "hamburger";
sample.substring(3);
// returns "burger"
String substring(int beginIndex, int endIndex) String sample = "hamburger";
sample.substring(4, 8);
// returns "urge"

1. toLowerCase() returns a String with the same characters as the string object, but with all characters converted to lowercase.

2. toUpperCase() returns a String with the same characters as the string object, but with all characters converted to uppercase.

3. trim() returns a String with the same characters as the string object, but with the leading and trailing whitespace removed.

4. substring(int beginIndex) returns the substring of the String object starting from beginIndex through to the end of the String object.

5. substring(int beginIndex, int endIndex) returns the substring of the String object starting from beginIndex through, but not including, position endIndex of the String object.

E. Comparing Strings

1. Because String variables hold object references, you cannot make a simple comparison to determine whether two String objects are equivalent. If you declare two Strings as

String aGreeting = "Hello";
String anotherGreeting = "Hello";

Java will evaluate a comparison such as

If (aGreeting == anotherGreeting) ...

as false. When you compare aGreeting and anotherGreeting with the == operator, you are comparing memory addresses, and not their values.

Fortunately, the String class provides you with a number of useful methods.

Comparison Method Sample syntax
boolean equals(Object anObject); String aName = "Mat";
String anotherName = "Mat";
if (aName.equals(anotherName))   System.out.println("the same");
boolean equalsIgnoreCase(String anotherString); String aName = "Mat";
if (aName.equalsIgnoreCase("MAT"))
  System.out.println("the same");
boolean compareTo(String anotherString) String aName = "Mat"
n = aName.compareTo("Rob"); // n < 0
n = aName.compareTo("Mat"); // n == 0
n = aName.compareTo("Amy"); // n > 0

2.The equals() method evaluates the contents of two String objects to determine if they are equivalent. The method returns true if the objects have identical contents. For example, the code below shows two String objects and several comparisons. Each of the comparisons evaluate to true; each comparison results in printing the line "Name's the same"

String aName = "Mat";
String anotherName = "Mat";

if (aName.equals(anotherName))
  System.out.println("Name's the same");

if (anotherName.equals(aName))
  System.out.println("Name's the same");

if (aName.equals("Mat"))
  System.out.println("Name's the same");

Each String shown above-aName and anotherName-is an object of type String, so each String has access to the equals() method. The aName object can cal equals() with aName.equals(), or the anotherName object can call equals() with anotherName.equals(). The equals() method can take either a variable String object or a literal String as its argument.

3. The equalsIgnoreCase() method is very similar to the equals() method. As its name implies, it ignores case when determining if two Strings are equivalent. This method is very useful when users type responses to prompts in your program. The equalsIgnoreCase() method allow you to test entered data without regard to capitalization.

4. The compareTo() method compares the calling string object and the string argument to see which comes first in the lexicographic ordering. Lexicographic ordering is the same as alphabetical ordering when both strings are either all uppercase or all lowercase. If the calling string is first, it returns a negative value. If the two strings are equal, it returns zero. If the arguments is first, it returns a positive number.


F. Strings and Characters.

1. It is natural to think of a char as a String of length 1. Unfortunately, in Java the char and String types are incompatible since a String is a reference type and a char is a primitive type. Some of the limitation of this incompatibility are:

a. You cannot pass a char argument to a String parameter (nor the opposite).
b. You cannot use a char constant in place of a String constant.
c. You cannot assign a char expression to a String variable (nor the opposite).

The last restriction is particularly troublesome, because there are many times in programs when char data and String data must be used cooperatively.

2.Extracting a char from within a String can be accomplished using the charAt method as previously described.

3. Conversion from char to String can be accomplished by using the "+" (concatenation) operator described previously. Concatenating any char with an empty string (String of length zero) results in a string that consists of that char. The java notation for an empty string is two consecutive double quotation marks. For example, the following expression

"" + 'X';

evaluates to a String of length 1, consisting of the letter "X"

// charVar is a variable of type char
// stringVar is a variable of type String
stringVar = "" + charVar;

The execution of this instruction assigns to stringVar a String object that consist of the single character from charVar.

 

SUMMARY/ REVIEW:

The use of pre-existing code (classes) has helped reduce the time and cost of developing new programs. In this lesson you will use the String class without knowing its inner details. This is an excellent example of data type abstraction.