56 Tanay JAVA Exp8
56 Tanay JAVA Exp8
8
String Operations And Vector Class
Theory:
StringBuffer is a peer class of String that provides much of the functionality of strings. String
represents fixed-length, immutable character sequences. In contrast, StringBuffer represents
growable and writeable character sequences. StringBuffer may have characters and substrings
inserted in the middle or appended to the end. StringBuffer will automatically grow to make
room for such additions and often has more characters preallocated than are actually needed, to
allow room for growth. Java uses both classes heavily, but many programmers deal only with
String and let Java manipulate StringBuffers behind the scenes by using the overloaded +
operator.
getChars( )
To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has
this general form:
void getChars(int sourceStart, int sourceEnd, char target[
], int targetStart)
append( )
The append( ) method concatenates the string representation of any other type of
data to the end of the invoking StringBuffer object.
Here, index specifies the index at which point the string will be inserted into the invoking
StringBuffer object.
reverse( )
You can reverse the characters within a StringBuffer object using reverse( ), shown here:
StringBuffer reverse( )
Java 2 added to StringBuffer the ability to delete characters using the methods delete( ) and
deleteCharAt( ). These methods are shown here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex
specifies the index of the first character to remove, and endIndex specifies an index one past the
last character to remove. Thus, the substring deleted runs from startIndex to endIndex–1. The
resulting StringBuffer object is returned.
replace( )
It replaces one set of characters with another set inside a StringBuffer object. Its signature is
shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the
substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str.
The resulting StringBuffer object is returned.
PROGRAM/CODE: a
OUTPUT a
Program Code : b
import java.util.*;
class VectorDemo
{
public static void main(String args[ ])
{
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() +" ");
System.out.println();
while(vEnum1.hasMoreElements())
System.out.print(vEnum1.nextElement() +" ");
System.out.println();
}
}
OUTPUT b