Class String

Class String is used to represent strings in Java. The next several subsections cover many of class String's capabilities.

29.3.1. String Constructors

Class String provides constructors for initializing String objects in a variety of ways. Four of the constructors are demonstrated in the main method of Fig. 29.1.

Figure 29.1. String class constructors.

(This item is displayed on page 1353 in the print version)

 1 // Fig. 29.1: StringConstructors.java
 2 // String class constructors.
 3
 4 public class StringConstructors
 5 {
 6 public static void main( String args[] )
 7 {
 8 char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a' , 'y' };
 9 String s = new String( "hello" );
10
11 // use String constructors 
12 String s1 = new String(); 
13 String s2 = new String( s ); 
14 String s3 = new String( charArray ); 
15 String s4 = new String( charArray, 6, 3);
16
17 System.out.printf(
18 "s1 = %s
s2 = %s
s3 = %s
s4 = %s
",
19 s1, s2, s3, s4 ); // display strings
20 } // end main
21 } // end class StringConstructors
 
s1 =
s2 = hello
s3 = birth day
s4 = day
 

Line 12 instantiates a new String object using class String's no-argument constructor and assigns its reference to s1. The new String object contains no characters (the empty string) and has a length of 0.

Line 13 instantiates a new String object using class String's constructor that takes a String object as an argument and assigns its reference to s2. The new String object contains the same sequence of characters as the String object s that is passed as an argument to the constructor.

Software Engineering Observation 29.1

It is not necessary to copy an existing String object. String objects are immutabletheir character contents cannot be changed after they are created, because class String does not provide any methods that allow the contents of a String object to be modified.

Line 14 instantiates a new String object and assigns its reference to s3 using class String's constructor that takes a char array as an argument. The new String object contains a copy of the characters in the array.

Line 15 instantiates a new String object and assigns its reference to s4 using class String's constructor that takes a char array and two integers as arguments. The second argument specifies the starting position (the offset) from which characters in the array are accessed. Remember that the first character is at position 0. The third argument specifies the number of characters (the count) to access in the array. The new String object contains a string formed from the accessed characters. If the offset or the count specified as an argument results in accessing an element outside the bounds of the character array, a String-IndexOutOfBoundsException is thrown. We discussed exceptions in detail in Chapter 13.

Common Programming Error 29.1

Attempting to access a character that is outside the bounds of a string (i.e., an index less than 0 or an index greater than or equal to the string's length) results in a StringIndexOutOfBounds-Exception.

 

29.3.2. String Methods length, charAt and getChars

String methods length, charAt and getChars return the length of a string, obtain the character at a specific location in a string and retrieve a set of characters from a string as a char array, respectively. The application in Fig. 29.2 demonstrates each of these methods.

Figure 29.2. String class character-manipulation methods.

 1 // Fig. 29.2: StringMiscellaneous.java
 2 // This application demonstrates the length, charAt and getChars
 3 // methods of the String class.
 4
 5 public class StringMiscellaneous
 6 {
 7 public static void main( String args[] )
 8 {
 9 String s1 = "hello there";
10 char charArray[] = new char[ 5 ];
11
12 System.out.printf( "s1: %s", s1 );
13
14 // test length method
15 System.out.printf( "
Length of s1: %d", s1.length() );
16
17 // loop through characters in s1 with charAt and display reversed
18 System.out.print( "
The string reversed is: " );
19
20 for ( int count = s1.length() - 1; count >= 0; count-- )
21 System.out.printf( "%s ", s1.charAt( count ) );
22
23 // copy characters from string into charArray
24 s1.getChars( 0, 5, charArray, 0 );
25 System.out.print( "
The character array is: " );
26
27 for ( char character : charArray )
28 System.out.print( character );
29
30 System.out.println();
31 } // end main
32 } // end class StringMiscellaneous
 
s1: hello there
Length of s1: 11
The string reversed is: e r e h t o l l e h
The character array is: hello
 

Line 15 uses String method length to determine the number of characters in string s1. Like arrays, strings always know their own length. However, unlike arrays, you cannot access a String's length via a length fieldinstead you must call the String's length method.

The for statement at lines 2021 print the characters of the string s1 in reverse order (and separated by spaces). String method charAt (line 21) returns the character at a specific position in the string. Method charAt receives an integer argument that is used as the index and returns the character at that position. Like arrays, the first element of a string is at position 0.

Line 24 uses String method getChars to copy the characters of a string into a character array. The first argument is the starting index in the string from which characters are to be copied. The second argument is the index that is one past the last character to be copied from the string. The third argument is the character array into which the characters are to be copied. The last argument is the starting index where the copied characters are placed in the target character array. Next, line 28 prints the char array contents one character at a time.

29.3.3. Comparing Strings

Chapter 7 discussed sorting and searching arrays. Frequently, the information being sorted or searched consists of strings that must be compared to place them into the proper order or to determine whether a string appears in an array (or other collection). Class String provides several methods for comparing stringsthese are demonstrated in the next two examples.

To understand what it means for one string to be greater than or less than another string, consider the process of alphabetizing a series of last names. You would, no doubt, place "Jones" before "Smith" because the first letter of "Jones" comes before the first letter of "Smith" in the alphabet. But the alphabet is more than just a list of 26 lettersit is an ordered set of characters. Each letter occurs in a specific position within the set. Z is more than just a letter of the alphabetit is specifically the twenty-sixth letter of the alphabet.

How does the computer know that one letter comes before another? All characters are represented in the computer as numeric codes (see Appendix B). When the computer compares two strings, it actually compares the numeric codes of the characters in the strings.

Figure 29.3 demonstrates String methods equals, equalsIgnoreCase, compareTo and regionMatches and using the equality operator == to compare String objects.

Figure 29.3. String comparisons.

(This item is displayed on pages 1356 - 1357 in the print version)

 1 // Fig. 29.3: StringCompare.java
 2 // String methods equals, equalsIgnoreCase, compareTo and regionMatches.
 3
 4 public class StringCompare
 5 {
 6 public static void main( String args[] )
 7 {
 8 String s1 = new String( "hello" ); // s1 is a copy of "hello"
 9 String s2 = "goodbye";
10 String s3 = "Happy Birthday";
11 String s4 = "happy birthday";
12
13 System.out.printf(
14 "s1 = %s
s2 = %s
s3 = %s
s4 = %s

", s1, s2, s3, s4 );
15
16 // test for equality
17 if ( s1 equals( "hello" ) ) // true
18 System.out.println( "s1 equals "hello"" );
19 else
20 System.out.println( "s1 does not equal "hello"" );
21
22 // test for equality with ==
23 if ( s1 == "hello" ) // false; they are not the same object
24 System.out.println( "s1 is the same object as "hello"" );
25 else
26 System.out.println( "s1 is not the same object as "hello"" );
27
28 // test for equality (ignore case)
29 if ( s3.equalsIgnoreCase( s4 ) ) // true
30 System.out.printf( "%s equals %s with case ignored
", s3, s4 );
31 else
32 System.out.println( "s3 does not equal s4" );
33
34 // test compareTo
35 System.out.printf(
36 "
s1.compareTo( s2 ) is %d", s1.compareTo( s2 ) );
37 System.out.printf(
38 "
s2.compareTo( s1 ) is %d", s2.compareTo( s1 ) );
39 System.out.printf(
40 "
s1.compareTo( s1 ) is %d", s1.compareTo( s1 ) );
41 System.out.printf(
42 "
s3.compareTo( s4 ) is %d", s3.compareTo( s4 ) );
43 System.out.printf(
44 "
s4.compareTo( s3 ) is %d

", s4.compareTo( s3 ) );
45
46 // test regionMatches (case sensitive)
47 if ( s3.regionMatches( 0, s4, 0, 5 ) )
48 System.out.println( "First 5 characters of s3 and s4 match" );
49 else
50 System.out.println(
51 "First 5 characters of s3 and s4 do not match" );
52
53 // test regionMatches (ignore case)
54 if ( s3. regionMatches( true, 0, s4, 0, 5 ) )
55 System.out.println( "First 5 characters of s3 and s4 match" );
56 else
57 System.out.println(
58 "First 5 characters of s3 and s4 do not match" );
59 } // end main
60 } // end class StringCompare
 
s1 = hello
s2 = goodbye
s3 = Happy Birthday
s4 = happy birthday

s1 equals "hello"
s1 is not the same object as "hello"
Happy Birthday equals happy birthday with case ignored

s1.compareTo( s2 ) is 1
s2.compareTo( s1 ) is -1
s1.compareTo( s1 ) is 0
s3.compareTo( s4 ) is -32
s4.compareTo( s3 ) is 32

First 5 characters of s3 and s4 do not match
First 5 characters of s3 and s4 match
 

The condition at line 17 uses method equals to compare string s1 and the string literal "hello" for equality. Method equals (a method of class Object overridden in String) tests any two objects for equalitythe strings contained in the two objects are identical. The method returns true if the contents of the objects are equal, and false otherwise. The preceding condition is TRue because string s1 was initialized with the string literal "hello". Method equals uses a lexicographical comparisonit compares the integer Unicode values (see Appendix F, Unicode, for more information) that represent each character in each string. Thus, if the string "hello" is compared with the string "HELLO", the result is false, because the integer representation of a lowercase letter is different from that of the corresponding uppercase letter.

The condition at line 23 uses the equality operator == to compare string s1 for equality with the string literal "hello". Operator == has different functionality when it is used to compare references than when it is used to compare values of primitive types. When primitive-type values are compared with ==, the result is true if both values are identical. When references are compared with ==, the result is true if both references refer to the same object in memory. To compare the actual contents (or state information) of objects for equality, a method must be invoked. In the case of Strings, that method is equals. The preceding condition evaluates to false at line 23 because the reference s1 was initialized with the statement

 s1 = new String( "hello" );

which creates a new String object with a copy of string literal "hello" and assigns the new object to variable s1. If s1 had been initialized with the statement

 s1 = "hello";

which directly assigns the string literal "hello" to variable s1, the condition would be TRue. Remember that Java treats all string literal objects with the same contents as one String object to which there can be many references. Thus, lines 8, 17 and 23 all refer to the same String object "hello" in memory.

Common Programming Error 29.2

Comparing references with == can lead to logic errors, because == compares the references to determine whether they refer to the same object, not whether two objects have the same contents. When two identical (but separate) objects are compared with ==, the result will be false. When comparing objects to determine whether they have the same contents, use method equals.

If you are sorting Strings, you may compare them for equality with method equals-IgnoreCase, which ignores whether the letters in each string are uppercase or lowercase when performing the comparison. Thus, the string "hello" and the string "HELLO" compare as equal. Line 29 uses String method equalsIgnoreCase to compare string s3Happy Birthdayfor equality with string s4happy birthday. The result of this comparison is true because the comparison ignores case sensitivity.

Lines 3544 use method compareTo to compare strings. Method compareTo is declared in the Comparable interface and implemented in the String class. Line 36 compares string s1 to string s2. Method compareTo returns 0 if the strings are equal, a negative number if the string that invokes compareTo is less than the string that is passed as an argument and a positive number if the string that invokes compareTo is greater than the string that is passed as an argument. Method compareTo uses a lexicographical comparisonit compares the numeric values of corresponding characters in each string. (For more information on the exact value returned by the compareTo method, see java.sun.com/j2se/5.0/docs/api/java/lang/String.html.)

The condition at line 47 uses String method regionMatches to compare portions of two strings for equality. The first argument is the starting index in the string that invokes the method. The second argument is a comparison string. The third argument is the starting index in the comparison string. The last argument is the number of characters to compare between the two strings. The method returns TRue only if the specified number of characters are lexicographically equal.

Finally, the condition at line 54 uses a five-argument version of String method regionMatches to compare portions of two strings for equality. When the first argument is true, the method ignores the case of the characters being compared. The remaining arguments are identical to those described for the four-argument regionMatches method.

The second example in this section (Fig. 29.4) demonstrates String methods startsWith and endsWith. Method main creates array strings containing the strings "started", "starting", "ended" and "ending". The remainder of method main consists of three for statements that test the elements of the array to determine whether they start with or end with a particular set of characters.

Figure 29.4. String class startsWith and endsWith methods.

(This item is displayed on page 1359 in the print version)

 1 // Fig. 29.4: StringStartEnd.java
 2 // String methods startsWith and endsWith.
 3
 4 public class StringStartEnd
 5 {
 6 public static void main( String args[] )
 7 {
 8 String strings[] = { "started", "starting", "ended", "ending" };
 9
10 // test method startsWith
11 for ( String string : strings )
12 {
13 if ( string.startsWith( "st" ) )
14 System.out.printf( ""%s" starts with "st"
", string );
15 } // end for
16
17 System.out.println();
18
19 // test method startsWith starting from position 2 of string
20 for ( String string : strings )
21 {
22 if ( string.startsWith( "art", 2 ) )
23 System.out.printf(
24 ""%s" starts with "art" at position 2
", string );
25 } // end for
26
27 System.out.println();
28
29 // test method endsWith
30 for ( String string : strings )
31 {
32 if ( string.endsWith( "ed" ) )
33 System.out.printf( ""%s" ends with "ed"
", string );
34 } // end for
35 } // end main
36 } // end class StringStartEnd
 
"started" starts with "st"
"starting" starts with "st"

"started" starts with "art" at position 2
"starting" starts with "art" at position 2

"started" ends with "ed"
"ended" ends with "ed"
 

The first for statement (lines 1115) uses the version of method startsWith that takes a String argument. The condition in the if statement (line 13) determines whether each String in the array starts with the characters "st". If so, the method returns true and the application prints that String. Otherwise, the method returns false and nothing happens.

The second for statement (lines 2025) uses the startsWith method that takes a String and an integer as arguments. The integer specifies the index at which the comparison should begin in the string. The condition in the if statement (line 22) determines whether each String in the array has the characters "art" beginning with the third character in each string. If so, the method returns true and the application prints the String.

The third for statement (lines 3034) uses method endsWith, which takes a String argument. The condition at line 32 determines whether each String in the array ends with the characters "ed". If so, the method returns true and the application prints the String.

29.3.4. Locating Characters and Substrings in Strings

Often it is useful to search for a character or set of characters in a string. For example, if you are creating your own word processor, you might want to provide a capability for searching through documents. Figure 29.5 demonstrates the many versions of String methods indexOf and lastIndexOf that search for a specified character or substring in a string. All the searches in this example are performed on the string letters (initialized with "abcdefghijklmabcdefghijklm") in method main. Lines 1116 use method indexOf to locate the first occurrence of a character in a string. If method indexOf finds the character, it returns the character's index in the stringotherwise, indexOf returns 1. There are two versions of indexOf that search for characters in a string. The expression in line 12 uses the version of method indexOf that takes an integer representation of the character to find. The expression at line 14 uses another version of method indexOf, which takes two integer argumentsthe character and the starting index at which the search of the string should begin.

Figure 29.5. String class searching methods.

(This item is displayed on pages 1360 - 1361 in the print version)

 1 // Fig. 29.5: StringIndexMethods.java
 2 // String searching methods indexOf and lastIndexOf.
 3
 4 public class StringIndexMethods
 5 {
 6 public static void main( String args[] )
 7 {
 8 String letters = "abcdefghijklmabcdefghijklm";
 9
10 // test indexOf to locate a character in a string
11 System.out.printf(
12 "'c' is located at index %d
", letters.indexOf( 'c' ) );
13 System.out.printf(
14 "'a' is located at index %d
", letters.indexOf( 'a', 1 ) );
15 System.out.printf(
16 "'$' is located at index %d

", letters.indexOf( '$' ) );
17
18 // test lastIndexOf to find a character in a string
19 System.out.printf( "Last 'c' is located at index %d
",
20 letters.lastIndexOf( 'c' ) );
21 System.out.printf( "Last 'a' is located at index %d
",
22 letters.lastIndexOf( 'a', 25 ) );
23 System.out.printf( "Last '$' is located at index %d

",
24 letters.lastIndexOf( '$' ) );
25
26 // test indexOf to locate a substring in a string
27 System.out.printf( ""def" is located at index %d
",
28 letters.indexOf( "def" ) );
29 System.out.printf( ""def" is located at index %d
",
30 letters.indexOf( "def",7 ) );
31 System.out.printf( ""hello" is located at index %d

",
32 letters.indexOf( "hello" ) );
33
34 // test lastIndexOf to find a substring in a string
35 System.out.printf( "Last "def" is located at index %d
",
36 letters.lastIndexOf( "def" ) );
37 System.out.printf( "Last "def" is located at index %d
",
38 letters.lastIndexOf( "def", 25 ) );
39 System.out.printf( "Last "hello" is located at index %d
",
40 letters.lastIndexOf( "hello" ) );
41 } // end main
42 } // end class StringIndexMethods
 
'c' is located at index 2
'a' is located at index 13
'$' is located at index -1

Last 'c' is located at index 15
Last 'a' is located at index 13
Last '$' is located at index -1

"def" is located at index 3
"def" is located at index 16
"hello" is located at index -1

Last "def" is located at index 16
Last "def" is located at index 16
Last "hello" is located at index -1
 

The statements at lines 1924 use method lastIndexOf to locate the last occurrence of a character in a string. Method lastIndexOf performs the search from the end of the string toward the beginning of the string. If method lastIndexOf finds the character, it returns the index of the character in the stringotherwise, lastIndexOf returns 1. There are two versions of lastIndexOf that search for characters in a string. The expression at line 20 uses the version of method lastIndexOf that takes the integer representation of the character. The expression at line 22 uses the version of method lastIndexOf that takes two integer argumentsthe integer representation of the character and the index from which to begin searching backward.

Lines 2740 demonstrate versions of methods indexOf and lastIndexOf that each take a String as the first argument. These versions of the methods perform identically to those described earlier except that they search for sequences of characters (or substrings) that are specified by their String arguments. If the substring is found, these methods return the index in the string of the first character in the substring.

29.3.5. Extracting Substrings from Strings

Class String provides two substring methods to enable a new String object to be created by copying part of an existing String object. Each method returns a new String object. Both methods are demonstrated in Fig. 29.6.

Figuire 29.6. String class substring methods.

 1 // Fig. 29.6: SubString.java
 2 // String class substring methods.
 3
 4 public class SubString
 5 {
 6 public static void main( String args[] )
 7 {
 8 String letters = abcdefghijklmabcdefghijklm";
 9
10 // test substring methods
11 System.out.printf( "Substring from index 20 to end is "%s"
",
12 letters.substring( 20 ) );
13 System.out.printf( "%s "%s"
",
14 "Substring from index 3 up to, but not including 6 is",
15 letters.substring( 3, 6 ) );
16 } // end main
17 } // end class SubString
 
Substring from index 20 to end is "hijklm"
Substring from index 3 up to, but not including 6 is "def"
 

The expression letters.substring( 20 ) at line 12 uses the substring method that takes one integer argument. The argument specifies the starting index in the original string letters from which characters are to be copied. The substring returned contains a copy of the characters from the starting index to the end of the string. Specifying an index outside the bounds of the string causes a StringIndexOutOfBoundsException.

The expression letters.substring( 3, 6 ) at line 15 uses the substring method that takes two integer arguments. The first argument specifies the starting index from which characters are copied in the original string. The second argument specifies the index one beyond the last character to be copied (i.e., copy up to, but not including, that index in the string). The substring returned contains a copy of the specified characters from the original string. Specifying an index outside the bounds of the string causes a StringIndexOutOfBoundsException.

29.3.6. Concatenating Strings

String method concat (Fig. 29.7) concatenates two String objects and returns a new String object containing the characters from both original strings. The expression s1.concat( s2 ) at line 13 forms a string by appending the characters in string s2 to the characters in string s1. The original Strings to which s1 and s2 refer are not modified.

Figure 29.7. String method concat.

 1 // Fig. 29.7: StringConcatenation.java
 2 // String concat method.
 3
 4 public class StringConcatenation
 5 {
 6 public static void main( String args[] )
 7 {
 8 String s1 = new String( "Happy " );
 9 String s2 = new String( "Birthday" );
10
11 System.out.printf( "s1 = %s
s2 = %s

", s1, s2 );
12 System.out.printf(
13 "Result of s1.concat( s2 ) = %s
", s1.concat( s2 ) );
14 System.out.printf( "s1 after concatenation = %s
", s1 );
15 } // end main
16 } // end class StringConcatenation
 
s1 = Happy
s2 = Birthday

Result of s1.concat( s2 ) = Happy Birthday
s1 after concatenation = Happy
 

29.3.7. Miscellaneous String Methods

Class String provides several methods that return modified copies of strings or that return character arrays. These methods are demonstrated in the application in Fig. 29.8.

Figure 29.8. String methods replace, toLowerCase, toUpperCase, trim and toCharArray.

(This item is displayed on page 1363 in the print version)

 1 // Fig. 29.8: StringMiscellaneous2.java
 2 // String methods replace, toLowerCase, toUpperCase, trim and toCharArray.
 3
 4 public class StringMiscellaneous2
 5 {
 6 public static void main( String args[] )
 7 {
 8 String s1 = new String( "hello" );
 9 String s2 = new String( "GOODBYE" );
10 String s3 = new String( " spaces " );
11
12 System.out.printf( "s1 = %s
s2 = %s
s3 = %s

", s1, s2, s3 );
13
14 // test method replace
15 System.out.printf(
16 "Replace 'l' with 'L' in s1: %s

", s1.replace( 'l', 'L' ) );
17
18 // test toLowerCase and toUpperCase
19 System.out.printf( "s1.toUpperCase() = %s
", s1.toUpperCase() );
20 System.out.printf( "s2.toLowerCase() = %s

", s2.toLowerCase() );
21
22 // test trim method
23 System.out.printf( "s3 after trim = "%s"

", s3.trim() );
24
25 // test toCharArray method
26 char charArray[] = s1.toCharArray();
27 System.out.print( "s1 as a character array = " );
28
29 for ( char character : charArray )
30 System.out.print( character );
31
32 System.out.println();
33 } // end main
34 } // end class StringMiscellaneous2
 
s1 = hello
s2 = GOODBYE
s3 = spaces

Replace 'l' with 'L' in s1: heLLo

s1.toUpperCase() = HELLO
s2.toLowerCase() = goodbye

s3 after trim = "spaces"

s1 as a character array = hello
 

Line 16 uses String method replace to return a new String object in which every occurrence in string s1 of character 'l' (lowercase el) is replaced with character 'L'. Method replace leaves the original string unchanged. If there are no occurrences of the first argument in the string, method replace returns the original string.

Line 19 uses String method toUpperCase to generate a new String object with uppercase letters where corresponding lowercase letters exist in s1. The method returns a new String object containing the converted string and leaves the original string unchanged. If there are no characters to convert, method toUpperCase returns the original string.

Line 20 uses String method toLowerCase to return a new String object with lowercase letters where corresponding uppercase letters exist in s2. The original string remains unchanged. If there are no characters in the original string to convert, toLowerCase returns the original string.

Line 23 uses String method TRim to generate a new String object that removes all whitespace characters that appear at the beginning or end of the string on which trim operates. The method returns a new String object containing the string without leading or trailing white space. The original string remains unchanged.

Line 26 uses String method toCharArray to create a new character array containing a copy of the characters in string s1. Lines 2930 output each char in the array.

29.3.8. String Method valueOf

As we have seen, every object in Java has a toString method that enables a program to obtain the object's string representation. Unfortunately, this technique cannot be used with primitive types because they do not have methods. Class String provides static methods that take an argument of any type and convert the argument to a String object. Figure 29.9 demonstrates the String class valueOf methods.

Figure 29.9. String class valueOf methods.

(This item is displayed on page 1365 in the print version)

 1 // Fig. 29.9: StringValueOf.java
 2 // String valueOf methods.
 3
 4 public class StringValueOf
 5 {
 6 public static void main( String args[] )
 7 {
 8 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
 9 boolean booleanValue = true;
10 char characterValue = 'Z';
11 int integerValue = 7;
12 long longValue = 10000000000L; // L suffix indicates long 
13 float floatValue = 2.5f; // f indicates that 2.5 is a float
14 double doubleValue = 33.333; // no suffix, double is default
15 Object objectRef = "hello"; // assign string to an Object reference
16
17 System.out.printf(
18 "char array = %s
", String.valueOf( charArray ) );
19 System.out.printf( "part of char array = %s
",
20 String.valueOf( charArray, 3, 3 ) );
21 System.out.printf(
22 "boolean = %s
", String.valueOf( booleanValue ) );
23 System.out.printf(
24 "char = %s
", String.valueOf( characterValue ) );
25 System.out.printf( "int = %s
", String.valueOf( integerValue ) );
26 System.out.printf( "long = %s
", String.valueOf( longValue ) );
27 System.out.printf( "float = %s
", String.valueOf( floatValue ) );
28 System.out.printf(
29 "double = %s
", String.valueOf( doubleValue ) );
30 System.out.printf( "Object = %s", String.valueOf( objectRef ) );
31 } // end main
32 } // end class StringValueOf
 
char array = abcdef
part of char array = def
boolean = true
char = Z
int = 7
long = 10000000000
float = 2.5
double = 33.333
Object = hello
 

The expression String.valueOf( charArray ) at line 18 uses the character array charArray to create a new String object. The expression String.valueOf( charArray, 3, 3 ) at line 20 uses a portion of the character array charArray to create a new String object. The second argument specifies the starting index from which the characters are used. The third argument specifies the number of characters to be used.

There are seven other versions of method valueOf, which take arguments of type boolean, char, int, long, float, double and Object, respectively. These are demonstrated in lines 2130. Note that the version of valueOf that takes an Object as an argument can do so because all Objects can be converted to Strings with method toString.

[Note: Lines 1314 use literal values 10000000L and 2.5f as the initial values of long variable longValue and float variable floatValue, respectively. By default, Java treats integer literals as type int and floating-point literals as type double. Appending the letter L to the literal 10000000 and appending letter f to the literal 2.5 indicates to the compiler that 10000000 should be treated as a long and that 2.5 should be treated as a float. An uppercase L or lowercase l can be used to denote a variable of type long and an uppercase F or lowercase f can be used to denote a variable of type float.]

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

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