AhmadLang / Java, How To Program, 2004
.pdf
1// Fig. 29.9: StringValueOf.java
2// String valueOf methods.
3
4public class StringValueOf
5{
6
7
8
9boolean booleanValue = true;
10char characterValue = 'Z';
11int integerValue = 7;
12long longValue = 10000000000L; // L suffix indicates long
13 float floatValue = 2.5f; // f indicates that 2.5 is a float
14double doubleValue = 33.333; // no suffix, double is default
15Object objectRef = "hello"; // assign string to an Object reference
17System.out.printf(
18"char array = %s\n", String.valueOf( charArray ) );
19System.out.printf( "part of char array = %s\n",
20String.valueOf( charArray, 3, 3 ) );
21System.out.printf(
22"boolean = %s\n", String.valueOf( booleanValue ) );
23System.out.printf(
24"char = %s\n", String.valueOf( characterValue ) );
25 System.out.printf( "int = %s\n", String.valueOf( integerValue ) );
26System.out.printf( "long = %s\n", String.valueOf( longValue ) );
27System.out.printf( "float = %s\n", String.valueOf( floatValue ) );
28System.out.printf(
29"double = %s\n", String.valueOf( doubleValue ) );
30System.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.]
[Page 1364 (continued)]
29.4. Class StringBuffer
Once a String object is created, its contents can never change. We now discuss the features of class StringBuffer for creating and manipulating dynamic string informationthat is, modifiable strings. Every StringBuffer is capable of storing a number of characters specified by its capacity. If the capacity of a StringBuffer is exceeded, the capacity is automatically expanded to accommodate the additional characters. Class StringBuffer is also used to implement operators + and += for String concatenation.
[Page 1365]
Performance Tip 29.2
Java can perform certain optimizations involving String objects (such as sharing one String object among multiple references) because it knows these objects will not change. Strings (not StringBuffers) should be used if the data will not change.
Performance Tip 29.3
In programs that frequently perform string concatenation, or other string modifications, it is more efficient to implement the modifications with class StringBuffer (covered in Section 29.4.1 ).
[Page 1366]
29.4.1. StringBuffer Constructors
Class StringBuffer provides four constructors. Three of these constructors are demonstrated in Fig. 29.10. Line 8 uses the no-argument StringBuffer constructor to create a StringBuffer with no characters in it and an initial capacity of 16 characters (the default for a StringBuffer). Line 9 uses the StringBuffer constructor that takes an integer argument to create a StringBuffer with no characters in it and the initial capacity specified by the integer argument (i.e., 10). Line 10 uses the StringBuffer constructor that takes a String argument (in this case, a string literal) to create a StringBuffer containing the characters in the String argument. The initial capacity is the number of characters in the String argument plus 16.
Figure 29.10. StringBuffer class constructors.
1// Fig. 29.10: StringBufferConstructors.java
2// StringBuffer constructors.
3
4public class StringBufferConstructors
5{
6public static void main( String args[] )
7{
8StringBuffer buffer1 = new StringBuffer();
9StringBuffer buffer2 = new StringBuffer( 10 );
10StringBuffer buffer3 = new StringBuffer( "hello" );
12System.out.printf( "buffer1 = \"%s\"\n", buffer1.toString() );
13System.out.printf( "buffer2 = \"%s\"\n", buffer2.toString() );
14System.out.printf( "buffer3 = \"%s\"\n", buffer3.toString() );
15} // end main
16} // end class StringBufferConstructors
buffer1 |
= |
"" |
buffer2 |
= |
"" |
buffer3 |
= |
"hello" |
|
|
|
The statements on lines 1214 uses StringBuffer method toString to output the StringBuffer with the printf method. In Section 29.4.4, we discuss how Java uses StringBuffer objects to implement the + and += operators for string concatenation.
29.4.2. StringBuffer Methods length, capacity, setLength and ensureCapacity
Class StringBuffer provides methods length and capacity to return the number of characters currently in a StringBuffer and the number of characters that can be stored in a StringBuffer without allocating more memory, respectively. Method ensureCapacity guarantees that a StringBuffer has at least the specified capacity. Method setLength increases or decreases the length of a StringBuffer. The application in Fig. 29.11 demonstrates these methods.
Figure 29.11. StringBuffer methods length and capacity.
(This item is displayed on page 1367 in the print version)
1 |
// |
Fig. 29.11: StringBufferCapLen.java |
2 |
// |
StringBuffer length, setLength, capacity and ensureCapacity methods. |
3 |
|
|
4public class StringBufferCapLen
5{
6 |
public static void main( |
String args[] ) |
7 |
{ |
|
8 |
StringBuffer buffer = |
new StringBuffer( "Hello, how are you?" ); |
9 |
|
|
10System.out.printf( "buffer = %s\nlength = %d\ncapacity = %d\n\n",
11buffer.toString(), buffer.length(), buffer.capacity() );
12
13buffer.ensureCapacity( 75 );
14System.out.printf( "New capacity = %d\n\n", buffer.capacity() );
16buffer.setLength( 10 );
17System.out.printf( "New length = %d\nbuf = %s\n",
18buffer.length(), buffer.toString() );
19} // end main
20} // end class StringBufferCapLen
buffer = Hello, how are you? length = 19
capacity = 35
New capacity = 75
New length = 10 buf = Hello, how
The application contains one StringBuffer called buffer. Line 8 uses the StringBuffer constructor that takes a String argument to initialize the StringBuffer with "Hello, how are you?". Lines 1011 print the contents, length and capacity of the StringBuffer. Note in the output window that the capacity of the StringBuffer is initially 35. Recall that the StringBuffer constructor that takes a String argument initializes the capacity to the length of the string passed as an argument plus 16.
[Page 1367]
Line 13 uses method ensureCapacity to expand the capacity of the StringBuffer to a minimum of 75 characters. Actually, if the original capacity is less than the argument, the method ensures a capacity that is the greater of the number specified as an argument and twice the original capacity plus 2. The StringBuffer's current capacity remains unchanged if it is more than the specified capacity.
Performance Tip 29.4
Dynamically increasing the capacity of a StringBuffer can take a relatively long time. Executing a large number of these operations can degrade the performance of an application. If a StringBuffer is going to increase greatly in size, possibly multiple times, setting its capacity high at the beginning will increase performance.
Line 16 uses method setLength to set the length of the StringBuffer to 10. If the specified length is less than the current number of characters in the StringBuffer, the buffer is truncated to the specified length (i.e., the characters in the StringBuffer after the specified length are discarded). If the specified length is greater than the number of characters currently in the StringBuffer, null characters (characters with the numeric representation 0) are appended to the StringBuffer until the total number of characters in the StringBuffer is equal to the specified length. See Section 14.7.1 for more details.
[Page 1368]
29.4.3. StringBuffer Methods charAt, setCharAt, getChars and reverse
Class StringBuffer provides methods charAt, setCharAt, getChars and reverse to manipulate the characters in a StringBuffer. Each of these methods is demonstrated in Fig. 29.12.
Figure 29.12. StringBuffer class character-manipulation methods.
1 |
// |
Fig. 29.12: StringBufferChars.java |
2 |
// |
StringBuffer methods charAt, setCharAt, getChars and reverse. |
3 |
|
|
4public class StringBufferChars
5{
6 |
public static void main( |
String args[] ) |
7 |
{ |
|
8 |
StringBuffer buffer = |
new StringBuffer( "hello there" ); |
9 |
|
|
10System.out.printf( "buffer = %s\n", buffer.toString() );
11System.out.printf( "Character at 0: %s\nCharacter at 4: %s\n\n",
12buffer.charAt( 0 ), buffer.charAt( 4 ) );
13
14char charArray[] = new char[ buffer.length() ];
15buffer.getChars( 0, buffer.length(), charArray, 0 );
16System.out.print( "The characters are: " );
17
18for ( char character : charArray )
19System.out.print( character );
21buffer.setCharAt( 0, 'H' );
22buffer.setCharAt( 6, 'T' );
23System.out.printf( "\n\nbuf = %s", buffer.toString() );
25buffer.reverse();
26System.out.printf( "\n\nbuf = %s\n", buffer.toString() );
27} // end main
28} // end class StringBufferChars
buffer = hello there Character at 0: h Character at 4: o
The characters are: hello there
buf = Hello There
buf = erehT olleH
[Page 1369]
Method charAt (line 12) takes an integer argument and returns the character in the StringBuffer at that index. Method getChars (line 15) copies characters from a StringBuffer into the character array passed as an argument. This method takes four argumentsthe starting index from which characters should be copied in the StringBuffer, the index one past the last character to be copied from the StringBuffer, the character array into which the characters are to be copied and the starting location in the character array where the first character should be placed. Method setCharAt (lines 21 and 22) takes an integer and a character argument and sets the character at the specified position in the StringBuffer to the character argument. Method reverse (line 25) reverses the contents of the
StringBuffer.
Common Programming Error 29.3
Attempting to access a character that is outside the bounds of a StringBuffer (i.e., with an index less than 0 or greater than or equal to the StringBuffer's length) results in a
StringIndexOutOfBoundsException.
29.4.4. StringBuffer append Methods
Class StringBuffer provides overloaded append methods to allow values of various types to be appended to the end of a StringBuffer. Versions are provided for each of the primitive types and for character arrays, Strings, Objects, StringBuffers and CharSequences. (Remember that method toString produces a string representation of any Object.) Each of the methods takes its argument, converts it to a string and appends it to the StringBuffer. The append methods are demonstrated in Fig. 29.13.
Figure 29.13. StringBuffer class append methods.
(This item is displayed on pages 1370 - 1371 in the print version)
1// Fig. 29.13: StringBufferAppend.java
2// StringBuffer append methods.
3
4public class StringBufferAppend
5{
6 public static void main( String args[] )
7{
8Object objectRef = "hello";
9String string = "goodbye";
10 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
11boolean booleanValue = true;
12char characterValue = 'Z';
13int integerValue = 7;
14long longValue = 10000000000L;
15 |
float floatValue = |
2.5f; |
// |
f suffix indicates 2.5 is a float |
16 |
double doubleValue |
= 33. |
333 |
; |
17
18StringBuffer lastBuffer = new StringBuffer( "last StringBuffer" );
19StringBuffer buffer = new StringBuffer();
20
21buffer.append( objectRef );
22buffer.append( "\n" ); // each of these contains new line
23buffer.append( string );
24buffer.append( "\n" );
25buffer.append( charArray );
26buffer.append( "\n" );
27buffer.append( charArray, 0, 3 );
28buffer.append( "\n" );
29buffer.append( booleanValue );
30buffer.append( "\n" );
31buffer.append( characterValue );
32buffer.append( "\n" );
33buffer.append( integerValue );
34buffer.append( "\n" );
35buffer.append( longValue );
36buffer.append( "\n" );
37buffer.append( floatValue );
38buffer.append( "\n" );
39buffer.append( doubleValue );
40buffer.append( "\n" );
41buffer.append( lastBuffer
42
43System.out.printf( "buffer contains %s\n", buffer.toString() );
44} // end main
45} // end StringBufferAppend
buffer contains hello goodbye
abcdef abc true
Z 7
10000000000
2.5
33.333
last StringBuffer
Actually, StringBuffers and the append methods are used by the compiler to implement the + and += operators for String concatenation. For example, assuming the declarations
String string1 = "hello"; String string2 = "BC"; int value = 22;
the statement
String s = string1 + string2 + value;
concatenates "hello", "BC" and 22. The concatenation is performed as follows:
new StringBuffer().append( "hello" ).append( "BC" ).append( 22 ).toString();
First, Java creates an empty StringBuffer, then appends to the StringBuffer the string "hello", the string "BC" and the integer 22. Next, StringBuffer's method toString converts the StringBuffer to a String object to be assigned to String s. The statement
s += "!";
41 |
"buffer after inserts:\n%s\n\n", buffer.toString() ); |
42 |
|
43buffer.deleteCharAt( 10 ); // delete 5 in 2.5
44buffer.delete( 2, 6 ); // delete .333 in 33.333
46System.out.printf(
47"buffer after deletes:\n%s\n", buffer.toString() );
48} // end main
49} // end class StringBufferInsert
buffer |
after |
inserts: |
|
|
|
33.333 |
2.5 |
10000000 |
7 K |
true |
def abcdef goodbye hello |
buffer |
after |
deletes: |
|
|
|
33 2. |
10000000 7 K |
true |
def |
abcdef goodbye hello |
|
|
|
|
|
|
|

Enter a character and press Enter