8.4. The StringBuilder-StringBuffer Class

 
[Page 262 ( continued )]

8.2. The String Class

The java.lang.String class models a sequence of characters as a string. You have already used string literals, such as the parameter in the println(String s) method. The Java compiler converts the string literal into a string object and passes it to println .

The String class has eleven constructors and more than forty methods for examining individual characters in a sequence, comparing strings, searching substrings, obtaining substrings, and creating a copy of a string with all the characters translated to uppercase or lowercase. The most frequently used methods are listed in Figure 8.1.

Figure 8.1. The String class provides the methods for processing a string.
(This item is displayed on page 263 in the print version)

8.2.1. Constructing a String

You can create a string object from a string value or from an array of characters. To create a string from a string literal, use a syntax like this one:

 String newString =   new   String(stringLiteral); 

The argument stringLiteral is a sequence of characters enclosed inside double quotes. The following statement creates a String object message for the string literal "Welcome to Java" :

 String message =   new   String(   "Welcome to Java"   ); 

Since strings are used frequently, Java treats a string literal as a String object. So the following statement is valid:

 String message =   "Welcome to Java"   ; 

You can also create a string from an array of characters. For example, the following statements create the string "Good Day".

   char   [] charArray = {   'G'   ,   'o'   ,   'o'   ,   'd'   ,   ' '   ,   'D'   ,   'a'   ,   'y'   }; String message =   new   String(charArray); 

Note

A String variable holds a reference to a String object that stores a string value. Strictly speaking, the terms String variable , String object , and string value are different, but the distinctions between them can be ignored most of the time. For simplicity, the term string will often be used to refer to String variable, String object, and string value.



[Page 263]

8.2.2. Immutable Strings and Interned Strings

A String object is immutable ; its contents cannot be changed. Does the following code change the contents of the string?

 String s =   "Java"   ; s =   "HTML"   ; 

The answer is no. The first statement creates a String object with the content "Java" and assigns its reference to s . The second statement creates a new String object with the content "HTML" and assigns its reference to s . The first String object still exists after the assignment, but it can no longer be accessed because variable s now points to the new object, as shown in Figure 8.2.

Figure 8.2. Strings are immutable; their contents cannot be changed once created.
(This item is displayed on page 264 in the print version)

Since strings are immutable and are frequently used, the JVM improves efficiency and saves memory, by using a unique instance for string literals with the same character sequence. Such an instance is called interned . You can also use a String object's intern method to return an interned string . For example, the following statements:


[Page 264]

display

 s1 == s is false s2 == s is true s == s3 is true 

In the preceding statements, s , s2 , and s3 refer to the same interned string "Welcome to Java" , therefore s2 == s and s == s3 are true . However, s1 == s is false , because s and s1 are two different string objects even though they have the same contents.

8.2.3. String Comparisons

Often, in a program, you need to compare the contents of two strings. You might attempt to use the == operator, as follows :

   if   (string1 == string2)   System.out.println(   "string1 and string2 are the same object"   );   else   System.out.println(   "string1 and string2 are different objects"   ); 

However, the == operator only checks whether string1 and string2 refer to the same object; it does not tell you whether string1 and string2 contain the same contents. Therefore, you cannot use the == operator to find out whether two string variables have the same contents. Instead, you should use the equals method for an equality comparison of the contents of objects. The code given below, for instance, can be used to compare two strings.

   if   (string1.equals(string2))   System.out.println(   "string1 and string2 have the same contents"   );   else   System.out.println(   "string1 and string2 are not equal"   ); 


[Page 265]

Note

Strings with the same contents do not always share the same object. For example, the following two variables, s1 and s2 , are different even though their contents are identical:

 String s1 =   new   String(   "Welcome to Java"   ); String s2 =   "Welcome to Java"   ; System.out.println(   "s1 == s2 is "   + (s1 == s2)); System.out.println(   "s1.equals(s2) is "   + (s1.equals(s2))); 

In this case, s1 == s2 is false since they point to two different objects, but s1.equals(s2) is true since the objects have the same contents. For safety and clarity, you should always use the equals method to test whether two strings have the same contents, and the == operator to test whether the two strings have the same references (i.e., point to the same memory location).


Note

For two strings x and y , x.equals(y) if and only if x.intern() == y.intern() .


The compareTo method can also be used to compare two strings. For example, consider the following code:

 s1.compareTo(s2) 

The method returns the value if s1 is equal to s2 , a value less than if s1 is lexicographically less than s2 , and a value greater than if s1 is lexicographically greater than s2 .

The actual value returned from the compareTo method depends on the offset of the first two distinct characters in s1 and s2 from left to right. For example, suppose s1 is "abc" and s2 is "abg" , and s1.compareTo(s2) returns -4 . The first two characters ( a vs. a ) from s1 and s2 are compared. Because they are equal, the second two characters ( b vs. b ) are compared. Because they are also equal, the third two characters ( c vs. g ) are compared. Since the character c is 4 less than g , the comparison returns -4 .

Caution

Syntax errors will occur if you compare strings by using comparison operators, such as > , >= , < , or <= . Instead, you have to use s1.compareTo(s2) .


Note

The equals method returns true if two strings are equal, and false if they are not equal. The compareTo method returns , a positive integer, or a negative integer, depending on whether one string is equal to, greater than, or less than the other string.


The String class also provides equalsIgnoreCase and regionMatches methods for comparing strings. The equalsIgnoreCase method ignores the case of the letters when determining whether two strings are equal. The regionMatches method compares portions of two strings for equality. You can also use str.startsWith(prefix) to check whether string str starts with a specified prefix, and str.endsWith(suffix) to check whether string str ends with a specified suffix .

8.2.4. String Length and Retrieving Individual Characters

You can get the length of a string by invoking its length() method. For example, message.length() returns the length of the string message .

The s.charAt(index) method can be used to retrieve a specific character in a string s , where the index is between and s.length() “ 1 . For example, message.charAt(0) returns the character W , as shown in Figure 8.3.


[Page 266]
Figure 8.3. A String object is represented using an array internally.


Note

When you use a string, you often know its literal value. For convenience, Java allows you to use the string literal to refer directly to strings without creating new variables. Thus, "Welcome to Java".charAt(0) is correct and returns W .


Note

A string value is represented using a private array variable internally. The array cannot be accessed outside of the String class. The String class provides many public methods, such as length() and charAt(index) , to retrieve the array information. This is a good example of encapsulation: the detailed data structure of the class is hidden from the user through the private modifier, and thus the user cannot directly manipulate the internal data structure. If the array were not private, the user would be able to change the string content by modifying the array. This would violate the tenet that the String class is immutable.


Caution

Accessing characters in a string s out of bounds is a common programming error. To avoid it, make sure that you do not use an index beyond s.length() “ 1 . For example, s.charAt(s.length()) would cause a StringIndexOutOfBoundsException .


Caution

length is a method in the String class but is a property of an array object. So you have to use s.length() to get the number of characters in string s , and a.length to get the number of elements in array a .


8.2.5. String Concatenation

You can use the concat method to concatenate two strings. The statement shown below, for example, concatenates strings s1 and s2 into s3 :

 String s3 = s1.concat(s2); 

Since string concatenation is heavily used in programming, Java provides a convenient way to concatenate strings. You can use the plus ( + ) sign to concatenate two or more strings. So the above statement is equivalent to

 String s3 = s1 + s2; 

The following code combines the strings message , " and " , and "HTML" into one string:

 String myString = message +   " and "   +   "HTML"   ; 

Recall that the + sign can also concatenate a number with a string. In this case, the number is converted into a string and then concatenated . Note that at least one of the operands must be a string in order for concatenation to take place.


[Page 267]

8.2.6. Obtaining Substrings

You can obtain a single character from a string using the charAt method. You can also obtain a substring from a string using the substring method in the String class. The substring method has two versions:

  • public String substring(int beginIndex, int endIndex) Returns a new string that is a substring of the string. The substring begins at the specified beginIndex and extends to the character at index endIndex “ 1 , as shown in Figure 8.4. Thus the length of the substring is endIndex-beginIndex .

    Figure 8.4. The substring method obtains a substring from a string.

  • public String substring(int beginIndex) Returns a new string that is a substring of the string. The substring begins with the character at the specified index and extends to the end of the string, as shown in Figure 8.4.

For example,

 String message =   "Welcome to Java"   .substring(0, 11) +   "HTML"   ; 

The string message now becomes "Welcome to HTML" .

8.2.7. String Conversions

The contents of a string cannot be changed once the string is created. But you can obtain a new string using the toLowerCase , toUpperCase , trim , and replace methods. The toLowerCase and toUpperCase methods return a new string by converting all the characters in the string to lowercase or uppercase. The trim method returns a new string by eliminating blank characters from both ends of the string. The replace(oldChar, newChar) method can be used to replace all occurrences of a character in the string with a new character.

For example,

   "Welcome"   .  toLowerCase()  returns a new string, welcome.   "Welcome"   .  toUpperCase()  returns a new string, WELCOME.   "  Welcome"   .  trim()  returns a new string, Welcome.   "Welcome"   .  replace(  'e'  ,  'A'  )  returns a new string, WAlcomA.   "Welcome"   .  replaceFirst(  "e"  ,  "A"  )  returns a new string, WAlcome.   "Welcome"   .  replaceAll(  "e"  ,  "A"  )  returns a new string, WAlcomA. 

8.2.8. Finding a Character or a Substring in a String

You can use the indexOf and lastIndexOf methods to find a character or a substring in a string. Four overloaded indexOf methods and four overloaded lastIndexOf methods are defined in the String class.

  •    public int   indexOf(   int   ch)   (   public int   lastIndexOf(   int   ch)) 

    Returns the index of the first ( last ) character in the string that matches the specified character ch . Returns ”1 if the specified character is not in the string. When you pass a character to ch (e.g., indexOf('a') ), the character's Unicode value is passed to the parameter ch (e.g., the Unicode value for 'a' is 97 in decimal).


    [Page 268]
  •    public int   indexOf(   int   ch,   int   fromIndex)  (   public int   lastIndexOf(   int   ch,   int   endIndex)) 

    Returns the index of the first ( last ) character in the string starting from ( ending at ) the specified fromIndex ( endIndex ) that matches the specified character ch . Returns “1 if the specified character is not in the substring beginning at position fromIndex ( ending at position endIndex ).

  •    public int   indexOf(String str)  (   public int   lastIndexOf(String str)) 

    Returns the index of the first character of the ( last ) substring in the string that matches the specified string str . Returns “1 if the str argument is not in the string.

  •    public int   indexOf(String str,   int   fromIndex)  (   public int   lastIndexOf(String str, int endIndex)) 

    Returns the index of the first character of the ( last ) substring in the string starting from ( ending at ) the specified fromIndex ( endIndex ) that matches the specified string str . Returns “1 if the str argument is not in the substring.

For example,

   "Welcome to Java"   .indexOf(   'W'   ) returns     .   "Welcome to Java"   .indexOf(   'o'   ) returns   4   .   "Welcome to Java"   .indexOf(   'o'   ,   5   ) returns   9   .   "Welcome to Java"   .indexOf(   "come"   ) returns   3   .   "Welcome to Java"   .indexOf(   "Java"   ,   5   ) returns   11   .   "Welcome to Java"   .indexOf(   "java"   ,   5   ) returns   -1   .   "Welcome to Java"   .lastIndexOf(   'W'   ) returns     .   "Welcome to Java"   .lastIndexOf(   'o'   ) returns   9   .   "Welcome to Java"   .lastIndexOf(   'o'   ,   5   ) returns   4   .   "Welcome to Java"   .lastIndexOf(   "come   ") returns   3   .   "Welcome to Java"   .lastIndexOf(   "Java   ",   5   ) returns   -1   .   "Welcome to Java"   .lastIndexOf(   "java   ",   5   ) returns   -1   . 

8.2.9. Conversion Between Strings and Arrays

Strings are not arrays, but a string can be converted into an array, and vice versa. To convert a string to an array of characters, use the toCharArray method. For example, the following statement converts the string "Java" to an array:

   char   [] chars =   "Java"   .toCharArray(); 

So chars[0] is 'J' , chars[1] is 'a' , chars[2] is 'v' , and chars[3] is 'a' .

You can also use the getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method to copy a substring of the string from index srcBegin to index srcEnd-1 into a character array dst starting from index dstBegin . For example, the following code copies a substring " 3720 " in " CS3720 " from index 2 to index 6 “ 1 into the character array dst starting from index 4 :

   char   [] dst = {   'J'   ,   'A'   ,   'V'   ,   'A'   ,   '1'   ,   '3'   ,   '0'   ,   '1'   };   "CS3720"   .getChars(   2   ,   6   , dst,   4   ); 

Thus dst becomes { 'J' , 'A' , 'V' , 'A' , '3' , '7' , '2' , '0' }.


[Page 269]

To convert an array of characters into a string, use the String(char[]) constructor or the valueOf(char[]) method. For example, the following statement constructs a string from an array using the String constructor:

 String str =   new   String(   new   char[]{   'J'   ,   'a'   ,   'v'   ,   'a'   }); 

The next statement constructs a string from an array using the valueOf method.

 String str = String.valueOf(   new   char[]{   'J'   ,   'a'   ,   'v'   ,   'a'   }); 

8.2.10. Converting Characters and Numeric Values to Strings

The valueOf method can be used to convert an array of characters into a string. There are several overloaded versions of the valueOf method that can be used to convert a character and numeric values to strings with different parameter types, char , double , long , int , and float . For example, to convert a double value 5.44 to a string, use String.valueOf(5.44) . The return value is a string consisting of the characters '5' , '.' , '4' , and '4' .

Note

Use Double.parseDouble(str) or Integer.parseInt(str) to convert a string to a double value or an int value.


Tip

You can use regular expressions to parse and validate strings. For more information, see §8.6, "Regular Expressions."


8.2.11. Example: Checking Palindromes

This example writes a program that prompts the user to enter a string and reports whether the string is a palindrome, as shown in Figure 8.5. A string is a palindrome if it reads the same forward and backward. The words "mom," "dad," and "noon," for instance, are all palindromes.

Figure 8.5. The program checks whether a string is a palindrome.

One solution is to check whether the first character in the string is the same as the last character. If so, check whether the second character is the same as the second-last character. This process continues until a mismatch is found or all the characters in the string are checked, except for the middle character if the string has an odd number of characters.


[Page 270]

To implement this idea, use two variables, say low and high , to denote the position of two characters at the beginning and the end in a string s , as shown in Listing 8.1 (lines 24, 27). Initially, low is 0 and high is s.length() “ 1 . If the two characters at these positions match, increment low by 1 and decrement high by 1 (lines 33 “34). This process continues until ( low >= high ) or a mismatch is found.

Listing 8.1. CheckPalindrome.java
 1   import   javax.swing.JOptionPane;  2  3   public class   CheckPalindrome {  4  /** Main method */  5   public static void   main(String[] args) {  6  // Prompt the user to enter a string  7     String s = JOptionPane.showInputDialog(   "Enter a string:"   );  8  9  // Declare and initialize output string  10     String output =   ""   ; 11 12   if   (isPalindrome(s)) 13       output = s +   " is a palindrome"   ; 14   else   15       output = s +   " is not a palindrome"   ; 16 17  // Display the result  18     JOptionPane.showMessageDialog(   null   , output); 19   } 20 21  /** Check if a string is a palindrome */  22   public static boolean   isPalindrome(  String s  ) { 23  // The index of the first character in the string  24   int   low =     ; 25 26  // The index of the last character in the string  27   int   high =  s.length ()  -   1   ; 28 29   while   (low < high) { 30   if   (  s.charAt(low)  !=  s.charAt(high)  ) 31   return false   ;  // Not a palindrome  32 33       low++; 34       high; 35     } 36 37   return true   ;  // The string is a palindrome  38   } 39 } 

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

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