0% found this document useful (0 votes)
13 views

String Buffer

Uploaded by

s.hemaswathi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

String Buffer

Uploaded by

s.hemaswathi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

StringBuffer

StringBuffer (Mutable)
• StringBuffer is a peer class of String that provides
much of the functionality of strings.
• As you know, String represents fixed-length,
immutable character sequences. In contrast,
• StringBuffer represents growable and writable
character sequences.(MUTABLE)
• 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.
StringBuffer Constructors
StringBuffer defines these four constructors:
1.StringBuffer( ) - 16 characters
StringBuffer s = new StringBuffer( ) ;
2.StringBuffer(int size) – externally defined size
StringBuffer s = new StringBuffer(10 ) ;
3.StringBuffer(String str) – initial content + 16 chars
StringBuffer s = new StringBuffer( “Welcome”) ;
4.StringBuffer(CharSequence chars) - initial content
+ 16 chars
CharSequence cs= “Hi GOAT”
StringBuffer s = new StringBuffer(cs) ;
length( ) and capacity( )
• int length( )- The current length of a StringBuffer can be
found via the length( ) method,
• int capacity( ) - while the total allocated capacity can be
found through the capacity( ) method
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
Output:
buffer = Hello
length = 5
capacity = 21
ensureCapacity( )
• If you want to preallocate room for a certain
number of characters after a StringBuffer has
been constructed, you can use ensureCapacity( )
to set the size of the buffer.
• This is useful if you know in advance that you will
be appending a large number of small strings to
a StringBuffer
• void ensureCapacity(int minCapacity)
• By setting the capacity in advance, you can
reduce the number of times the StringBuffer
needs to allocate more memory, which can
improve performance.
public class EnsureCapacityExample {
public static void main(String[] args) {
// Create a StringBuffer with initial content
StringBuffer sb = new StringBuffer("Hello");
// Print initial capacity
System.out.println("Initial capacity: " + sb.capacity());
// Ensure the capacity is at least 50
sb.ensureCapacity(50);
// Print capacity after ensuring
System.out.println("Capacity after ensuring: " + sb.capacity());
// Append a large number of small strings
for (int i = 0; i < 10; i++) {
sb.append(" World");
}
// Print the final content and capacity
System.out.println("Final content: " + sb);
System.out.println("Final capacity: " + sb.capacity());}}
Output:
Initial capacity: 21
Capacity after ensuring:
50
Final content: Hello World World World
World World World World World World
World
Final capacity: 65
setLength( )

• The setLength(int newLength) method in


the StringBuffer class sets the length of
the character sequence contained in the
buffer.
• If the new length is greater than the
current length, the buffer is padded with
null characters (\u0000).
• If the new length is less than the current
length, the buffer is truncated to the
specified length.
public class SetLengthExample {
public static void main(String[] args) {
// Create a StringBuffer with initial content
StringBuffer sb = new StringBuffer("Hello, World!");
// Print the initial content and length
System.out.println("Initial content: " + sb);
System.out.println("Initial length: " + sb.length());
// Set the length to a larger value (15)
sb.setLength(15);
// Print the content and length after setting a larger length
System.out.println("Content after setting larger length: " + sb);
System.out.println("Length after setting larger length: " + sb.length());
// Set the length to a smaller value (4)
sb.setLength(5);
// Print the content and length after setting a smaller length
System.out.println("Content after setting smaller length: " + sb);
System.out.println("Length after setting smaller length: " + sb.length());
}
}
charAt( ) and setCharAt( )
char charAt(int where)
void setCharAt(int where, char ch)
class setCharAtDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
Output:
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
getChars( )
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
public class GetCharsExample {
public static void main(String[] args) {
// Create a StringBuffer with initial content
StringBuffer sb = new StringBuffer("Hello, World!");
// Create a target character array with sufficient size
char[] target = new char[20];
// Specify the range of characters to copy and the start position in the target array
int sourceStart = 6; // Starting index in the source (inclusive)
int sourceEnd = 11; // Ending index in the source (exclusive)
int targetStart = 4; // Starting index in the target array

// Use getChars to copy characters from the StringBuffer to the target array
sb.getChars(sourceStart, sourceEnd, target, targetStart);

// Print the content of the target array


System.out.print("Target array content: ");
for (char c : target) {
System.out.print(c == '\u0000' ? '_' : c); }
}
}

Output:
Target array content: 0000World000000000000
append( )
• append( ) method concatenates the string representation of any
other type of data to the end of the invoking StringBuffer object.
• It has several overloaded versions.

• StringBuffer append(String str)


• StringBuffer append(int num)
• StringBuffer append(Object obj)
append( )
class appendDemo
{
public static void main(String args[]) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
Output
a = 42!
insert( )

• The insert( ) method inserts one string into


another.
• It is overloaded to accept values of all the
primitive types, plus Strings, Objects, and
CharSequences
• StringBuffer insert(int index, String str)
• StringBuffer insert(int index, char ch)
• StringBuffer insert(int index, Object obj)
Insert()
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
Output:
I like Java!
reverse( )
• Reverse the characters within a StringBuffer object using reverse()
StringBuffer reverse( )
class ReverseDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Output:
abcdef
fedcba
delete( ) and deleteCharAt( )
• StringBuffer delete(int startIndex, int endIndex)
• StringBuffer deleteCharAt(int loc)
Program:
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}

Output:
After delete: This a test.
After deleteCharAt: his a test.
replace( )

StringBuffer replace(int startIndex, int endIndex, String str)


Program:
class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
Output:
After replace: This was a test.
substring( )
String substring(int startIndex)
String substring(int startIndex,int endIndex)
• The first form returns the substring that starts
at startIndex and runs to the end of the
invoking StringBuffer object.
• The second form returns the substring that
starts at startIndex and runs through
endIndex–1
StringBuilder Vs StringBuffer
Feature StringBuilder StringBuffer
Introduced in JDK 5 JDK 1.0
Not synchronized (not
Synchronization Synchronized (thread-safe)
thread-safe)
Faster due to lack of Slower due to
Performance
synchronization synchronization overhead
Single-threaded Multi-threaded
Use Case
environments environments
Mutable (can change Mutable (can change
Mutability
contents) contents)
All methods are identical to All methods are identical to
Methods
StringBuffer StringBuilder
More efficient for single- Less efficient due to
Efficiency
threaded operations synchronization
public class CompareToExample {
public static void main(String[] args) {
// Create some sample strings
String str1 = "apple";
String str2 = "banana";
String str3 = "apple";
String str4 = "Apple";
// Compare str1 with str2
int result1 = str1.compareTo(str2);
System.out.println("Comparing \"" + str1 + "\" with \"" + str2 + "\": " + result1);
// Compare str1 with str3
int result2 = str1.compareTo(str3);
System.out.println("Comparing \"" + str1 + "\" with \"" + str3 + "\": " + result2);
// Compare str1 with str4
int result3 = str1.compareTo(str4);
System.out.println("Comparing \"" + str1 + "\" with \"" + str4 + "\": " + result3);
// Compare str2 with str4
int result4 = str2.compareTo(str4);
System.out.println("Comparing \"" + str2 + "\" with \"" + str4 + "\": " + result4);
}
}

Output:
Comparing "apple" with "banana": -1
Comparing "apple" with "apple": 0
Comparing "apple" with "Apple": 32
Comparing "banana" with "Apple": 31
String Comparison
Bubble Sort
class SortString
{
static String arr[] = { "Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid",
"of", "their", "country“ };
public static void main(String args[])
{
for(int j = 0; j < arr.length; j++)
{
for(int i = j + 1; i < arr.length; i++)
{
if(arr[i].compareTo(arr[j]) < 0)
{
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
for (int j = 0; j < arr.length; j++)
{
System.out.println(arr[j]);
}
}
}
}
The output of this program is the list of words:
Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to

You might also like