Tuesday, March 23, 2021

StringBuilder Class in Java With Examples

StringBuilder class in Java, added in Java 5, is a mutable (modifiable) sequence of characters just like StringBuffer class, which is in contrast to String class in Java which is an immutable sequence of characters. Thus in case of StringBuilder length and content of the sequence can be changed through certain method calls.

Internally StringBuilder class objects are treated like variable-length arrays that contain a sequence of characters.

StringBuilder class in Java provides an API compatible with StringBuffer, how it differs from StringBuffer is that StringBuilder in Java is not thread-safe whereas StringBuffer is thread-safe.

As per Java docs– StringBuilder class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.


Constructors in Java StringBuilder class

  • StringBuilder()- Constructs a string builder with no characters in it and an initial capacity of 16 characters.
  • StringBuilder(CharSequence seq)- Constructs a string builder that contains the same characters as the specified CharSequence.
  • StringBuilder(int capacity)- Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
  • StringBuilder(String str)- Constructs a string builder initialized to the contents of the specified string.

Java StringBuilder Capacity

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.

length and capacity methods in StringBuilder

Since we are talking about capacity here so it is very relevant to discuss length and capacity methods of StringBuilder in Java here. As it becomes confusing for some people to distinguish between these two methods.

  • public int capacity()- Returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.
  • public int length()- Returns the length (character count).

So you can see where length() method returns the length of the sequence of characters currently represented by this StringBuilder object, the capacity() method will return the current capacity. So if you create an empty StringBuilder object its length will be 0 but capacity will be 16 (default).

Example code

public class StringBuilderDemo {

 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder();
  System.out.println("length " + sb.length());
  System.out.println("capacity " + sb.capacity());
 }
}

Output

length 0
capacity 16

Where as when you initialize StringBuilder with a string "Test" where length of the string is 4 then length method will return 4 where as capacity method will return 20 as in that case initial capacity of the string buffer is 16 plus the length of the string argument.

Example code

public class StringBuilderDemo {

 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder("Test");
  System.out.println("length " + sb.length());
  System.out.println("capacity " + sb.capacity());
 }
}

Output

length 4
capacity 20

insert and append methods in StringBuilder class

The principal operations on a StringBuilder in Java are the append and insert methods. Most of the times you will use StringBuilder class over String when you are appending or inserting to a string. That won't result in creating lots of new string objects with every append as StringBuilder object is mutable.

append and insert methods are overloaded so as to accept data of any type. So there are overloaded versions which takes primitive data types like int, float, long, double as parameter apart from having versions which take String, StringBuffer, Object as parameter.

Each of these overloaded versions 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.

Java StringBuilder append method example

public class SBAppendDemo {
 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder();
  StringBuilder sb1 = sb.append("This").append(" is").append(" Number ").append(1).append(" and ").append(1.101);
  System.out.println("After append -- " + sb.toString());
  
  if(sb == sb1){
   System.out.println("True - same reference");
  }else{
   System.out.println("false - reference changed");
  }

  //With String
  String str = new String();
  String str1 = str.concat("This").concat(" is");
  if(str == str1){
   System.out.println("True - same reference");
  }else{
   System.out.println("false - reference changed");
  }
 }
}

Output

After append -- This is Number 1 and 1.101
True - same reference
false - reference changed

Here note that append method is used with string and primitive data types as parameters and appended to the StringBuilder. Just to check whether the reference remains same or changes a new reference sb1 of StringBuilder is created. It can be seen that sb and sb1 both are pointing to the same StringBuilder object, new object is not created for every append.

Same thing is done with String and data is concatenated to the original string, here again another reference str1 is created but str and str1 are not pointing to the same String object because new String object is created with every concatenation as String is immutable.

Java StringBuilder insert method example

public class SBDemo {

 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder("let");
  sb.insert(2, "n");
  System.out.println("After insert -- " + sb.toString());
 }
}

Output

After insert – lent

Java StringBuilder toString method

Another important method is toString(), this method returns a string representing the data in this sequence. A new String object is allocated and initialized to contain the character sequence currently represented by this object. This String is then returned. Subsequent changes to this sequence do not affect the contents of the String.

Java StringBuilder reverse method

One more convenient utility method provided by StringBuilder class in Java is reverse() method, in String class there is no such method. In case you want to reverse a string with StringBuilder it is just a method call.

public StringBuilder reverse()- Causes this character sequence to be replaced by the reverse of the sequence.

public class SBRevDemo {
 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder("Test");
  sb.reverse();
  System.out.println("reversed - " + sb.toString());
 }
}

Output

reversed – tseT

StringBuilder class also has subString and indexOf(), lastIndexOf() methods which provide the same functionality as in String class.

That's all for this topic StringBuilder Class in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. String Vs StringBuffer Vs StringBuilder in Java
  2. Java split() Method - Splitting a String
  3. Is String Thread Safe in Java
  4. How to Create Immutable Class in Java
  5. Java String Interview Questions And Answers

You may also like-

  1. Difference Between Comparable and Comparator in Java
  2. equals() And hashCode() Methods in Java
  3. Difference Between CountDownLatch And CyclicBarrier in Java
  4. AtomicInteger in Java With Examples
  5. Race Condition in Java Multi-Threading
  6. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  7. super Keyword in Java With Examples
  8. Java Abstract Class and Abstract Method

No comments:

Post a Comment