OCAJP – StringBuilder Class Examples

This post is about the OCAJP exam objective “Manipulate data using the StringBuilder class and its methods“. You will be tested in the exam about various methods and syntax related to the StringBuilder class. Here we would explain about the StringBuilder class and important methods. If you have any questions, please write it in the comments section.

StringBuilder Class

  • String Builder was added to Java in 1.5 version. We had StringBuffer class before StringBuilder class.
  • The class StringBuilder is defined in the package java.lang and it has a mutable sequence of characters.
  • StringBuilder is a final class , so it is not possible to create sub classes for it. You can use StringBuilder methods , but you can’t override.
  • StringBuilder implements two intefaces such as CharSequence, Serializable.
  • Unlike StringBuilder, the String class has an immutable sequence of characters. Every time you modify a string that’s represented by the String class, your code actually creates new String objects instead of modifying the existing one.
  • You must use class StringBuilder when you’re dealing with larger strings or modifying the contents of a string often. Doing so will improve the performance of your code.

When to use StringBuilder Class?

The exact difference between StringBuilder and StringBuffer class is that StringBuilder is not thread safe where StringBuffer is thread safe. It is highly recommended to use the StringBuilder class instead of using the StringBuffer class.

Here is some of the points about the StringBuilder class.

  • StringBuilder class methods are exactly same as StringBuffer class methods, except that StringBuilder is not thread safe.
  • In other words its methods are not synchronized.
  • Oracle recommends you that you use StringBuilder instead of StringBuffer whenever possible, because StringBuilder will run faster.
  • Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

Real World Scenario

We prefer String Builder when you are working with files that are large, ever changing streams of input are being handled by the program.In these cases large blocks of characters are handled as units, String Builder object are the great way to handle a block of data , pass it on and then reuse the same memory to handle next block of data.

Creating StringBuilder Objects

The StringBuilder class has four overloaded constructors.

  • StringBuilder( )
  • StringBuilder( CharSequence seq)
  • StringBuilder(int capacity)
  • StringBuilder(String str)

 Let’s use these constructors in a sample program.

class StringBuilderObjects {

     public static void main(String args[]) {

          StringBuilder sb1 = new StringBuilder();  // 1 
          StringBuilder sb2 = new StringBuilder(sb1); // 2
          StringBuilder sb3 = new StringBuilder(10); // 3
          StringBuilder sb4 = new StringBuilder("Hi"); // 4 

     }
}

Line 1 creates StringBuilder object with no characters in it and an initial capacity of 16 characters.

How StringBuilder capacity increases ?

Line 1 creates StringBuilder object with no characters in it and an initial capacity of 16 characters. After you add 17th character to StringBuilder object , it’s capacity will be increased to 34 . The formula used by the StringBuilder to increase its capacity.

newCapacity = (intialcapacity * 2) + 2.

  • Line 2 creates a StringBuilder object that contains the same set of characters as contained by the StringBuilder object passed to it.
  • Line 3 creates a StringBuilder object with no characters and an initial capacity of 10 characters.
  • Line 4 creates a StringBuilder object with an initial value as contained by the String object.

StringBuilder Class Methods

String Builder contains methods. Most of the methods works as like String methods, for example methods such as charAt, indexOf, lastIndexOf, substring and length.

append( )

  • The append method adds the specified value at the end of the existing value of a StringBuilder object and returns reference to the the same StringBuilder object .
  • Because you may want to add data from multiple data types to a StringBuilder object, this method has been overloaded so that it can accept data of any type.

This method accepts all primitives(char, int, long,float,double,boolean), String, char array, and Object as method  parameters.

class StringBuilderDemo {

      public static void main(String args[]) {

           StringBuilder sb = new StringBuilder();
           StringBuilder sb1 = new StringBuilder();
           StringBuilder sb2 = new StringBuilder();
           sb.append(5); // appends int value
           sb.append(false); // appends boolean value
           sb.append('a'); // appends char value 
           sb.append(10.5f); // appends float value 
           sb.append(10.5); // appends double value 
           sb.append("Hi"); // appends String object
           sb1.append(sb); // appends StringBuilder object
           sb2.append(sb, 1, 4);// appends characters from index 1 to 3 ( because 4 is exclusive).
           
           System.out.println(sb); // prints 5falsea10.510.5Hi
           System.out.println(sb1); // prints 5falsea10.510.5Hi
           System.out.println(sb2); // prints fa1
      }
}

Note : sb2.append(sb, 1, 4) This method throws IndexOutOfBoundsException if you give invalid values.

  • You can append a complete char array, or its subset as follows:
StringBuilder sb = new StringBuilder();
char[] name1 = { 'O', 'c', 'a', 'j', 'p' };
char[] name2 = { 'J', 'a', 'v', 'a', '8' };
sb.append(name1);
sb.append(name2, 1, 3);
            System.out.println(sb); // prints Ocajpava 
sb.append(name1);

It appends all characters to the StringBuilder object.

sb.append(name2, 1, 3);

Pay attention to this method. Here

1 – starting position in the array.

3 – How many characters to add  to array after starting position.

It throws IndexOutOfBoundsException according to Java doc if you give wrong index values. But In practice it throws ArrayIndexOutOfBoundsException.

  • Because the method append also accepts a method parameter of type Object, you can pass it any object from the Java API or your own user-defined object:

Example :

public class StringBuilderDemo {

       public static void main(String[] args) {
 
              StringBuilder sb1 = new StringBuilder();
              sb1.append("Java");
              sb1.append(new Student("Oracle"));
              System.out.println(sb1); // prints Javacom.mss.Student@58d25a40
       }
}
class Student {
              String name;Student(String str) { name = str; }
}

Insert( )

  • The insert method adds the specified value at the specified position of the existing value of a StringBuilder object returns reference to the same StringBuilder object . It throws StringIndexOutOfBoundsException, if you pass invalid index value.
  • It is also overloaded method.
  • Because you may want to add data from multiple data types to a StringBuilder object, this method has been overloaded so that it can accept data of any type.
  • This method accepts all primitives(char, int, long,float,double,boolean), String, char array, and Object as method
  • The main difference between the append and insert methods is that the insert method enables you to insert the requested data at a particular position, but the append method only allows you to add the requested data at the end of the StringBuilder object
public class StringBuilderDemo {

       public static void main(String[] args) {
 
              StringBuilder sb = new StringBuilder("IamJavaDevelopernow");
              StringBuilder sb1 = new StringBuilder();
              StringBuilder sb2 = new StringBuilder();
              sb.insert(2, 5); // inserts 5 literal at position 2
              sb.insert(4,false); // inserts false literal at position 4
              sb.insert(6,'a'); // inserts 'a' literal at position 6
              sb.insert(7,10.5f); // inserts 10.5 literal at position 7
              sb.insert(8,10.5); //inserts 10.5 literal at position 8
              sb.insert(9,"Hi"); // inserts String object at position 9
              sb1.insert(0,sb); // inserts StringBuilder object  at position 0
              sb2.insert(0,sb, 1, 4);// inserts characters of sb from index 1 to 3 (because 4 is exclusive) to sb2 at position 0.
              System.out.println(sb);//prints Ia5mfaa11Hi0.50.5lseJavaDevelopernow
              System.out.println(sb1);//prints Ia5mfaa11Hi0.50.5lseJavaDevelopernow
              System.out.println(sb2); // prints a5m
       }
}
  • You can inserts a complete char array, or its subset as follows:
StringBuilder sb = new StringBuilder("HiHello");
char[] name1 = { 'O', 'c', 'a', 'j', 'p' };
char[] name2 = { 'J', 'a', 'v', 'a', '8' };
sb.insert(2,name1);
sb.insert(4,name2, 1, 3);
                        System.out.println(sb);// prints HiOcavaajpHello
sb.insert(2,name1);

inserts all characters of names1 array to sb starting from position 2

sb.insert(4,name2, 1, 3);

Pay attention to this method. Here

1 – starting position in the array.

3 – How many characters to add  to sb after starting position.

4- starting position in sb to insert array elements.

  • Because the method append also accepts a method parameter of type Object, you can pass it any object from the Java API or your own user-defined object:

Example :

public class StringBuilderDemo {

       public static void main(String[] args) {

              StringBuilder sb1 = new StringBuilder("HiHello");
              sb1.insert(2,"Java");// inserts String object at position 2 
              sb1.insert(4,new Student("Oracle"));inserts Student object at position 4
              System.out.println(sb1);//prints HiJacom.mss.Student@58d25a40vaHello
      }
}

class Student {
      String name;
      Student(String str) { name = str; }
}

charAt( ), setCharAt( )

public char charAt(int index)
  • charAt method takes index value as argument , it returns the the particular character at the specified index value.
  • If you pass invalid index value it throws IndexOutOfBoundsException . But in practice it throws StringIndexOutOfBoundsException.
public void setCharAt(int index, char ch)
  • setCharAr method replaces the character at the specified index in the object. It returns nothing.
  • If you pass invalid index value it throws IndexOutOfBoundsException . But in practice it throws StringIndexOutOfBoundsException.

Example :

public class StringBuilderDemo {

       public static void main(String[] args) {

              StringBuilder sb = new StringBuilder("Hello");
              char c = sb.charAt(1);
              sb.setCharAt(0, 'N');
              System.out.println(c); // prints e
              System.out.println(sb); // prints Nello
      }
}

reverse(), toString() , replace public StringBuilder reverse()

  • Reverse method reverses the character sequence present in StringBuilder object and returns reference to the same object.
public String toString()
  • toString method converts StringBuilder object  into String object.
public StringBuilder replace(int start, int end, String str)
  • Replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end – 1 or to the end of the sequence if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start. (This sequence will be lengthened to accommodate the specified String if necessary.)
  • It throws StringIndexOutOfBoundsException if you give in valid index values.
public class StringBuilderDemo {

       public static void main(String[] args) {

              StringBuilder sb = new StringBuilder("Hello");
              sb.replace(1, 4, "ABC");
              System.out.println(sb); // prints HABCo
              StringBuilder sb1 = sb.reverse();
              String s = sb.toString(); 
              System.out.println(sb); // prints oCBAH
              System.out.println(sb == sb1); // prints true because both sb , sb1 referencing to the same object.
              System.out.println(s);// prints oCBAH
       }
 }

Delete, DeleteCharAt

public StringBuilder delete(int start, int end)
  • Delete methods removes characters from start position to end-1 position.
  • It throws StringIndexOutOfBoundsException if you give in valid index values.
public StringBuilder deleteCharAt(int index)
  • Removes the character at the specified index.
  • It throws StringIndexOutOfBoundsException if you give in valid index value.
public class StringBuilderDemo {

       public static void main(String[] args) {

              StringBuilder sb = new StringBuilder("HelloHi");
              sb.delete(2, 4); 
              sb.deleteCharAt(0);
              System.out.println(sb); // prints eoHi
       }
}

Capacity, ensureCapacity, length,setLength, trimToSize

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 void ensureCapacity(int minimumCapacity)
  • Ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:
  • The minimumCapacity argument.
  • Twice the old capacity, plus 2.
public void trimToSize()
  • Attempts to reduce storage used for the character sequence. If the buffer is larger than necessary to hold its current sequence of characters, then it may be resized to become more space efficient.
public int length()
  • Returns the number of characters in the particular object .
public void setLength(int newLength)
  • Sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument.
  • It throws IndexOutOfBoundsException, if the newLength argument is negative.
public class StringBuilderDemo {

       public static void main(String[] args) {

              StringBuilder sb = new StringBuilder();
              sb.append("OCAJP8");
              System.out.println(sb.capacity());// prints 16 because StringBuilder default capacity 16.
              System.out.println(sb.length());// prints 6 because we appended 6 character sequence  
              sb.ensureCapacity(20); // It increases the capacity, doesn't changes length of character sequence
              System.out.println(sb.capacity()); // prints 34 because capacity increases
              System.out.println(sb.length());// prints 6 
              sb.setLength(8);// It increases the length of character sequence, doesn't changes  capacity
              System.out.println(sb.capacity()); // prints 34
              System.out.println(sb.length()); // prints 8
              sb.trimToSize(); // It decreases the capacity to length of character sequence, but doesn't changes length of character sequence  
              System.out.println(sb.capacity()); // prints 8
              System.out.println(sb.length()); // prints 8
       }
}

getChars, indexOf, lastIndexOf , subSequence, subString

 public void getChars(int srcBegin, int srcEnd,char[] dst, int dstBegin)

Example

public class StringBuilderDemo {

       public static void main(String[] args) {

              StringBuilder sb = new StringBuilder();
              sb.append("OCAJP8");
              char[] ch = new char[5] ;
              sb.getChars(0, 2, ch, 0);
              System.out.println(Arrays.toString(ch)); // prints [O,C,  ,  ]
       }
}

public int indexOf(String str)

  • It looks for first match.If the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
  • public int indexOf(String str, int fromIndex)
  • It looks for first match.If the string argument occurs as a substring within this object starting at the specified index , then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
public class StringBuilderDemo {
 
       public static void main(String[] args) {

              StringBuilder sb = new StringBuilder();
              sb.append("OCAJPA8J");
              System.out.println(sb.indexOf("A")); // prints 2
              System.out.println(sb.indexOf("Z"));  // prints -1
              System.out.println(sb.indexOf("J",4));  // prints 7
      }
}

public int lastIndexOf(String str)

  • It looks for last match.If the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
Example : 
public class StringBuilderDemo {

        public static void main(String[] args) {

               StringBuilder sb = new StringBuilder();
               sb.append("OCAJPA8J");
               System.out.println(sb.indexOf("A")); // prints 2
               System.out.println(sb.lastIndexOf("A"));  // prints 5
               System.out.println(sb.lastIndexOf("Z"));  // prints -1
       }
}

public String substring(int start)

  • Returns a new String that contains a subsequence of characters currently contained in this character sequence. The substring begins at the specified index and extends to the end of this sequence.
  • It throws StringIndexOutOfBoundsException if start is invalid value.
public String substring(int start, int end)
  • Returns a new String that contains a subsequence of characters currently contained in this sequence. The substring begins at the specified start and extends to the character at index end – 1.
  • It throws StringIndexOutOfBoundsException if start or end or both invalid
public CharSequence subSequence(int start, int end)
  • Returns a new character sequence that is a subsequence of this sequence starting from start to end-1.
  • It throws StringIndexOutOfBoundsException if start or end or both invalid .
  • The difference between substring , subSequence is return types are different.

Both the returns reference to String object.

Example :

public class StringBuilderDemo {

       public static void main(String[] args) {

              StringBuilder sb = new StringBuilder();
              sb.append("OCAJPA8J");
              System.out.println(sb.substring(2)); // prints AJPA8J
              System.out.println(sb.substring(2,5));  // prints AJP
              CharSequence c =       sb.subSequence(2, 5);
              System.out.println(c);  // prints AJP
              System.out.println(c instanceof String);  // prints true
              System.out.println(c instanceof StringBuilder); // prints false
       }
}

OCAJP Tips

The following are the methods that are very important for the OCAJP exam preparation:

  • public StringBuilder append(String s)
  • public StringBuilder delete(int start, int end)
  • public StringBuilder insert(int offset, String s)
  • public StringBuilder reverse()
  • public String toString()

The exam may test your knowledge on difference between String and StringBuilder objects. You have to understand the clear difference between the String class and StringBuilder class.

You can try our free test for OCAJP Mock Exams. If you have any questions, please write it in the comments section.

About Aditi Malhotra

Aditi Malhotra is the Content Marketing Manager at Whizlabs. Having a Master in Journalism and Mass Communication, she helps businesses stop playing around with Content Marketing and start seeing tangible ROI. A writer by day and a reader by night, she is a fine blend of both reality and fantasy. Apart from her professional commitments, she is also endearing to publish a book authored by her very soon.

2 thoughts on “OCAJP – StringBuilder Class Examples”

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top