SlideShare a Scribd company logo
1 of 23
StringBuffer Class
A string buffer implements a mutable sequence of characters.
A string buffer is like a String, but can be modified.
At any point in time it contains some particular sequence of
characters, but the length and content of the sequence can be
changed through certain method calls.
Every string buffer has a capacity.
When the length of the character sequence contained in the
string buffer exceed the capacity, it is automatically made
larger.
String buffers are used by the compiler to implement the
binary string concatenation operator +.
For example:
x = "a" + 4 + "c"
is compiled to the equivalent of:
x = new StringBuffer().append("a").append(4).
append("c") .toString()
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.
StringBuffer defines these four constructors:
◦ StringBuffer( )
◦ StringBuffer(int size)
◦ StringBuffer(String str)
◦ StringBuffer(CharSequence chars)
The default constructor reserves room for 16 characters without
reallocation.
By allocating room for a few extra characters(size +16),
StringBuffer reduces the number of reallocations that take place.
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); //default capacity -16
StringBuffer sb = new StringBuffer(65);
System.out.println(sb.capacity());
StringBuffer sb = new StringBuffer(“A”);
System.out.println(sb.capacity());
StringBuffer sb = new StringBuffer('A');
System.out.println(sb.capacity());
length( ) and capacity( )
The current length of a StringBuffer can be found via the length( ) method,
while the total allocated capacity can be found through the capacity( )
method.
int length( )
int capacity( )
Example:
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer(“Hello");
System.out.println("length = " + sb.length()); ---5
System.out.println("capacity = " + sb.capacity());--16
}
}
StringBuffer sb1=new StringBuffer();
System.out.println(sb1.capacity());
System.out.println(sb1.length());
StringBuffer sb1=new StringBuffer(“BANASTHALI”);
System.out.println(sb1.capacity());
System.out.println(sb1.length());
If we want to preallocate room for a certain number of
characters after a StringBuffer has been constructed, we can
use ensureCapacity( ) to set the size of the buffer.
This is useful if we know in advance that we will be
appending a large number of small strings to a
StringBuffer.
void ensureCapacity(int capacity)
Here, capacity specifies the size of the buffer.
used to set the length of the buffer within a StringBuffer object.
void setLength(int length)
Here, length specifies the length of the buffer.
When we increase the size of the buffer, null characters are added to
the end of the existing buffer.
If we call setLength( ) with a value less than the current value returned by length( ),
then the characters stored beyond the new length will be lost.
StringBuffer sb1=new StringBuffer(“java”);
sb1.setLength(2)
System.out.println(sb1);----Ja
sb1.setLength(10)
System.out.println(sb1);----Ja--------
The 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)
StringBuffer sb1=new StringBuffer();
sb1.append(“hello”);
System.out.println(sb1.capacity());
Sytem.out.println(sb1.length());
sb1.append(“Ajmer”);
System.out.println(sb1.capacity());
System.out.println(sb1.length());
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);
}
}
The insert( ) method inserts one string into another.
It is overloaded to accept values of all the simple types, plus
Strings, Objects, and CharSequences.
This string is then inserted into the invoking StringBuffer
object.
◦ StringBuffer insert(int index, String str)
◦ StringBuffer insert(int index, char ch)
◦ StringBuffer insert(int index, Object obj)
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I
Java!"); sb.insert(2, "like ");
System.out.println(sb);
}
}
Used to reverse the characters within a StringBuffer object.
This method returns the reversed object on which it was called.
StringBuffer reverse()
Example:
class ReverseDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer(“Banana");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Used to delete characters within a StringBuffer.
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int index)
The delete( ) method deletes a sequence of characters from the
invoking object (from startIndex to endIndex-1).
The deleteCharAt( ) method deletes the character at the
specified index.
It returns the resulting StringBuffer object.
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer(“She is not a good girl.”);
sb.delete(7, 11);
System.out.println("After delete: " + sb);
sb.deleteCharAt(7);
System.out.println("After deleteCharAt: " + sb);
}
}
Used to replace one set of characters with another set inside a
StringBuffer object.
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.
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);
}
}
StringBuffer sb1=new StringBuffer();
sb1.append(“hello”);
Sytem.out.println(2, ‘s’);
Sytem.out.println(sb1);
StringBuffer Class Guide

More Related Content

Similar to StringBuffer Class Guide

Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdflearnEnglish51
 
Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Danial Virk
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string classfedcoordinator
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...Indu32
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)Tak Lee
 

Similar to StringBuffer Class Guide (20)

07slide
07slide07slide
07slide
 
Strings
StringsStrings
Strings
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
 
Java
JavaJava
Java
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)
 
M C6java7
M C6java7M C6java7
M C6java7
 
Strings
StringsStrings
Strings
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
LectureNotes-04-DSA
LectureNotes-04-DSALectureNotes-04-DSA
LectureNotes-04-DSA
 
Day_5.1.pptx
Day_5.1.pptxDay_5.1.pptx
Day_5.1.pptx
 
Strings in java
Strings in javaStrings in java
Strings in java
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
 
Learn Java Part 7
Learn Java Part 7Learn Java Part 7
Learn Java Part 7
 

Recently uploaded

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

StringBuffer Class Guide

  • 2. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. Every string buffer has a capacity. When the length of the character sequence contained in the string buffer exceed the capacity, it is automatically made larger.
  • 3. String buffers are used by the compiler to implement the binary string concatenation operator +. For example: x = "a" + 4 + "c" is compiled to the equivalent of: x = new StringBuffer().append("a").append(4). append("c") .toString()
  • 4. 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.
  • 5. StringBuffer defines these four constructors: ◦ StringBuffer( ) ◦ StringBuffer(int size) ◦ StringBuffer(String str) ◦ StringBuffer(CharSequence chars) The default constructor reserves room for 16 characters without reallocation. By allocating room for a few extra characters(size +16), StringBuffer reduces the number of reallocations that take place.
  • 6. StringBuffer sb = new StringBuffer(); System.out.println(sb.capacity()); //default capacity -16 StringBuffer sb = new StringBuffer(65); System.out.println(sb.capacity()); StringBuffer sb = new StringBuffer(“A”); System.out.println(sb.capacity()); StringBuffer sb = new StringBuffer('A'); System.out.println(sb.capacity());
  • 7. length( ) and capacity( ) The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. int length( ) int capacity( ) Example: class StringBufferDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer(“Hello"); System.out.println("length = " + sb.length()); ---5 System.out.println("capacity = " + sb.capacity());--16 } }
  • 8. StringBuffer sb1=new StringBuffer(); System.out.println(sb1.capacity()); System.out.println(sb1.length()); StringBuffer sb1=new StringBuffer(“BANASTHALI”); System.out.println(sb1.capacity()); System.out.println(sb1.length());
  • 9. If we want to preallocate room for a certain number of characters after a StringBuffer has been constructed, we can use ensureCapacity( ) to set the size of the buffer. This is useful if we know in advance that we will be appending a large number of small strings to a StringBuffer. void ensureCapacity(int capacity) Here, capacity specifies the size of the buffer.
  • 10. used to set the length of the buffer within a StringBuffer object. void setLength(int length) Here, length specifies the length of the buffer. When we increase the size of the buffer, null characters are added to the end of the existing buffer. If we call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost.
  • 12. The 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)
  • 14. 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); } }
  • 15. The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings, Objects, and CharSequences. This string is then inserted into the invoking StringBuffer object. ◦ StringBuffer insert(int index, String str) ◦ StringBuffer insert(int index, char ch) ◦ StringBuffer insert(int index, Object obj)
  • 16. class insertDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); } }
  • 17. Used to reverse the characters within a StringBuffer object. This method returns the reversed object on which it was called. StringBuffer reverse() Example: class ReverseDemo { public static void main(String args[]) { StringBuffer s = new StringBuffer(“Banana"); System.out.println(s); s.reverse(); System.out.println(s); } }
  • 18. Used to delete characters within a StringBuffer. StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int index) The delete( ) method deletes a sequence of characters from the invoking object (from startIndex to endIndex-1). The deleteCharAt( ) method deletes the character at the specified index. It returns the resulting StringBuffer object.
  • 19. class deleteDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer(“She is not a good girl.”); sb.delete(7, 11); System.out.println("After delete: " + sb); sb.deleteCharAt(7); System.out.println("After deleteCharAt: " + sb); } }
  • 20. Used to replace one set of characters with another set inside a StringBuffer object. 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.
  • 21. 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); } }