Section 7.2. String Basics


[Page 306 (continued)]

7.2. String Basics

Before we cover the new material on Strings, let's first review what we know about this topic. In Java, Strings are considered full-fledged objects. A String object is a sequence of the characters that make up the string, plus the methods used to manipulate the string. The java.lang.String class (Fig. 7.1) is a direct subclass of Object, and it contains many public methods that can be used to perform useful operations on strings (such as concatenation). We will discuss a selection of the more commonly used methods, but for a full listing and description of the String methods see

Figure 7.1. The java.lang.String class.
(This item is displayed on page 307 in the print version)


Are strings objects?


http://java.sun.com/j2se/docs/

Like other object variables, String variables serve as references to their respective objects. However, unlike other Java objects, Strings have certain characteristics in common with the primitive data types. For example, as we have already seen, Java allows for literal strings. A string literal is a sequence of zero or more characters contained in double quotes, such as "Socrates" and "" (the empty string). Java allows us to perform operations on literal strings, such as concatenation. As we have already seen, the expression "Hello" + "world" results in the string "Helloworld". Java also allows us to use string literals to initialize String variables with an assignment statement. These exceptional features greatly simplify the use of Strings in our programs. Given how much we use Strings, incorporating these features into Java seems like a good design decision.


[Page 307]

7.2.1. Constructing Strings

To create String objects, the String class provides many constructors, including the following:

public String();                    // Creates an empty string public String(String initial_value);// Copy constructor: Creates copy of a string 


When we create an object using the first constructor, as in

String name = new String(); 


Java will create a String object and make name the reference to it. Figure 7.2 shows a hypothetical representation of a String object. In addition to storing the sequence of characters that make up the string, Java also stores an integer value representing the number of characters in the string. We have chosen to represent these two elements as the private instance variables value, for the sequence of characters, and count, for the number of characters. In fact, we don't know exactly how Java stores the sequence of characters. That information is hidden. As Figure 7.2 illustrates, when we use the default constructor, the value of the String is the empty string and its count is 0.


[Page 308]

Figure 7.2. An empty string is a String object with value "" and count 0.
(This item is displayed on page 307 in the print version)


The second constructor is the copy constructor for the String class. A copy constructor is a constructor that makes a duplicate, sometimes called a clone, of an object. Many Java classes have copy constructors. Consider the following statements:

String s1 = new String("Hello"); String s2 = new String(s1); 


These two statements would result in two distinct String objects, both storing the word "Hello".

Note that in the first of the preceding statements, we used the literal string "Hello" in the constructor. When Java encounters a new literal string in a program, it constructs an object for it. For example, if your program contained the literal "Socrates", Java would create an object for it and treat the literal itself as a reference to the object (Fig. 7.3).

Figure 7.3. The literal String "Socrates".


We often use a string literal to assign a value to a String variable:

String s;       // The value of s is initially null s = "Socrates"; // s now refers to "Socrates" object 


In this case, the reference variable s is initially nullthat is, it has no referent, no object, to refer to. However, after the assignment statement, s would refer to the literal object "Socrates", which is depicted in Figure 7.3. Given these two statements, we still have only one object, the String object containing the word "Socrates". But now we have two references to it: the literal string "Socrates" and the reference variable s.

Assignment statements can also be used as initializers when declaring a String variable:

String name1 = "";          // Reference to the empty string String name2 = "Socrates";  // References to "Socrates" String name3 = "Socrates"; 


In this example, Java does not construct new String objects. Instead, as Figure 7.4 shows, it simply makes the variables name1, name2, and name3 serve as references to the same objects that are referred to by the literal strings "" and "Socrates". This is a direct consequence of Java's policy of creating only one object to serve as the referent of a literal string, no matter how many occurrences there are of that literal in the program. Thus, these declarations result in no new objects, just new references to existing objects. The justification for this policy is that it saves lots of memory in our programs. Instead of creating a String object for each occurrence of the literal "Socrates", Java creates one object and lets all occurrences of "Socrates" refer to that object.


[Page 309]

Figure 7.4. The variables name1, name2, and name3 serve as references to the literal String objects "Socrates" and "".
(This item is displayed on page 308 in the print version)


Finally, consider the following declarations, which do invoke the String constructors:

String name4 = new String();            // Creates an object String name5 = new String("Socrates"); String name6 = name4; 


In this case, as shown in Figure 7.5, Java creates two new objects and sets name4 to refer to the first and name5 to refer to the second. It gives name4 the empty string as its value, and it gives name5 "Socrates" as its value. But these two objects must be distinguished from the objects corresponding to the literals ("" and "Socrates") themselves. The declaration of name6 just creates a second reference to the object referred to by name4.

Figure 7.5. Together with the objects in Figure 7.4, there are now four different String objects with eight different references to them, including the literals "Socrates" and "".


Java Language Rule: Strings

Java Strings are full-fledged objects, but they have some properties in common with primitive types. They can have literal values and they can be used in assignment statements.


dftgdsgh

Java Language Rule: String Declaration and Instantiation

Unless a String() constructor is called explicitly, no new String object is created when declaring a String variable and assigning it an initial value.


7.2.2. Concatenating Strings

Another way to build a String object is to concatenate two other strings. Recall from Chapter 2 that there are two ways to perform string concatenation in Java: the concat() method and the concatenation operator, +.

String lastName = "Onassis"; String jackie = new String("Jacqueline " + "Kennedy " + lastName); System.out.println("Jacqueline".concat(lastName)); 



[Page 310]

The second of these statements uses the concatenation operator, +, to create the String "Jacqueline Kennedy Onassis". The third statement uses the String method, concat(), to print "JacquelineOnassis".

String concatenation


Using the + symbol as the string concatenation operator is another example of operator overloadingusing the same operator for two or more different operationswhich we encountered in Chapter 5.

Operator overloading


Java Language Rule: String Concatenation

When surrounded on either side by a String, the + symbol is used as a binary concatenation operator. It has the effect of joining two strings together to form a single string.


Note that primitive types are automatically promoted to Strings when they are mixed with concatenation operators. Thus, the statement

System.out.println("The sum of 5 and 5 = "+ (5 + 5)); 


will print the string "The sum of 5 and 5 = 10". Note that the integer addition(5 + 5)is performed first, before the integer result is converted into a String. If we had left off the parentheses around the addition operation, the second plus sign would also be interpreted as a concatenation operator. Thus,

System.out.println("The concatenation of 5 and 5 = " + 5 + 5); 


would print "The concatenation of 5 and 5 = 55".

Self-Study Exercises

Exercise 7.1

What will be printed by each of the following segments of code?

  1. String s1 = "silly"; System.out.println(s1); 

  2. String s2 = s1; System.out.println(s2); 

  3. String s3 = new String (s1 + " stuff"); System.out.println(s3); 

Exercise 7.2

Write a String declaration that satisfies each of the following descriptions:

  1. Initialize a String variable, str1, to the empty string.

  2. Instantiate a String object, str2, and initialize it to the word stop.

  3. Initialize a String variable, str, to the concatenation of str1 and str2.


[Page 311]
Exercise 7.3

Evaluate the following expressions:

int M = 5, N = 10; String s1 = "51", s2 = "75"; 


  1. M + N

  2. M + s1

  3. s1 + s2

Exercise 7.4

Draw a picture, similar to Figure 7.5, showing the objects and references created by the following declarations:

String s1, s2 = "Hello", s3 = "Hello"; String s4 = "hello"; String s5 = new String("Hello"); String s6 = s5; String s7 = s3; 


7.2.3. Indexing Strings

Programmers often need to take strings apart or put them together or rearrange them. Just think of the many word-processing tasks, such as cut and paste, that involve such operations. To help simplify such operations, it is useful to know how many characters a string contains and to number, or index, the characters that make up the string.

The number of characters in a string is called its length. The String instance method, length(), returns an integer that gives a String's length. For example, consider the following String declarations and the corresponding values of the length() method for each case:

String string1 = "";                        string1.length() ==> 0 String string2 = "Hello";                   string2.length() ==> 5 String string3 = "World";                   string3.length() ==> 5 String string4 = string2 + " " + string3;   string4.length() ==> 11 


String length


The position of any given character in a string is called its string index. All Strings in Java are zero indexedthat is, the index of the first character is zero. (Remember, zero indexing is contrasted with unit indexing, in which we start counting at 1.) For example, in "Socrates", the letter S occurs at index 0, the letter o occurs at index 1, r occurs at index 3, and so on. Thus, the String "Socrates" contains eight characters indexed from 0 to 7 (Fig. 7.6). Zero indexing is customary in programming languages. We will see other examples of this when we talk about arrays and vectors.

Figure 7.6. The string "Socrates" has eight characters, indexed from 0 to 7. This is an example of zero indexing.



[Page 312]

Java Language Rule: String Indexing

Strings are indexed starting at 0. The first character in a string is at position 0.


Debugging Tip: Zero versus Unit Indexing

Syntax and semantic errors will result if you forget that strings are zero indexed. In a string of N characters, the first character occurs at index 0 and the last at index N -1. This is different from the String.length() method, which gives the number of characters in the string, counting from 1.


7.2.4. Converting Data to Strings

The String.valueOf() method is a class method used to convert a value of some primitive type into a String object. For example, the expression String.valueOf(128) converts its int argument to the String "128".

There are different versions of valueOf(), each of which has the following type of signature:

public static String valueOf(Type); 


where Type stands for any primitive data type, including boolean, char, int, double, and so on.

The valueOf() method is most useful for initializing Strings. Because valueOf() is a class method, it can be used as follows to instantiate new String objects:

String number = String.valueOf(128);  // Creates "128" String truth = String.valueOf(true);  // Creates "true" String bee = String.valueOf('B');     // Creates "B" String pi = String.valueOf(Math.PI);  // Creates "3.14159" 


We have already seen that Java automatically promotes primitive type values to String where necessary, so why do we need the valueOf() methods? For example, we can initialize a String to "3.14159" as follows:

String pi = new String(""+Math.PI); // Creates "3.14" 


In this case, because it is part of a concatenation expression, the value of Math.PI will automatically be promoted to a String value. The point of the valueOf() method is twofold. First, it may be the method that the Java compiler relies on to perform string promotions like this one. Second, using it in a programeven when it is not completely necessarymakes the promotion operation explicit rather than leaving it implicit. This helps to make the code more readable. (Also, see Exercise 7.9.)

Readability



[Page 313]
Self-Study Exercises

Exercise 7.5

Evaluate each of the following expressions:

  1. String.valueOf (45)

  2. String.valueOf (128 - 7)

  3. String.valueOf ('X')

Exercise 7.6

Write an expression to satisfy each of the following descriptions:

  1. Convert the integer value 100 to the string "100."

  2. Convert the character 'V' to the string "V."

  3. Initialize a new String object to X times Y.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net