100 likes | 341 Views
StringBuffer class. Presented by- Sarat Chetri DC2011MCA0027 01/11/12. StringBuffer. In Java, strings are class objects and implemented using two classes- Strings and StringBuffer . Both the String and StringBuffer classes are defined in java.lang .
E N D
StringBuffer class Presented by- SaratChetri DC2011MCA0027 01/11/12.
StringBuffer • In Java, strings are class objects and implemented using two classes- Strings and StringBuffer. • Both the Stringand StringBuffer classes are defined in java.lang. • StringBuffer creates a strings of flexiable lengththat can be modified in terms of both length and content. • With StringBuffer, we can insert characters and substrings in the middle of a string, or append another string to the end.
StringBuffer constructors • StringBuffer( ) • StringBuffer(intsize) • StringBuffer(String str)
Commonly used StringBufferMethods Method Task Modifies the nth character to x. Appends the string s2 to s1 at the end. Insert the string s2 at the position n of the string s1. Set the length of the string s1 to n. If n<s1.length(),s1 is truncated. If n>s1.length(), zeros are added to s1. • s1.setChartAt(n, ’x’) • S1.apend(s2) • S1.insert(n,s2) • S1.setLength(n)
Program 1- //Demonstrate append(). • class AppendDemo • { • public static void main(String args[]) • { • String s; • int a = 42; • StringBuffersb = new StringBuffer(40); • s = sb.append("a = ").append(a).append("!").toString(); • System.out.println(s); • } • } • The output is: 42!
Program 2-//Demonstrate insert(). • class InsertDemo • { • public static void main(String args[]) • { • StringBuffersb = new StringBuffer("I Java!"); • sb.insert(2, "like "); • System.out.println(sb); • } • } • The output is: I like java!
Program 3:// Demonstrate reverse(). • class ReverseDemo • { • public static void main(String args[]) • { • StringBuffers = new StringBuffer("abcdef"); • System.out.println(s); • s.reverse(); • System.out.println(s); • } • } • The output of abcdef • is fedcba.
References • Balagurusamy E, Programming with Java, Fourth Edn.,McGraw Hill. • http//www.mhhe.com/balagurusamy/java4. • Herbert Schildt, Java2: The complete reference, Fifth Edn.,McGraw Hill/osbrone.