Tutorials

Java String


StringBuilder in java


String Builder in java helps us create mutable string object just like String Buffer. 

 

We can modify the created string any number of time we want. It was introduced JDK 1.5

 

Note: String Builder is non-synchronized or not thread-safe. It means multiple threads can access it simultaneously.

 

 

Q Time: Difference between String Buffer and String Builder?

Package: String Builder class is present in java.lang package.

 

Implements: String Builder implements Serializable and charSequence interface.

 

Extend: String Builder class extends Object class.

 

String Builder class is declared as shown below:

Public final class StringBuilder extends Object implements Serializable, charSequence{}

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

 

String Builder append()

The append() method will concatenate the new string to the original string.

public class CreateStrBdr {

 

      public static void main(String[] args) {

            StringBuilder sb = new StringBuilder("Mukesh"); //original string

            sb.append("Tripathi");  //append to original string

 

            System.out.println(sb);

      }

}

 

OUTPUT:

MukeshTripathi

 

String Builder reverse()

The reverse() method of String Builder in java is used to reverse the original string. For example String MukeshTripathi will be reversed to ihtapirThsekuM.

 

Example:

public class CreateStrBdr {

 

      public static void main(String[] args) {

            StringBuilder sb = new StringBuilder("Mukesh");

            sb.append("Tripathi");

 

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

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

      }

}

 

OUTPUT:

appended string: MukeshTripathi

reversed string: ihtapirThsekuM



Please Share this page
Views : 98
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!