7.2. String BasicsBefore 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. |
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. |
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));
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".
Exercise 7.1 | What will be printed by each of the following segments of code?
|
Exercise 7.2 | Write a String declaration that satisfies each of the following descriptions:
|
Exercise 7.3 | Evaluate the following expressions: int M = 5, N = 10; String s1 = "51", s2 = "75";
|
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; |
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.
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. |
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
Exercise 7.5 | Evaluate each of the following expressions:
|
Exercise 7.6 | Write an expression to satisfy each of the following descriptions:
|