Saturday 3 August 2013

33:StringBuffer and StringBuilder

Learning Objectives
After completing this session, you will be able to:
‰  Define StringBuffer and StringBuilder
The StringBuffer Class
Problem with String objects: Once created, can no longer be modified (It is a final class)
A StringBuffer object:
‰  Similar to a String object
‰  But, mutable or can be modified:
‰  Unlike String in this aspect
‰  Length and content may get changed through some method calls
The StringBuffer Class: Methods
The StringBuffer Class: Example
1 class StringBufferDemo {
2 public static void main(String args[]) {
3 StringBuffer sb = new StringBuffer("Jonathan");
4 System.out.println("sb = " + sb);
5 /* initial capacity is 16 */
6 System.out.println("capacity of sb: "+sb.capacity());
7 System.out.println("append \'O\' to sb: " +
8 sb.append('O'));
9 System.out.println("sb = " + sb);
10 System.out.println("3rd character of sb: " +
11 sb.charAt(2));
12
13 char charArr[] = "Hi XX".toCharArray();
14 /* Need to add 1 to the endSrc index of getChars */
15 sb.getChars(0, 2, charArr, 3);
16 System.out.print("getChars method: ");
17 System.out.println(charArr);
18 System.out.println("Insert \'jo\' at the 3rd cell: "
19 + sb.insert(2, "jo"));
20 System.out.println("Delete \'jo\' at the 3rd cell: "
21 + sb.delete(2,4));
22 System.out.println("length of sb: " + sb.length());
23
24 System.out.println("replace: " +
25 sb.replace(3, 9, " Ong"));
26 /* Need to add 1 to the endIndex parameter of
27 substring*/
28 System.out.println("substring (1st two characters): "
29 + sb.substring(0, 3));
30 System.out.println("implicit toString(): " + sb);
31 }
32 }
The java.lang.StringBuilder Class
‰  J2SE5.0 added the StringBuilder class, which is a drop-in replacement for StringBuffer
in cases where thread safety is not an issue.
‰  Because StringBuilder is not synchronized,it offers faster performance than
StringBuffer.
‰  In general, you should apply StringBuilder in preference over StringBuffer. In fact, the
J2SE 5.0 javac compiler normally uses StringBuilder instead of StringBuffer whenever
you perform string concatenation as in System.out.println("The result is " + result);
‰  All the methods available on StringBuffer are also available on StringBuilder, so it
really is a drop-in replacement.
‰  StringBuilder is identical to the well-known StringBuffer class of Java except for one
important difference it is not synchronized, which means it is not thread-safe.
‰  The advantage of using StrignBuilder is faster performance.
‰  However, in cases in which you are applying multithreading, you must apply
StringBuffer rather than StringBuilder.
‰  The String class defines a new constructor that enables you to construct a String from
a StringBuilder as shown in the following code:
String(StringBuilder strBuildObj)
Try It Out
Problem Statement:
Write a program that illustrates the manipulation of the StringBuffer objects using the append() ,
insert() , and setCharAt() methods.
Code:
public class StringBufferApp {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer(" is ");
sb.append("Hot");
sb.append('!');
sb.insert(0, "Java");
sb.append('\n');
sb.append("This is ");
sb.append(true);
sb.setCharAt(21, 'T');
sb.append('\n');
sb.append("Java is #");
sb.append(1);
String s = sb.toString();
System.out.println(s);
}
}
Refer File Name: StringBufferApp.javato obtain soft copy of the program code
How It Works:
‰  The program creates a StringBuffer object using the string " is ". It appends the string
"Hot" using the append() method and the character '!' using an overloaded version of
the same method.
‰  The insert() method is used to insert the string "Java" at the beginning of the string
buffer.
‰  Three append methods are used respectively to tack on the following:
oA new line character (\n), the string "This is ", and the boolean value true.
‰  The append() method is overloaded to support the appending of the primitive data
types as well as arbitrary Java objects.
‰  The setCharAt() method is used to replace the letter 't' at index 21 with the letter 'T‘ .
The charAt() and setCharAt() methods allow StringBuffer objects to be treated as
arrays of characters.
‰  Finally, another newline character is appended tosb, followed by the string "Java is #"
and the int value 1.
‰  The StringBuffer object is then converted toa string and displayed to the console
window.
‰  The output of the program is as follows:
Java is Hot!
This is True
Java is #1
Tips and Tricks:
List out key points on String Buffers.
Solution:
‰  String Buffers are mutable strings.
‰  StringBuffer is a final class.
‰  They can be created empty, from a string orwith a capacity. An empty StringBuffer is
created with 16-character capacity. A StringBuffer created from a String has the
capacity of the length of String + 16. StringBuffer created with the specified capacity
has the exact capacity specified. As they can grow dynamically in size without bounds,
capacity does not have much effect.
‰  append, insert, setCharAt, and reverse are used to manipulate the string buffer.
‰  setLength changes the length. If the current content is larger than specified length,
then it is truncated. If it is smaller than the specified length, then nulls are padded. This
method does not affect the capacity.
‰  equals on StringBuffer does a shallow comparison (same like ==) and will return true
only if the objects are same. Do not use it to test content equality.
‰  trim is not a StringBuffer method.
‰  There is no relationship between String and StringBuffer. Both extend Object class.
‰  String context means, ‘+’ operator appearing with one String operand. String
concatenation cannot be applied to StringBuffer.
‰  A new StringBuffer is created.
‰  All operands are appended by calling toString method, if needed.
‰  Finally a string is returned by calling toString on the StringBuffer.
Summary
‰  The StringBuffer’s API is the same as the new StringBuilder’s API, except that
StringBuilder’s methods are not synchronized for thread safety.
‰  StringBuilder methods should run faster than StringBuffer methods.
‰  All of the following apply to both StringBuffer and StringBuilder:
‰  They are mutable – they can change without creating a new object.
‰  StringBuffer methods act on the invoking object, and objects can change without an
explicit assignment in the statement.
‰  StringBuffer equals() is not overridden; it doesn’t compare values.
‰  StringBuffer methods to remember: append(), delete(), insert(), reverse(), and
toString().

No comments:

Post a Comment