Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать
public static void main( String args[] )
{
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

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 += "!";

is performed as follows:

s = new StringBuffer().append( s ).append( "!" ).toString();

[Page 1370]

First, Java creates an empty StringBuffer, then appends to the StringBuffer the current contents of s followed by "!". Next, StringBuffer's method toString converts the StringBuffer to a string representation and the result is assigned to s.

[Page 1371]

29.4.5. StringBuffer Insertion and Deletion Methods

Class StringBuffer provides overloaded insert methods to allow values of various types to be inserted at any position in a StringBuffer. Versions are provided for each of the primitive types and for character arrays, Strings, Objects and CharSequences. Each of the methods takes its second argument, converts it to a string and inserts it immediately preceding the index specified by the first argument. The index specified by the first argument must be greater than or equal to 0 and less than

the length of the StringBufferotherwise, a StringIndexOutOfBoundsException occurs. Class

StringBuffer also provides methods delete and deleteCharAt for deleting characters at any position in a StringBuffer. Method delete takes two argumentsthe starting index and the index one past the end of the characters to delete. All characters beginning at the starting index up to but not including the ending index are deleted. Method deleteCharAt takes one argumentthe index of the character to delete. Invalid indices cause both methods to throw a String-IndexOutOfBoundsException. Methods insert, delete and deleteCharAt are demonstrated in Fig. 29.14.

Figure 29.14. StringBuffer methods insert and delete.

(This item is displayed on pages 1371 - 1372 in the print version)

1

//

Fig. 29.14: StringBufferInsert.java

 

2

//

StringBuffer methods insert, delete

and deleteCharAt.

3

 

 

 

4public class StringBufferInsert

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 = 'K';

13int integerValue = 7;

14long longValue = 10000000;

15

float floatValue =

2.

5f; //

f suffix indicates that 2.5 is a float

16

double doubleValue

=

33.333

;

17

 

 

 

 

18

StringBuffer buffer

=

new StringBuffer();

19

 

 

 

 

20buffer.insert( 0, objectRef );

21buffer.insert( 0, " " ); // each of these contains two spaces

22buffer.insert( 0, string );

23buffer.insert( 0, " " );

24buffer.insert( 0, charArray );

25buffer.insert( 0, " " );

26buffer.insert( 0, charArray, 3, 3 );

27buffer.insert( 0, " " );

28buffer.insert( 0, booleanValue );

29buffer.insert( 0, " " );

30buffer.insert( 0, characterValue );

31buffer.insert( 0, " " );

32buffer.insert( 0, integerValue );

33buffer.insert( 0, " " );

34buffer.insert( 0, longValue );

35buffer.insert( 0, " " );

36buffer.insert( 0, floatValue );

37buffer.insert( 0, " " );

38buffer.insert( 0, doubleValue );

39

40 System.out.printf(

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

 

 

 

 

 

 

[Page 1372]

29.5. Class Character

Recall from Chapter 17 that Java provides eight type-wrapper classesBoolean, Character, Double, Float, Byte, Short, Integer and Longthat enable primitive-type values to be treated as objects. In this section, we present class Characterthe type-wrapper class for primitive type char.

Most Character methods are static methods designed to be convenience methods for processing individual char values. These methods take at least a character argument and perform either a test or a manipulation of the character. Class Character also contains a constructor that receives a char argument to initialize a Character object. Most of the methods of class Character are presented in the next three examples. For more information on class Character (and all the type-wrapper classes), see the java.lang package in the Java API documentation.

[Page 1373]

Figure 29.15 demonstrates some static methods that test characters to determine whether they are a specific character type and the static methods that perform case conversions on characters. You can enter any character and apply the methods to the character.

Figure 29.15. Character class static methods for testing characters and converting character case.

(This item is displayed on pages 1373 - 1374 in the print version)

1

//

Fig. 29

.15: StaticCharMethods.java

2

//

Static

Character testing methods and case conversion methods.

3

import java.util.Scanner;

4

 

 

 

5public class StaticCharMethods

6{

7public static void main( String args[] )

8{

9Scanner scanner = new Scanner( System.in ); // create scanner

10System.out.println( "Enter a character and press Enter" );

11String input = scanner.next();

12char c = input.charAt( 0 ); // get input character

13

14// display character info

15System.out.printf( "is defined: %b\n", Character.isDefined( c ) );

16System.out.printf( "is digit: %b\n", Character.isDigit( c ) );

17System.out.printf( "is first character in a Java identifier: %b\n",

18Character.isJavaIdentifierStart( c ) );

19System.out.printf( "is part of a Java identifier: %b\n",

20Character.isJavaIdentifierPart( c ) );

21System.out.printf( "is letter: %b\n", Character.isLetter( c ) );

22System.out.printf(

23"is letter or digit: %b\n", Character.isLetterOrDigit( c ) );

24System.out.printf(

25"is lower case: %b\n", Character.isLowerCase( c ) );

26System.out.printf(

27"is upper case: %b\n", Character.isUpperCase( c ) );

28System.out.printf(

29"to upper case: %s\n", Character.toUpperCase( c ) );

30System.out.printf(

31"to lower case: %s\n", Character.toLowerCase( c ) );

32} // end main

33} // end class StaticCharMethods

Enter a character and press Enter

A

is defined: true is digit: false

is first character in a Java identifier: true is part of a Java identifier: true

is letter: true

is letter or digit: true is lower case: false

is upper case: true to upper case: A

to lower case: a

Enter a character and press Enter

8

 

is

defined: true

is

digit: true

is first character in a Java identifier: false is part of a Java identifier: true

is letter: false

is letter or digit: true is lower case: false

is upper case: false to upper case: 8

to lower case: 8

Enter a character and press Enter

$

 

is

defined: true

is

digit: false

is first character in a Java identifier: true is part of a Java identifier: true

is letter: false

is letter or digit: false is lower case: false

is upper case: false to upper case: $

to lower case: $

Line 15 uses Character method isDefined to determine whether character c is defined in the Unicode character set. If so, the method returns true, and otherwise, it returns false. Line 16 uses Character method isDigit to determine whether character c is a defined Unicode digit. If so, the method returns TRue, and otherwise, it returns false.

Line 18 uses Character method isJavaIdentifierStart to determine whether c is a character that can be the first character of an identifier in Javathat is, a letter, an underscore (_) or a dollar sign ($). If so, the method returns TRue, and otherwise, it returns false. Line 20 uses Character method isJavaIdentifierPart to determine whether character c is a character that can be used in an identifier in Javathat is, a digit, a letter, an underscore (_) or a dollar sign ($). If so, the method returns true, and otherwise, it returns false.

[Page 1374]