StringBuilder is a alternative to the existing StringBuffer class in Java. StringBuilder class is first introduced in Java 5.0. The key difference between StringBuilder and StringBuffer is that, StringBuilder is not synchronous where as StringBuffer is synchronous. This makes the StringBuilder class offers better performance then the StringBuffer.
The new OCAJP exam added a separate objective for String Builder class. The objective of the exam is:
Manipulate data using the StringBuilder class and its methods
If you look at the above objective, there is no clear indication of what are the methods that will be asked in the exam. That means there is likely chance that they may test you any methods that are defines in the StringBuilder API. In this tutorial, I will list down the methods and which are most important for the OCAJP exam. At the end of this tutorial, I have also provided few sample StringBuilder mock exam questions for your practice.
StringBuilder Constructor
There are four variant of constructors defined in the StringBuilder class.
- StringBuilder()
- StringBuilder(CharSequence seq)
- StringBuilder(int capacity)
- StringBuilder(String str)
StringBuilder Methods
There are fifty methods that are defines in the StringBuilder class. Most of the methods are overloaded and used for the similar operations with varying datatypes. You are not required to remember all the methods for the OCAJP exam, but required to understand few important methods and how to use them in your application. I have provided few examples at the end of this tutorial.
- StringBuilder append(boolean b)
- StringBuilder append(char c)
- StringBuilder append(char[] str)
- StringBuilder append(char[] str, int offset, int len)
- StringBuilder append(CharSequence s)
- StringBuilder append(CharSequence s, int start, int end)
- StringBuilder append(double d)
- StringBuilder append(float f)
- StringBuilder append(int i)
- StringBuilder append(long lng)
- StringBuilder append(Object obj)
- StringBuilder append(String str)
- StringBuilder append(StringBuffer sb)
- StringBuilder appendCodePoint(int codePoint)
- int capacity()
- char charAt(int index)
- int codePointAt(int index)
- int codePointBefore(int index)
- int codePointCount(int beginIndex, int endIndex)
- StringBuilder delete(int start, int end)
- StringBuilder deleteCharAt(int index)
- void ensureCapacity(int minimumCapacity)
- void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
- int indexOf(String str)
- int indexOf(String str, int fromIndex)
- 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 dstOffset, CharSequence s)
- StringBuilder insert(int dstOffset, CharSequence s, int start, int end)
- StringBuilder insert(int offset, double d)
- StringBuilder insert(int offset, float f)
- StringBuilder insert(int offset, int i)
- StringBuilder insert(int offset, long l)
- StringBuilder insert(int offset, Object obj)
- StringBuilder insert(int offset, String str)
- int lastIndexOf(String str)
- int lastIndexOf(String str, int fromIndex)
- int length()
- int offsetByCodePoints(int index, int codePointOffset)
- StringBuilder replace(int start, int end, String str)
- StringBuilder reverse()
- void setCharAt(int index, char ch)
- void setLength(int newLength)
- CharSequence subSequence(int start, int end)
- String substring(int start)
- String substring(int start, int end)
- String toString()
- void trimToSize()
StringBuilder Example
Here is very simple example for using StringBuilder class. I have used only very few important methods defined in the API, but it is easy to learn and use any of the methods by yourself. One of the important point tested in the real exam is that extending StringBuilder class. It is a final class, so developer can not extend this class.
StringBuilder Example Program:
package net.javabeat; public class StringBuilderExample{ public static void main(String[] args) { StringBuilder stringBuilder = new StringBuilder(50); stringBuilder.append("This"); stringBuilder.append(" "); stringBuilder.append("is"); stringBuilder.append(" "); stringBuilder.append("a sample"); stringBuilder.append(" "); stringBuilder.append("string"); stringBuilder.append("!!"); System.out.println("StringBuilder String : " + stringBuilder.toString()); System.out.println("StringBuilder Capacity : " + stringBuilder.capacity()); System.out.println("StringBuilder Length : " + stringBuilder.length()); System.out.println("StringBuilder Substring : " + stringBuilder.substring(3)); System.out.println("StringBuilder Char At : " + stringBuilder.charAt(5)); System.out.println("StringBuilder Capacity : " + stringBuilder.indexOf("sample")); System.out.println("StringBuilder Replace : " + stringBuilder.replace(2, 6, "replaced")); } }
Here is the output:
StringBuilder String : This is a sample string!! StringBuilder Capacity : 50 StringBuilder Length : 25 StringBuilder Substring : s is a sample string!! StringBuilder Char At : i StringBuilder Replace : Threplaceds a sample string!!
StringBuilder Mock Exam Questions
1. What will be the output of the following program?
public class JavaBeatStringBuilderMock1{ public static void main(String args[]) { String s = "hello"; StringBuilder sb = new StringBuilder("hello"); sb.reverse(); s.reverse(); if (s == sb.toString()) System.out.println("Equal"); else System.out.println("Not Equal"); } }
- A. It will print ‘Not Equal’.
- B. Runtime error.
- C. Compilation error.
- D. It will print ‘Equal’.
- E. None of the above.
Correct Answer : (C) is the correct answer.
There is no reverse() method in String class
2. Consider the following code:
public class JavaBeatStringBuilderMock2 extends StringBuilder{ JavaBeatStringBuilderMock2(){ super(); } }
The above code will not compile.
- A. True
- B. False
Correct Answer: (A) is the correct answer.
This will not compile because StringBuilder class is a final class and final classes cannot be extended. Hence the compiler will not allow this program to successfully compile. You would see the questions like this in real exam and so you should remember that StringBuffer and StringBuilder are also final. All Primitive wrappers are also final (i.e. Boolean, Integer, Byte etc).
java.lang.System is also final.
3. How can you initialize a StringBuilder to have a capacity of at least 50 characters?
- A. StringBuilder sb = new StringBuilder(50);
- B. StringBuilder sb = StringBuilder.getInstance(50);
- C. StringBuilder sb = new StringBuilder();sb.setCapacity(50);
- D. StringBuilder sb = new StringBuilder();sb.ensureCapacity(50);
Correct Answer: (A) and (D) is the correct answer.
StringBuilder(50) is one of the constructor takes capacity as the parameter and initializes the StringBuilder’s capacity. Also you can change the capacity of StringBuilder using the setCapacity(int) method.