SlideShare a Scribd company logo
Programming in Java
Lecture 13: StringBuffer
Introduction
 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.
Introduction
 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()
Why StringBuffer?
 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 Constructors
 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.
Brain Storming
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity());
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());
StringBuffer Methods
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(“New Zealand");
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
ensureCapacity( )
 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.
Important
 When the length of StringBuffer becomes larger than the
capacity then memory reallocation is done:
 In case of StringBuffer, reallocation of memory is done using
the following rule:
 If the new_length <= 2*(original_capacity + 1), then
new_capacity = 2*(original_capacity + 1)
 Else, new_capacity = new_length.
setLength( )
 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.
charAt( ) and setCharAt( )
 The value of a single character can be obtained from a
StringBuffer via the charAt( ) method.
 We can set the value of a character within a StringBuffer using
setCharAt( ).
char charAt(int index)
void setCharAt(int index, char ch)
getChars( )
 getChars( ) method is used to copy a substring of a
StringBuffer into an array.
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.
 It has several overloaded versions.
◦ StringBuffer append(String str)
◦ StringBuffer append(int num)
◦ StringBuffer append(Object obj)
Example
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);
}
}
insert( )
 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)
Example
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
reverse( )
 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);
}
}
delete( ) and deleteCharAt( )
 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.
Example
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);
}
}
replace( )
 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.
Example
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);
}
}
substring( )
 Used to obtain a portion of a StringBuffer by calling 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.
L14 string handling(string buffer class)

More Related Content

PPS
String and string buffer
kamal kotecha
 
PPTX
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
PDF
Java threading
Chinh Ngo Nguyen
 
PPS
Wrapper class
kamal kotecha
 
PDF
Files in java
Muthukumaran Subramanian
 
PPTX
Python array
Arnab Chakraborty
 
PPSX
Collections - Lists, Sets
Hitesh-Java
 
PPT
sets and maps
Rajkattamuri
 
String and string buffer
kamal kotecha
 
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
Java threading
Chinh Ngo Nguyen
 
Wrapper class
kamal kotecha
 
Python array
Arnab Chakraborty
 
Collections - Lists, Sets
Hitesh-Java
 
sets and maps
Rajkattamuri
 

What's hot (20)

PPTX
Java 8 Lambda and Streams
Venkata Naga Ravi
 
PPTX
Java - Exception Handling
Prabhdeep Singh
 
PPTX
Java Strings
RaBiya Chaudhry
 
PPT
Java collection
Arati Gadgil
 
PPSX
Collections - Maps
Hitesh-Java
 
PPTX
Java 8 streams
Manav Prasad
 
PPTX
Java String
SATYAM SHRIVASTAV
 
PPTX
Interface in java
PhD Research Scholar
 
PPTX
Type casting in java
Farooq Baloch
 
PPTX
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
PDF
Collections In Java
Binoj T E
 
PPT
JavaScript Arrays
Reem Alattas
 
PPTX
C# classes objects
Dr.Neeraj Kumar Pandey
 
PDF
Methods in Java
Jussi Pohjolainen
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
PPTX
Exception Handling in object oriented programming using C++
Janki Shah
 
PPTX
Lecture09 recursion
Hariz Mustafa
 
PPT
Object Oriented Programming with Java
backdoor
 
PPTX
Java swing
Apurbo Datta
 
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Java - Exception Handling
Prabhdeep Singh
 
Java Strings
RaBiya Chaudhry
 
Java collection
Arati Gadgil
 
Collections - Maps
Hitesh-Java
 
Java 8 streams
Manav Prasad
 
Java String
SATYAM SHRIVASTAV
 
Interface in java
PhD Research Scholar
 
Type casting in java
Farooq Baloch
 
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
Collections In Java
Binoj T E
 
JavaScript Arrays
Reem Alattas
 
C# classes objects
Dr.Neeraj Kumar Pandey
 
Methods in Java
Jussi Pohjolainen
 
Classes, objects in JAVA
Abhilash Nair
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Exception Handling in object oriented programming using C++
Janki Shah
 
Lecture09 recursion
Hariz Mustafa
 
Object Oriented Programming with Java
backdoor
 
Java swing
Apurbo Datta
 
Ad

Similar to L14 string handling(string buffer class) (20)

PPTX
StringBuffer.pptx
meenakshi pareek
 
PPTX
String Handling, Inheritance, Packages and Interfaces
Prabu U
 
PDF
String handling(string buffer class)
Ravi Kant Sahu
 
PDF
String handling(string buffer class)
Ravi_Kant_Sahu
 
PPTX
Java string , string buffer and wrapper class
SimoniShah6
 
PPT
Strings
naslin prestilda
 
PPTX
package
sweetysweety8
 
PPTX
Strings in Java
Abhilash Nair
 
PPT
07slide
Aboudi Sabbah
 
PPTX
Computer programming 2 Lesson 12
MLG College of Learning, Inc
 
PPTX
L13 string handling(string class)
teach4uin
 
PPT
M C6java7
mbruggen
 
PPTX
In the given example only one object will be created. Firstly JVM will not fi...
Indu32
 
PPT
Java Strings methods and operations.ppt
JyothiAmpally
 
PPT
Strings
Imad Ali
 
PPT
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
PPTX
Java String Handling
Infoviaan Technologies
 
PPT
Chapter 7 String
OUM SAOKOSAL
 
PPTX
Java
JahnaviBhagat
 
PPTX
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
StringBuffer.pptx
meenakshi pareek
 
String Handling, Inheritance, Packages and Interfaces
Prabu U
 
String handling(string buffer class)
Ravi Kant Sahu
 
String handling(string buffer class)
Ravi_Kant_Sahu
 
Java string , string buffer and wrapper class
SimoniShah6
 
package
sweetysweety8
 
Strings in Java
Abhilash Nair
 
07slide
Aboudi Sabbah
 
Computer programming 2 Lesson 12
MLG College of Learning, Inc
 
L13 string handling(string class)
teach4uin
 
M C6java7
mbruggen
 
In the given example only one object will be created. Firstly JVM will not fi...
Indu32
 
Java Strings methods and operations.ppt
JyothiAmpally
 
Strings
Imad Ali
 
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
Java String Handling
Infoviaan Technologies
 
Chapter 7 String
OUM SAOKOSAL
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
Ad

More from teach4uin (20)

PPTX
Controls
teach4uin
 
PPT
validation
teach4uin
 
PPT
validation
teach4uin
 
PPT
Master pages
teach4uin
 
PPTX
.Net framework
teach4uin
 
PPT
Scripting languages
teach4uin
 
PPTX
Css1
teach4uin
 
PPTX
Code model
teach4uin
 
PPT
Asp db
teach4uin
 
PPTX
State management
teach4uin
 
PPT
security configuration
teach4uin
 
PPT
static dynamic html tags
teach4uin
 
PPT
static dynamic html tags
teach4uin
 
PPTX
New microsoft office power point presentation
teach4uin
 
PPT
.Net overview
teach4uin
 
PPT
Stdlib functions lesson
teach4uin
 
PPT
enums
teach4uin
 
PPT
memory
teach4uin
 
PPT
array
teach4uin
 
PPT
storage clas
teach4uin
 
Controls
teach4uin
 
validation
teach4uin
 
validation
teach4uin
 
Master pages
teach4uin
 
.Net framework
teach4uin
 
Scripting languages
teach4uin
 
Css1
teach4uin
 
Code model
teach4uin
 
Asp db
teach4uin
 
State management
teach4uin
 
security configuration
teach4uin
 
static dynamic html tags
teach4uin
 
static dynamic html tags
teach4uin
 
New microsoft office power point presentation
teach4uin
 
.Net overview
teach4uin
 
Stdlib functions lesson
teach4uin
 
enums
teach4uin
 
memory
teach4uin
 
array
teach4uin
 
storage clas
teach4uin
 

Recently uploaded (20)

PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Software Development Company | KodekX
KodekX
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
This slide provides an overview Technology
mineshkharadi333
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Architecture of the Future (09152021)
EdwardMeyman
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Software Development Company | KodekX
KodekX
 

L14 string handling(string buffer class)

  • 1. Programming in Java Lecture 13: StringBuffer
  • 2. Introduction  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. Introduction  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. Why StringBuffer?  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 Constructors  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. Brain Storming StringBuffer sb = new StringBuffer(); System.out.println(sb.capacity()); 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. StringBuffer Methods 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(“New Zealand"); System.out.println("length = " + sb.length()); System.out.println("capacity = " + sb.capacity()); } }
  • 8. ensureCapacity( )  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.
  • 9. Important  When the length of StringBuffer becomes larger than the capacity then memory reallocation is done:  In case of StringBuffer, reallocation of memory is done using the following rule:  If the new_length <= 2*(original_capacity + 1), then new_capacity = 2*(original_capacity + 1)  Else, new_capacity = new_length.
  • 10. setLength( )  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.
  • 11. charAt( ) and setCharAt( )  The value of a single character can be obtained from a StringBuffer via the charAt( ) method.  We can set the value of a character within a StringBuffer using setCharAt( ). char charAt(int index) void setCharAt(int index, char ch)
  • 12. getChars( )  getChars( ) method is used to copy a substring of a StringBuffer into an array. void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
  • 13. append( )  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. Example 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. insert( )  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. Example class insertDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); } }
  • 17. reverse( )  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. delete( ) and deleteCharAt( )  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. Example 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. replace( )  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. Example 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); } }
  • 22. substring( )  Used to obtain a portion of a StringBuffer by calling 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.