Download java lang StringBuilder Class in Formats
QR Code for this Page
java lang StringBuilder Class

java lang StringBuilder Class

java.lang.StringBuilder Class

StringBuilder Class in Java

A mutable sequence of characters. Java StringBuilder class provides an API compatible with Java StringBuffer, but with no guarantee of synchronization. Java StringBuilder class is designed for use as a drop-in replacement for Java StringBuffer in places where the Java StringBuffer was being used by a single thread. It is recommended that Java StringBuilder class be used in preference to Java StringBuffer as it will be faster under most implementations.

Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

Note :

StringBuilder implements Comparable but does not override equals. Thus, the natural ordering of StringBuilder is inconsistent with equals. Care should be exercised if StringBuilder objects are used as keys in a SortedMap or elements in a SortedSet. See Comparable, SortedMap, or SortedSet for more information.

What is StringBuilder in Java ?

StringBuilder in Java is known as StringBuilder class in Java. StringBuilder objects are like String objects, except that they can be modified. Internally, these StringBuilder objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations. If you need to concatenate a large number of strings, appending to a StringBuilder object is more efficient for better performance .

Is StringBuilder thread safe ?

The Java StringBuilder class is not thread safe . Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

How to convert Java StringBuilder to String ?

The toString() method of Java StringBuilder class can be used to convert StringBuilder content to a String. This method returns a String object that represents the contents of StringBuilder.

Which is better StringBuilder or StringBuffer ?

StringBuilder is better than StringBuffer . StringBuffer is mutable. It can change in terms of length and content. StringBuffers are thread-safe, meaning that they have synchronized methods to control access so that only one thread can access a StringBuffer object's synchronized code at a time.

How to clear or empty StringBuilder ?

You can clear or empty Java StringBuilder three ways. Java probably uses a builder in the background.

  1. Use stringBuilderObj.setLength(0)
  2. Allocate a new one with new StringBuilder() instead of clearing the buffer.
  3. If you want to clear or delete the contents of StringBuilder you can also use the delete(int start, int end) method of StringBuilder .

What is the use of StringBuilder ?

Java StringBuilder class is designed for use as a drop-in replacement for StringBuffer in places where the StringBuffer was being used by a single thread . If execution speed and performance is a factor, Java StringBuilder class can be used in place of StringBuffer.

List of StringBuilder Constructors

Constructor Description
StringBuilder() Creates an empty string builder with a capacity of 16 (16 empty elements).
StringBuilder(CharSequence cs) Constructs a string builder containing the same characters as the specified CharSequence , plus an extra 16 empty elements trailing the CharSequence .
StringBuilder(int initCapacity) Creates an empty string builder with the specified initial capacity.
StringBuilder(String s) Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string.

What is the Length and Capacity of StringBuilder in Java ?

The StringBuilder class , like the String class , has a length() method that returns the length of the character sequence in the StringBuilder.

Unlike strings , every StringBuilder also has a capacity, the number of character spaces that have been allocated. The capacity , which is returned by the capacity() method , is always greater than or equal to the length (usually greater than) and will automatically expand as necessary to accommodate additions to the StringBuilder.

StringBuilder Length and Capacity Methods

Method Description
void setLength(int newLength) Sets the length of the character sequence. If newLength is less than length() , the last characters in the character sequence are truncated. If newLength is greater than length() , null characters are added at the end of the character sequence.
void ensureCapacity(int minCapacity) Ensures that the capacity is at least equal to the specified minimum.

List of Various StringBuilder Methods

Method Description
StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(double d)
StringBuilder append(float f)
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String s)
Appends the argument to this string builder. The data is converted to a string before the append operation takes place.
StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)
The first method deletes the subsequence from start to end-1 (inclusive) in the StringBuilder's char sequence. The second method deletes the character located at index.
StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long lng)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String s)
Inserts the second argument into the string builder. The first integer argument indicates the index before which the data is to be inserted. The data is converted to a string before the insert operation takes place.
StringBuilder replace(int start, int end, String s)
void setCharAt(int index, char c)
Replaces the specified character(s) in this string builder.
StringBuilder reverse() Reverses the sequence of characters in this string builder.
String toString() Returns a string that contains the character sequence in the builder.

What are the principal operations on a StringBuilder in Java ?

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

For example, if z refers to a string builder object whose current contents are "start", then the method call z.append("le") would cause the string builder to contain "startle", whereas z.insert(4, "le") would alter the string builder to contain "starlet".

In general, if sb refers to an instance of a StringBuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x).

Following Java StringBuilder class example you can learn how to create Java StringBuilder and how to use Java StringBuilder.

Java StringBuilder Example with Default Constructor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*  Java StringBuilder Example with Default Constructor
    Save with file name StringBuilderExample1.java  */
  
public class StringBuilderExample1
{
  public static void main(String args[])
  {
    //Java StringBuilder DECLARATION
    StringBuilder s1;
    //CREATE Java StringBuilder INSTANCE USING DEFAULT CONSTRUCTOR
    //THE VALUE OF STRINGBUILDER IS EMPTY
    s1 = new StringBuilder();
    //Java StringBuilder OUTPUT EMPTYSTRING
    System.out.println("StringBuilder value : " + s1);
  }
}

Java StringBuilder Example with Parameter Constructor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*  Java StringBuilder Example with Parameter Constructor
    Save with file name StringBuilderExample2.java  */
  
public class StringBuilderExample2
{
  public static void main(String args[])
  {
    //Java StringBuilder DECLARATION
    StringBuilder s1;
    //CREATE Java StringBuilder INSTANCE USING PARAMETER CONSTRUCTOR
    s1 = new StringBuilder("Huda Tutorials");
    //Java StringBuilder OUTPUT
    System.out.println("StringBuilder value : " + s1);
  }
}

How to Reverse String in java using StringBuilder ?

By using the Java StringBuilder class you can reverse the string in java. In the following Java StringBuilder example you can learn how to reverse string in java using StringBuilder.

Most of the interviewer ask a question "How to reverse String in java?". Most of the people fail in this question. Because those are worked on String class not worked on StringBuilder class.

Following Java StringBuilder class example you can learn how to reverse string using StringBuilder.

How to reverse string using Java StringBuilder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*  Java StringBuilder Example with how to reverse string in java
    Save with file name StringBuilderExample3.java  */
  
public class StringBuilderExample3
{
  public static void main(String args[])
  {
    //Java StringBuilder DECLARATION
    StringBuilder s1;
    //CREATE Java StringBuilder INSTANCE USING PARAMETER CONSTRUCTOR
    s1 = new StringBuilder("abcd");
    //Java StringBuilder REVERSE STRING USING REVERSE METHOD
    System.out.println("Reverse String is : " + s1.reverse());
  }
}

Following Java StringBuilder class example you can learn how to append String into Java StringBuilder.

How to append String into Java StringBuilder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*  Java StringBuilder Example with how to append String into Java StringBuilder
    Save with file name StringBuilderExample4.java  */
  
public class StringBuilderExample4
{
  public static void main(String args[])
  {
    //Java StringBuilder DECLARATION
    StringBuilder s1;
    //CREATE Java StringBuilder INSTANCE USING PARAMETER CONSTRUCTOR
    s1 = new StringBuilder("Huda");
    s1.append("Tutorials");
    //Java StringBuilder APPENDED STRING
    System.out.println("String is : " + s1.toString());
  }
}
Download java lang StringBuilder Class in Formats