JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

OCAJP – StringBuilder API

November 2, 2015 by Krishna Srinivasan Leave a Comment

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.

ocajp-exam

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.

OCAJP Javabeat Sales Promotion

StringBuilder Constructor

There are four variant of constructors defined in the StringBuilder class.

  1. StringBuilder()
  2. StringBuilder(CharSequence seq)
  3. StringBuilder(int capacity)
  4. 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.

  1. StringBuilder append(boolean b)
  2. StringBuilder append(char c)
  3. StringBuilder append(char[] str)
  4. StringBuilder append(char[] str, int offset, int len)
  5. StringBuilder append(CharSequence s)
  6. StringBuilder append(CharSequence s, int start, int end)
  7. StringBuilder append(double d)
  8. StringBuilder append(float f)
  9. StringBuilder append(int i)
  10. StringBuilder append(long lng)
  11. StringBuilder append(Object obj)
  12. StringBuilder append(String str)
  13. StringBuilder append(StringBuffer sb)
  14. StringBuilder appendCodePoint(int codePoint)
  15. int capacity()
  16. char charAt(int index)
  17. int codePointAt(int index)
  18. int codePointBefore(int index)
  19. int codePointCount(int beginIndex, int endIndex)
  20. StringBuilder delete(int start, int end)
  21. StringBuilder deleteCharAt(int index)
  22. void ensureCapacity(int minimumCapacity)
  23. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
  24. int indexOf(String str)
  25. int indexOf(String str, int fromIndex)
  26. StringBuilder insert(int offset, boolean b)
  27. StringBuilder insert(int offset, char c)
  28. StringBuilder insert(int offset, char[] str)
  29. StringBuilder insert(int index, char[] str, int offset, int len)
  30. StringBuilder insert(int dstOffset, CharSequence s)
  31. StringBuilder insert(int dstOffset, CharSequence s, int start, int end)
  32. StringBuilder insert(int offset, double d)
  33. StringBuilder insert(int offset, float f)
  34. StringBuilder insert(int offset, int i)
  35. StringBuilder insert(int offset, long l)
  36. StringBuilder insert(int offset, Object obj)
  37. StringBuilder insert(int offset, String str)
  38. int lastIndexOf(String str)
  39. int lastIndexOf(String str, int fromIndex)
  40. int length()
  41. int offsetByCodePoints(int index, int codePointOffset)
  42. StringBuilder replace(int start, int end, String str)
  43. StringBuilder reverse()
  44. void setCharAt(int index, char ch)
  45. void setLength(int newLength)
  46. CharSequence subSequence(int start, int end)
  47. String substring(int start)
  48. String substring(int start, int end)
  49. String toString()
  50. 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:

[code lang=”java”]
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"));
}
}
[/code]

Here is the output:

[code]
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!!
[/code]

StringBuilder Mock Exam Questions

1. What will be the output of the following program?

[code lang=”java”]
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");
}
}
[/code]

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

[code lang=”java”]
public class JavaBeatStringBuilderMock2 extends StringBuilder{
JavaBeatStringBuilderMock2(){ super(); }
}
[/code]

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.

Filed Under: OCAJP

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved