StringBuffer class in java



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.

            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






Oldest

4 comments

Click here for comments
13 March 2022 at 17:41×

Mulththreading pls write

Reply
avatar
13 March 2022 at 19:03×

Yeah sure basic of String Handling Mr. Santosh Kumar.

Reply
avatar
13 March 2022 at 19:03×

Yeah sure Santosh kumar sir

Reply
avatar