Wednesday, 27 July 2016

StringBuilder in Java

StringBuilder class (Added in Java 5),just like StringBuffer, is a mutable(modifiable) sequence of characters which is in contrast to String class 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 objects are treated like variable-length arrays that contain a sequence of characters.

StringBuilder class provides an API compatible with StringBuffer, how it differs from StringBuffer is that StringBuilder is not thread-safe whereas StringBuffer is thread-safe.
As per Java docs – This 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 for StringBuilder

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.

  • 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.

length and capacity method

Since we are talking about capacity here so it is very relevant to discuss length and capacity method 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 method

The principal operations on a StringBuilder 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.

Example Code

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");
  }

  
  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.

Example code for insert method

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

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.

reverse method

One more convenient utility method provided by StringBuilder class 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.

Example code

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 in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String in Java
  2. String comparison in Java
  3. Splitting a String using split() method in Java
  4. String join() method in Java 8
  5. How to find the longest palindrome in the given String
  6. Java String interview questions

You may also like -

>>>Go to Java Basics page

2 comments:

  1. Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.

    Digital Marketing For Small Business in Chennai

    ReplyDelete
  2. Great and really helpful article! Adding to the conversation, providing more information, or expressing a new point of view...Nice information and updates. Really i like it and everyday am visiting your site..

    CRO Agency in Chennai

    ReplyDelete