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

What's hot

String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
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
 
Java string handling
Java string handlingJava string handling
Java string handling
Salman Khan
 
Java strings
Java   stringsJava   strings
Java strings
Mohammed Sikander
 
String in java
String in javaString in java
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
Java String
Java StringJava String
Java String
Java2Blog
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
SimoniShah6
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
Ravi Kant Sahu
 
String java
String javaString java
String java
774474
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
Infoviaan Technologies
 
Cs1123 9 strings
Cs1123 9 stringsCs1123 9 strings
Cs1123 9 strings
TAlha MAlik
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
Ravi Kant Sahu
 
07slide
07slide07slide
07slide
Aboudi Sabbah
 
String in programming language in c or c++
 String in programming language  in c or c++  String in programming language  in c or c++
String in programming language in c or c++
Samsil Arefin
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
Fahim Adil
 

What's hot (20)

String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Java strings
Java   stringsJava   strings
Java strings
 
String in java
String in javaString in java
String in java
 
Java String
Java String Java String
Java String
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Java String
Java StringJava String
Java String
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
String java
String javaString java
String java
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Cs1123 9 strings
Cs1123 9 stringsCs1123 9 strings
Cs1123 9 strings
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
07slide
07slide07slide
07slide
 
String in programming language in c or c++
 String in programming language  in c or c++  String in programming language  in c or c++
String in programming language in c or c++
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
 

Similar to L14 string handling(string buffer class)

StringBuffer.pptx
StringBuffer.pptxStringBuffer.pptx
StringBuffer.pptx
meenakshi pareek
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
Prabu U
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
Ravi_Kant_Sahu
 
package
packagepackage
package
sweetysweety8
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
MLG College of Learning, Inc
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
M C6java7
M C6java7M C6java7
M C6java7
mbruggen
 
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
 
Strings
StringsStrings
Strings
Imad Ali
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
Java
JavaJava
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf3.7_StringBuilder.pdf
3.7_StringBuilder.pdf
Ananthi68
 
Java string handling
Java string handlingJava string handling
Java string handling
GaneshKumarKanthiah
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
fedcoordinator
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
learnEnglish51
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
Vikram Nandini
 
String.ppt
String.pptString.ppt
String.ppt
ajeela mushtaq
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
Intro C# Book
 
String notes
String notesString notes
String notes
Prasadu Peddi
 

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

StringBuffer.pptx
StringBuffer.pptxStringBuffer.pptx
StringBuffer.pptx
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
package
packagepackage
package
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
M C6java7
M C6java7M C6java7
M C6java7
 
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...
 
Strings
StringsStrings
Strings
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
 
Java
JavaJava
Java
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf3.7_StringBuilder.pdf
3.7_StringBuilder.pdf
 
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
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
String.ppt
String.pptString.ppt
String.ppt
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
String notes
String notesString notes
String notes
 

More from teach4uin

Controls
ControlsControls
Controls
teach4uin
 
validation
validationvalidation
validation
teach4uin
 
validation
validationvalidation
validation
teach4uin
 
Master pages
Master pagesMaster pages
Master pages
teach4uin
 
.Net framework
.Net framework.Net framework
.Net framework
teach4uin
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
teach4uin
 
Css1
Css1Css1
Css1
teach4uin
 
Code model
Code modelCode model
Code model
teach4uin
 
Asp db
Asp dbAsp db
Asp db
teach4uin
 
State management
State managementState management
State management
teach4uin
 
security configuration
security configurationsecurity configuration
security configuration
teach4uin
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
teach4uin
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
teach4uin
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
teach4uin
 
.Net overview
.Net overview.Net overview
.Net overview
teach4uin
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
teach4uin
 
enums
enumsenums
enums
teach4uin
 
memory
memorymemory
memory
teach4uin
 
array
arrayarray
array
teach4uin
 
storage clas
storage classtorage clas
storage clas
teach4uin
 

More from teach4uin (20)

Controls
ControlsControls
Controls
 
validation
validationvalidation
validation
 
validation
validationvalidation
validation
 
Master pages
Master pagesMaster pages
Master pages
 
.Net framework
.Net framework.Net framework
.Net framework
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
 
Css1
Css1Css1
Css1
 
Code model
Code modelCode model
Code model
 
Asp db
Asp dbAsp db
Asp db
 
State management
State managementState management
State management
 
security configuration
security configurationsecurity configuration
security configuration
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
 
.Net overview
.Net overview.Net overview
.Net overview
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
enums
enumsenums
enums
 
memory
memorymemory
memory
 
array
arrayarray
array
 
storage clas
storage classtorage clas
storage clas
 

Recently uploaded

Redefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI CapabilitiesRedefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI Capabilities
Priyanka Aash
 
Accelerating Migrations = Recommendations
Accelerating Migrations = RecommendationsAccelerating Migrations = Recommendations
Accelerating Migrations = Recommendations
isBullShit
 
Intel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdfIntel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdf
Tech Guru
 
UX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business GoalsUX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business Goals
FIDO Alliance
 
Finetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and DefendingFinetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and Defending
Priyanka Aash
 
Integrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecaseIntegrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecase
shyamraj55
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
ldtexsolbl
 
It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...
Zilliz
 
Camunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptxCamunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptx
ZachWylie3
 
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
FIDO Alliance
 
Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3
DianaGray10
 
The History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal EmbeddingsThe History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal Embeddings
Zilliz
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
SAI KAILASH R
 
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptxMAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
janagijoythi
 
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
alexjohnson7307
 
The Path to General-Purpose Robots - Coatue
The Path to General-Purpose Robots - CoatueThe Path to General-Purpose Robots - Coatue
The Path to General-Purpose Robots - Coatue
Razin Mustafiz
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
bellared2
 
Acumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptxAcumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptx
BrainSell Technologies
 
Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10
ankush9927
 

Recently uploaded (20)

Redefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI CapabilitiesRedefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI Capabilities
 
Accelerating Migrations = Recommendations
Accelerating Migrations = RecommendationsAccelerating Migrations = Recommendations
Accelerating Migrations = Recommendations
 
Intel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdfIntel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdf
 
UX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business GoalsUX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business Goals
 
Finetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and DefendingFinetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and Defending
 
Integrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecaseIntegrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecase
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
 
It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...
 
Camunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptxCamunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptx
 
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
 
Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3
 
The History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal EmbeddingsThe History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal Embeddings
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
 
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptxMAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
MAKE MONEY ONLINE Unlock Your Income Potential Today.pptx
 
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
 
The Path to General-Purpose Robots - Coatue
The Path to General-Purpose Robots - CoatueThe Path to General-Purpose Robots - Coatue
The Path to General-Purpose Robots - Coatue
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
 
Acumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptxAcumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptx
 
Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10
 

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.