Tutorials

Java String


StringBuffer in java


If we need a String object which can be modified then java provides us with facility of String Buffer and String Builder which helps us to create mutable String.

 

What is mutable String?

String which can be modified is called mutable String

We will use any one of them to create mutable String and keep modifying the characters of mutable String object.

 

String Buffer in java

String Buffer in java helps us create mutable string object. 

We can modify the created string any number of time we want.

 

Note: String Buffer is thread-safe. It means multiple threads cannot access it simultaneously.

 

Difference between String and String Buffer/String Builder?

Various methods which help us to modify String are given below:

 

String Buffer append()

 

The append() method will concatenate the new string to the original string. For example new string “Tripathi” will be appended to original string “Mukesh”.

 

Example:

 


public class CreateStrBfr {



      public static void main(String[] args) {

            StringBuffer sb = new StringBuffer("Mukesh");

            sb.append("Tripathi");



            System.out.println(sb);

      }

}

 

OUTPUT:

MukeshTripathi

 

String Buffer reverse()

 

Example:

 


public class CreateStrBfr {



      public static void main(String[] args) {

            StringBuffer sb = new StringBuffer("Mukesh");

            sb.append("Tripathi");



            System.out.println("appended string: "+ sb);

            System.out.println("reversed string:"+ sb.reverse());

      }

}


Please Share this page
Views : 123
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!