- 7.1 Introduction
- 7.2 Fundamentals of Characters and Strings
- 7.3 Class String
- 7.4 Class StringBuilder
- 7.5 Class Character
- 7.6 Tokenizing Strings
- 7.7 Intro to Natural Language Processing (NLP)-at the Root of Generative AI<sup><a id="fn7_5" href="ch07.xhtml#fn7_5a">5</a></sup>
- 7.8 Objects-Natural Case Study: Intro to Regular Expressions in NLP
- 7.9 Objects-Natural Security Case Study: pMa5tfEKwk59dTvC04Ft1IFQz9mEXnkfYXZwxk4ujGE=
- 7.10 Wrap-Up
7.3 Class String
The next several subsections cover many of class String’s capabilities.
7.3.1 Creating String Objects
Figure 7.1 shows several ways to create and initialize String objects.
1 // Fig. 7.1: StringConstructors.java
2 // String class constructors.
3
4 public class StringConstructors {
5 public static void main(String[] args) {
6 char[] charArray = {'b', 'i', 'r', 't', 'h', 'd', 'a', 'y'};
7 var s = new String("hello");
8
9 // use String constructors
10 var s1 = new String(); // ""
11 var s2 = new String(s); // "hello"
12 var s3 = new String(charArray); // "birthday"
13 var s4 = new String(charArray, 5, 3); // "day"
14
15 System.out.printf(
16 "s1 = %s%ns2 = %s%ns3 = %s%ns4 = %s%n", s1, s2, s3, s4);
17 }
18 }
s1 = s2 = hello s3 = birthday s4 = day
Fig. 7.1 | String class constructors.
Line 7 uses the new operator to create a String object. The variable s is initialized with the result of the expression
new String("hello")
which is formally called a class instance creation expression.3 The new operator creates an object (that is, an instance) of the specified class—in this case, String. The parentheses that follow the class name represent a call to a constructor, which is similar to a method but is called implicitly by the new operator to initialize an object when it’s created. Line 7 calls the String constructor that copies another String’s contents into the new String object. We’ll discuss constructors in detail in Chapter 8.
Line 10 creates a new String using the String no-argument constructor, which creates a String object containing no characters (i.e., the empty string, which can also be represented as ""). Line 11 creates a new String object containing a copy of its argument s, which contains "hello". Line 12 creates a new String object containing a copy of the characters in the String constructor’s char array argument.
Line 13 creates a new String object using the String constructor that takes a char array and two integers as arguments. The second argument specifies the starting position (the offset; String indices start at 0) from which characters in the array are copied. The third argument specifies the number of characters (the count) to copy from the array. If the offset or the count specified as an argument results in accessing an element outside the array’s bounds, an IndexOutOfBoundsException occurs.
Generative AI
1 Prompt genAIs to add meaningful comments to the program in Fig. 7.1, then compare the results to the original program.
7.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. Figure 7.2 demonstrates these methods.
1 // Fig. 7.2: StringMiscellaneous.java
2 // This program demonstrates the length, charAt and getChars
3 // methods of the String class.
4
5 public class StringMiscellaneous {
6 public static void main(String[] args) {
7 String s1 = "hello there";
8 char[] charArray = new char[5];
9
10 System.out.printf("s1: %s", s1);
11
12 // test length method
13 System.out.printf("%nLength of s1: %d", s1.length());
14
15 // loop through characters in s1 with charAt and display reversed
16 System.out.printf("%nThe string reversed is: ");
17
18 for (int count = s1.length() - 1; count >= 0; --count) {
19 System.out.printf("%c ", s1.charAt(count));
20 }
21
22 // copy characters from s1 into charArray
23 s1.getChars(0, 5, charArray, 0);
24 System.out.printf("%nThe character array is: ");
25
26 for (char character : charArray) {
27 System.out.print(character);
28 }
29
30 System.out.println();
31 }
32 }
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
Fig. 7.2 | String methods length, charAt and getChars.
Line 13 uses String method length to determine the number of characters in String s1. Like arrays, Strings know their own length. However, unlike arrays, you access a String’s length using the String’s length method.
Lines 18–20 print the characters of the String s1 in reverse order (and separated by spaces). String method charAt (line 19) returns the character at a specific position in the String. Method charAt receives an integer argument representing an index and returns the character at that index. Like arrays, the first element of a String is at position 0.
Line 23 uses the String method getChars to copy the characters of a String into a character array. The first argument is the starting index from which characters are copied. The second argument is the index that’s one past the last character to copy from the String. The third argument is the character array into which the characters are copied. The last argument is the starting index where the copied characters are placed in the target character array. Next, lines 26–28 print the char array contents one character at a time.
Generative AI
1 Prompt genAIs to write a counting for statement equivalent to the enhanced for statement in lines 26–28 of Fig. 7.2. Ask them to comment on why the enhanced for statement is preferred.
7.3.3 Comparing Strings
Frequently, information being sorted or searched consists of Strings that must be compared to place them into order or to determine whether a String appears in an array (or other collection). Class String provides methods for comparing Strings, as demonstrated in Figs. 7.3–7.4.
To understand what it means for one String to be greater than or less than another, consider the process of alphabetizing a series of last names. No doubt, you’d place “Garcia” before “Tanaka” because the first letter of “Garcia” comes before the first letter of “Tanaka” in the alphabet. The alphabet is more than just a list of 26 letters—it’s an ordered list of characters. Each letter occurs in a specific position within the list. Z is more than just a letter of the alphabet—it’s specifically the twenty-sixth letter of the alphabet.
How does Java know that one letter “comes before” another? All characters are represented internally as numeric codes in the Unicode character set. When Java compares Strings, it compares their characters using lexicographical comparison—that is, it compares the characters’ Unicode numeric values.
Figure 7.3 demonstrates several String comparison methods and using the equality operator == to compare String objects. We broke this example into pieces for discussion purposes. Lines 6–12 create and display several Strings for use in this example.
1 // Fig. 7.3: StringCompare.java
2 // Comparing Strings and portions of Strings.
3
4 public class StringCompare {
5 public static void main(String[] args) {
6 String s1 = new String("hello"); // s1 is a copy of "hello"
7 String s2 = "goodbye";
8 String s3 = "Happy Birthday";
9 String s4 = "happy birthday";
10
11 System.out.printf(
12 "s1 = %s%ns2 = %s%ns3 = %s%ns4 = %s%n%n", s1, s2, s3, s4);
13
s1 = hello s2 = goodbye s3 = Happy Birthday s4 = happy birthday
Fig. 7.3 | String methods equals, equalsIgnoreCase, compareTo and regionMatches.
String Method equals
Line 15 uses String method equals to compare String s1 and the String literal "hello" for equality:
14 // test for equality
15 if (s1.equals("hello")) { // true
16 System.out.println("s1 equals \"hello\"");
17 }
18 else {
19 System.out.println("s1 does not equal \"hello\"");
20 }
21
s1 equals "hello"
For Strings, the equals method determines whether the contents of the two Strings are identical. If so, it returns true; otherwise, it returns false. Line 15’s condition is true because String s1 was initialized with the literal "hello". Method equals uses a lexicographical comparison. So, if the String "hello" is compared to the String "HELLO", the result is false, because the integer representation of 'h' is different from that of 'H'.
Comparing Strings with the == Operator
Line 23’s condition uses the equality operator == to compare String s1 for equality with the String literal "hello".
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 }
26 else {
27 System.out.println("s1 is not the same object as \"hello\"");
28 }
29
s1 is not the same object as "hello"
When comparing primitive-type values with ==, the result is true if both values are identical. When comparing references with ==, the result is true if both refer to the same object in memory. You must call a method to compare objects’ contents for equality. For Strings, that method is equals. Line 23’s condition evaluates to false because the reference s1 was initialized with the statement
s1 = new String("hello");
which creates a new String object containing a copy of "hello" and assigns the new object to variable s1. The condition would be true if s1 had been initialized by directly assigning "hello" to variable s1 as in:
s1 = "hello";
Remember that Java treats all String literals with the same contents as one String object with many references to it. Thus, the "hello" literals in lines 6, 15 and 23 all refer to the same String object.
String Method equalsIgnoreCase
When sorting Strings, you might compare them for equality with the String class’s equalsIgnoreCase method, which performs a case-insensitive comparison. Thus, "hello" and "HELLO" compare as equal. Line 31 uses equalsIgnoreCase to compare String s3—Happy Birthday—for equality with String s4—happy birthday. This comparison is true because the method ignores the case.
30 // test for equality (ignore case)
31 if (s3.equalsIgnoreCase(s4)) { // true
32 System.out.printf("%s equals %s with case ignored%n", s3, s4);
33 }
34 else {
35 System.out.println("s3 does not equal s4");
36 }
37
Happy Birthday equals happy birthday with case ignored
String Method compareTo
Lines 39–48 use the String method compareTo to compare Strings. Line 40 compares String s1 ("hello") to String s2 ("goodbye"). Method compareTo returns
0 if the Strings are equal,
a negative number if the String that calls the method is less than the String argument and
a positive number if the String that calls the method is greater than the String argument.
The method uses lexicographical comparison to compare the Unicode numeric values of each String’s corresponding characters.
38 // test compareTo 39 System.out.printf( 40 "%ns1.compareTo(s2) is %d", s1.compareTo(s2)); 41 System.out.printf( 42 "%ns2.compareTo(s1) is %d", s2.compareTo(s1)); 43 System.out.printf( 44 "%ns1.compareTo(s1) is %d", s1.compareTo(s1)); 45 System.out.printf( 46 "%ns3.compareTo(s4) is %d", s3.compareTo(s4)); 47 System.out.printf( 48 "%ns4.compareTo(s3) is %d%n%n", s4.compareTo(s3)); 49
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
String Method regionMatches
The condition at line 51 uses a version of the String method regionMatches to compare portions of two Strings for equality. The first argument to this version of the method 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. The method returns true only if the characters compared are lexicographically equal.
Finally, the condition at line 60 uses a five-argument version of regionMatches to compare portions of two Strings for equality. When the first argument is true, the method ignores characters’ case. The remaining arguments are identical to those described for the four-argument regionMatches method.
50 // test regionMatches (case sensitive)
51 if (s3.regionMatches(0, s4, 0, 5)) {
52 System.out.println("First 5 characters of s3 and s4 match");
53 }
54 else {
55 System.out.println(
56 "First 5 characters of s3 and s4 do not match");
57 }
58
59 // test regionMatches (ignore case)
60 if (s3.regionMatches(true, 0, s4, 0, 5)) {
61 System.out.println(
62 "First 5 characters of s3 and s4 match with case ignored\n");
63 }
64 else {
65 System.out.println(
66 "First 5 characters of s3 and s4 do not match\n");
67 }
68
First 5 characters of s3 and s4 do not match First 5 characters of s3 and s4 match with case ignored
String Method isBlank
Line 70 uses String method isBlank to determine whether " \t\n" contains only whitespace characters. In this case, isBlank returns true because the String contains three whitespace characters—a space, a tab and a newline.
69 // test whether a String contains only whitespace
70 System.out.printf("\" \\t\\n\".isBlank(): %b%n", " \t\n".isBlank());
71 }
72 }
" \t\n".isBlank(): true
String Methods startsWith and endsWith
Figure 7.4 demonstrates String methods startsWith (lines 10 and 19) and endsWith (line 29). Method main creates the array strings containing "started", "starting", "ended" and "ending". We use three for statements to test the array elements, determining whether they start with or end with a particular set of characters.
1 // Fig. 7.4: StringStartEnd.java
2 // String methods startsWith and endsWith.
3
4 public class StringStartEnd {
5 public static void main(String[] args) {
6 String[] strings = {"started", "starting", "ended", "ending"};
7
8 // test method startsWith
9 for (String string : strings) {
10 if (string.startsWith("st")) {
11 System.out.printf("\"%s\" starts with \"st\"%n", string);
12 }
13 }
14
15 System.out.println();
16
17 // test method startsWith starting from position 2 of string
18 for (String string : strings) {
19 if (string.startsWith("art", 2)) {
20 System.out.printf(
21 "\"%s\" starts with \"art\" at position 2%n", string);
22 }
23 }
24
25 System.out.println();
26
27 // test method endsWith
28 for (String string : strings) {
29 if (string.endsWith("ed")) {
30 System.out.printf("\"%s\" ends with \"ed\"%n", string);
31 }
32 }
33 }
34 }
"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"
Fig. 7.4 | String methods startsWith and endsWith.
Lines 9–13 use the version of method startsWith that takes a String argument. The condition in the if statement (line 10) determines whether each String starts with the characters "st". If so, the method returns true, and the program prints that String; otherwise, the method returns false and nothing is printed.
Lines 18–23 use the startsWith method that takes a String and an integer as arguments. The integer specifies the index in the String where the comparison should begin. The condition in line 19 determines whether each String has the characters "art" starting with the character at index 2 in each String. If so, the method returns true, and the program prints the String.
The third for statement (lines 28–32) uses the method endsWith, which takes a String argument. The condition in line 29 determines whether each String ends with the characters "ed". If so, the method returns true, and the program prints the String.
Generative AI
1 Prompt genAIs to write Java code proving that all instances of a String literal in a program are one object in memory, whereas a new String object initialized with that same String literal is a different object. Ask the generative AIs to explain precisely how those comparisons work.
2 Prompt genAIs asking them to explain why Java’s String method compareTo does not always return -1 or 1 when Strings are not equal.
7.3.4 Locating Characters and Substrings in Strings
Often, it’s useful to search a String for a character or set of characters (known as a substring). For example, if you’re creating your own text editor, you might include a capability to search for text in the current document. Figure 7.5 demonstrates the several versions of the String methods indexOf and lastIndexOf that search for a specified character or substring in a String. We broke this example into pieces for discussion purposes. This example’s searches use the String letters ("abcdefghijklmabcdefghijklm").
1 // Fig. 7.5: StringIndexMethods.java
2 // String searching methods indexOf and lastIndexOf.
3
4 public class StringIndexMethods {
5 public static void main(String[] args) {
6 String letters = "abcdefghijklmabcdefghijklm";
7
Fig. 7.5 | String-searching methods indexOf and lastIndexOf.
Searching for Characters with Method indexOf
Lines 9–14 use method indexOf to locate the first occurrence of a character in a String. If the method finds the character, it returns the character’s index in the String—otherwise, it returns –1. There are two versions of indexOf that search for characters in a String. The expression in line 10 uses the indexOf version that takes an integer representation of the character to find. The expression at line 12 uses another version of indexOf that takes two integer arguments—the character to find and the starting index at which the search should begin.
8 // test indexOf to locate a character in a String
9 System.out.printf(
10 "'c' is located at index %d%n", letters.indexOf('c'));
11 System.out.printf(
12 "'a' is located at index %d%n", letters.indexOf('a', 1));
13 System.out.printf(
14 "'$' is located at index %d%n%n", letters.indexOf('$'));
15
'c' is located at index 2 'a' is located at index 13 '$' is located at index -1
Searching for Characters with Method lastIndexOf
Lines 17–22 use lastIndexOf to locate the last occurrence of a character in a String. The method searches from the end of the String. If it finds the character, it returns the character’s index—otherwise, it returns –1. There are two versions of lastIndexOf. The expression at line 18 uses the version that takes the int representation of the character to find. The expression at line 20 uses the version that takes two int arguments—the int representation of the character to find and the index from which to begin searching backward.
16 // test lastIndexOf to find a character in a String
17 System.out.printf("Last 'c' is located at index %d%n",
18 letters.lastIndexOf('c'));
19 System.out.printf("Last 'a' is located at index %d%n",
20 letters.lastIndexOf('a', 25));
21 System.out.printf("Last '$' is located at index %d%n%n",
22 letters.lastIndexOf('$'));
23
Last 'c' is located at index 15 Last 'a' is located at index 13 Last '$' is located at index -1
Searching for Substrings with indexOf and lastIndexOf
Lines 25–38 demonstrate versions of methods indexOf and lastIndexOf that take a String as the first argument. These versions perform identically to those described earlier but they search for substrings 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.
24 // test indexOf to locate a substring in a String
25 System.out.printf("\"def\" is located at index %d%n",
26 letters.indexOf("def"));
27 System.out.printf("\"def\" is located at index %d%n",
28 letters.indexOf("def", 7));
29 System.out.printf("\"hello\" is located at index %d%n%n",
30 letters.indexOf("hello"));
31
32 // test lastIndexOf to find a substring in a String
33 System.out.printf("Last \"def\" is located at index %d%n",
34 letters.lastIndexOf("def"));
35 System.out.printf("Last \"def\" is located at index %d%n",
36 letters.lastIndexOf("def", 25));
37 System.out.printf("Last \"hello\" is located at index %d%n",
38 letters.lastIndexOf("hello"));
39 }
40 }
"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
Generative AI
1 Prompt genAIs to write statements that do the following:
Write Java code that locates the first occurrence of the substring "be" in the String "to be or not to be", then display the index.
Write a Java expression that locates the last occurrence of the substring "be" in the String "to be or not to be", then display the index.
Compare the generated results to the following code:
String s = "to be or not to be";
System.out.printf("First occurrence of \"be\" is at index: %d%n",
s.indexOf("be"));
System.out.printf("Last occurrence of \"be\" is at index: %d%n",
s.lastIndexOf("be"));
First occurrence of "be" is at index: 3 Last occurrence of "be" is at index: 16
7.3.5 Extracting Substrings from Strings
Each of the two String class substring methods creates and returns a new String object by copying part of an existing one. Figure 7.6 demonstrates both methods.
1 // Fig. 7.6: SubString.java
2 // String class substring methods.
3
4 public class SubString {
5 public static void main(String[] args) {
6 String letters = "abcdefghijklmabcdefghijklm";
7
8 // test substring methods
9 System.out.printf("Substring from index 20 to end is \"%s\"%n",
10 letters.substring(20));
11 System.out.printf("%s \"%s\"%n",
12 "Substring from index 3 up to, but not including, 6 is",
13 letters.substring(3, 6));
14 }
15 }
Substring from index 20 to end is "hijklm" Substring from index 3 up to, but not including, 6 is "def"
Fig. 7.6 | String class substring methods.
The expression letters.substring(20) at line 10 uses the substring method that takes one integer argument. The argument specifies the starting index in the original String letters from which to copy characters. 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 an IndexOutOfBoundsException.
Line 13 uses the substring method that takes two integer arguments—the starting index from which to copy characters in the original String and the index one beyond the last character to copy (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. An index outside the bounds of the String causes a IndexOutOfBoundsException.
Generative AI
1 Prompt genAIs to write code that catches the exception thrown when code attempts to access characters outside a String’s bounds. The code should catch and display Index-OutOfBoundsExceptions.
7.3.6 Concatenating Strings
String method concat (Fig. 7.7) concatenates two String objects (like the + operator) and returns a new String object containing the characters from both original Strings. The expression s1.concat(s2) at line 11 forms a String by appending the characters in s2 to those in s1. Line 12 prints s1 after the String concatenation to show that it was not modified—again, Strings are immutable, so methods like concat return new Strings.
1 // Fig. 7.7: StringConcatenation.java
2 // String method concat.
3
4 public class StringConcatenation {
5 public static void main(String[] args) {
6 String s1 = "Happy ";
7 String s2 = "Birthday";
8
9 System.out.printf("s1 = %s%ns2 = %s%n%n",s1, s2);
10 System.out.printf(
11 "Result of s1.concat(s2) = %s%n", s1.concat(s2));
12 System.out.printf("s1 after concatenation = %s%n", s1);
13 }
14 }
s1 = Happy s2 = Birthday Result of s1.concat(s2) = Happy Birthday s1 after concatenation = Happy
Fig. 7.7 | String method concat.
7.3.7 Miscellaneous String Methods
Class String provides several methods that return Strings or character arrays containing modified copies of an original String’s contents (Fig. 7.8). We broke this example into pieces for discussion purposes. Lines 6–10 create and display the String objects used in this example.
1 // Fig. 7.8: StringMiscellaneous2.java
2 // String methods replace, toLowerCase, toUpperCase, trim and toCharArray.
3
4 public class StringMiscellaneous2 {
5 public static void main(String[] args) {
6 String s1 = "hello";
7 String s2 = "GOODBYE";
8 String s3 = " spaces ";
9
10 System.out.printf("s1: \"%s\"%ns2: \"%s\"%ns3: \"%s\"", s1, s2, s3);
11
s1: "hello" s2: "GOODBYE" s3: " spaces "
Fig. 7.8 | String methods replace, toLowerCase, toUpperCase, trim and toCharArray.
Replacing Characters in a String
Line 14 uses String method replace to return a new String object in which every occurrence in 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, replace returns the original String. An overloaded version of method replace enables you to replace substrings rather than individual characters.
12 // test method replace
13 System.out.printf(
14 "%n%nReplace 'l' with 'L' in s1: %s%n%n", s1.replace('l', 'L'));
15
Replace 'l' with 'L' in s1: heLLo
Changing a String’s Case
Line 17 uses the String method toUpperCase to get a new String with uppercase letters replacing any lowercase letters in s1, leaving the original String unchanged. If there are no characters to convert, toUpperCase returns the original String. Line 18 uses the String method toLowerCase to get a new String object with lowercase letters replacing any uppercase letters in s2, leaving the original String unchanged. If there are no characters in the original String to convert, toLowerCase returns the original String.
16 // test toLowerCase and toUpperCase
17 System.out.printf("s1.toUpperCase() = %s%n", s1.toUpperCase());
18 System.out.printf("s2.toLowerCase() = %s%n%n", s2.toLowerCase());
19
s1 = HELLO s2 = goodbye
Removing Whitespace at the Ends of a String
Line 21 uses the String method strip to get a new String with all whitespace characters at the original String’s beginning and/or end removed. The method returns a String without leading or trailing whitespace and leaves the original String unchanged. If there are no whitespace characters at the beginning and end, strip returns the original String. You can remove whitespace characters at only the String’s beginning or end using String methods stripLeading and stripTrailing, respectively.
20 // test strip method
21 System.out.printf("s3 after strip = \"%s\"%n%n", s3.strip());
22
s3 after strip = "spaces"
Converting a String to a char Array
Since Strings are immutable, you cannot modify their characters. If you need to manipulate and modify a String’s characters, you can use the String method toCharArray to create a new char array containing a copy of the characters (line 24), then manipulate the characters in the array. Lines 27–29 simply output each of the array’s characters separated from the next by a space.
23 // test toCharArray method
24 char[] charArray = s1.toCharArray();
25 System.out.print("s1 as a character array = ");
26
27 for (char character : charArray) {
28 System.out.printf("%c ", character);
29 }
30
31 System.out.println();
32 }
33 }
s1 as a character array = h e l l o
7.3.8 String Method valueOf
Every object in Java has a toString method that returns the object’s String representation. Unfortunately, this 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 it to a String object. Figure 7.9 demonstrates the String class valueOf methods.
1 // Fig. 7.9: StringValueOf.java
2 // String valueOf methods.
3
4 public class StringValueOf {
5 public static void main(String[] args) {
6 char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'};
7 boolean booleanValue = true;
8 char characterValue = 'Z';
9 int integerValue = 7;
10 long longValue = 10000000000L; // L suffix indicates long
11 float floatValue = 2.5f; // f indicates that 2.5 is a float
12 double doubleValue = 33.333; // no suffix, double is default
13 Object objectRef = "hello"; // assign String to an Object reference
14
15 System.out.printf(
16 "char array = %s%n", String.valueOf(charArray));
17 System.out.printf("part of char array = %s%n",
18 String.valueOf(charArray, 3, 3));
19 System.out.printf(
20 "boolean = %s%n", String.valueOf(booleanValue));
21 System.out.printf(
22 "char = %s%n", String.valueOf(characterValue));
23 System.out.printf("int = %s%n", String.valueOf(integerValue));
24 System.out.printf("long = %s%n", String.valueOf(longValue));
25 System.out.printf("float = %s%n", String.valueOf(floatValue));
26 System.out.printf(
27 "double = %s%n", String.valueOf(doubleValue));
28 System.out.printf("Object = %s%n", String.valueOf(objectRef));
29 }
30 }
char array = abcdef part of char array = def boolean = true char = Z int = 7 long = 10000000000 float = 2.5 double = 33.333 Object = hello
Fig. 7.9 | String valueOf methods.
Lines 10–11 use literal values 10000000000L and 2.5f as the initial values of the long variable longValue and the float variable floatValue, respectively. Recall that Java treats integer literals as type int and floating-point literals as type double. Appending the letter L to the literal 10000000000 and appending the letter f to the literal 2.5 tells the compiler to treat 10000000000 as a long and 2.5 as a float. You can denote a long value with an uppercase L or lowercase l, and can denote a float value with an uppercase F or lowercase f. Uppercase L is preferred for long values because lowercase l can be mistaken as a 1 (one).
Line 16 creates a new String object with a copy of the contents of charArray. Line 18 creates a new String object by copying a portion of charArray—the second argument specifies the starting index from which to copy characters, and the third argument specifies the number of characters to copy.
Lines 19–28 demonstrate seven other valueOf overloads that take arguments of type boolean, char, int, long, float, double and Object, respectively. Method valueOf with an Object argument simply returns the result of calling the argument’s toString method.
Generative AI
1 Most String.valueOf calls are not required because Java can convert every primitive-type value and every object to a String automatically. Prompt genAIs with Fig. 7.9’s code and ask them to remove as many of the String.valueOf calls as possible, while still using %s to output the values. Compare the generated code to Fig. 7.9.
