String Buffer class in Java is a JDK 5.0 Specification that is used to create mutable strings. It is available in java.util package. It can also have methods provided in this class which directly manipulate the data inside the object.
Creating String Buffer Object:
There are two ways to create string buffer object
1. We can create string buffer object using new operator and passing the string to object as
StringBuffer sb = new StringBuffer("Hello");
2. Another way of creating StringBuffer object is to first allocate memory to StringBuffer object using new operator and later storing the string into it.
StringBuffer sb = new StringBuffer();
When you create like this StringBuffer object allocates a size of 16 characters. Even though we can increase the size of the StringBuffer object when required.
Commonly Used Methods
1. s1.setCharAt(n,'x') - Modifies the nth character to "x"
2.s1.append(s2) - Appends the string s2 to s1 at the end
3.s1.setLength(n) - sets the string length to n
4. s1.insert(n,s2) - Insert the string s2 at the position of n in string s1.
Example program
import java.util.*; import java.lang.*; import java.io.*; class SBDemo { public static void main(String[] args) { StringBuffer sb=new StringBuffer("object Oriented"); System.out.println("Original String is:"+ sb); System.out.println("length of String is:"+ sb.length()); sb.setCharAt(6,'-'); // inserting character at 6th position in string StringBuffer s2=new StringBuffer("language"); sb.insert(15,s2); // inserting string at 15th posotion in string System.out.println("Modified String is:"+ sb); } }Output:
D:\java examples>javac SBDemo.java
D:\java examples>java SBDemo
Original String is:object Oriented
length of String is:15
Modified String is:object-Oriented language
Difference between string and StringBuffer
String |
StringBuffer |
Used to create immutable string |
Used to create mutable strings |
It does not contain direct methods to manipulate string object |
It does contain direct methods to manipulate string object |
It is a sub class |
It is a super class |
It is available in java.lang package |
It is available in java.util package |
String is not synchronized which means it not thread safe |
It is synchronized which means it is synchronized |
Poor performance |
Better performance |
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.