In this article, we will learn to represent the StringBuffer class in java. StringBuffer class important class in java that is used to perform operations on strings. I have mentioned some points about the StringBuffer class.
StringBuffer is a class that performs string operations using its methods.
StringBuffer is a Thread-Safe, mutable sequence of characters.
StringBuffer is like String but can be modified in the same memory location.
StringBuffer object created in only one way it's by Constructor.
StringBuffer class is used to create mutable string objects.
StringBuffer class is available in java.lang package.
String and StringBuffer classes are the same only difference is mutability.
StringBuffer is fast and consumes less memory because we are concating two strings.
//StringBuffer has 4 constructors.
1. It creates an empty StringBuffer object with a default capacity of 16 buffers means 16 empty locations.
2. create a StringBuffer object with a given capacity
Syntax
StringBuffer sb=new StringBuffer(int capacity);
Example
StringBuffer sb3=new StringBuffer(3);
1. It creates an empty StringBuffer object with a default capacity of 16 buffers means 16 empty locations.
StringBuffer sb=new StringBuffer();
System.out.print(sb.capacity()); //16
2. create a StringBuffer object with a given capacity
Syntax
StringBuffer sb=new StringBuffer(int capacity);
Example
StringBuffer sb3=new StringBuffer(3);
3. create StringBuffer object with given string obj data.
// It performs string to copy from String to StringBuffer object.
// default capacity is 16+ s.length().
StringBuffer sb5=new StringBuffer("abc");
System.out.print(sb5); //abc
System.out.println(sb5.capacity()); // 19
4. create a new StringBuffer object with the given CharacterSequence object characters,
Syntax.
StringBuffer sb=new StringBuffer(CharSequence cs);
// it also performs string copy from CharacterSequence object to StringBuffer object.
its capacity is 16+length().
StringBuffer sb6=new StringBuffer("hello");
StringBuffer sb7=new StringBuffer(sb6);
System.out.print(sb6); // hello
System.out.print(sb7); // hello
System.out.print(sb6.capacity()); //21
System.out.print(sb7.capacity()); //21
// reference check
System.out.print(sb6==sb7); // false
// StringBuffer capacity should be >=0, if passed -ve numberJVM throws java.lang.NegativeArraySizeException
StringBuffer sb1=new StringBuffer(-5); //NASE
// Don't create StringBuffer object by passing null it leads NullPointerException
StringBuffer sb8=new StringBuffer(null); // NPE
4 comments
Click here for commentsString handling ....
ReplyMulththreading pls write
ReplyYeah sure basic of String Handling Mr. Santosh Kumar.
ReplyYeah sure Santosh kumar sir
Reply