Better Efficiency with StringBuffers

     

The StringBuffer class is useful for making strings that need to be concatenated , appended to, or otherwise tangled with more than two or three times. Because regular String objects are immutable, changing a String actually creates a whole new String, which is an expensive operation. To make String-changing more efficient, we use StringBuffer. If you've done any work in C#, you'll recognize this as System.Text.StringBuilder .

There are generally only two things you do with a StringBuffer: append text to it, and then, when you're all done appending, call the toString() method to use it as a String. Like so:

 

 package net.javagarage.demo.String; public class StringBufferDemo { public static void main(String[] args) {   //do it manually     StringBuffer sb = new StringBuffer("Sideshow");     sb.append(" Bob");     sb.append(" Frames Krusty");     System.out.println(sb);     System.out.println(doLoop()); }     private static String doLoop(){         StringBuffer sb = new StringBuffer();         int i = 10;         while(i > 0){             sb.append(i + ",");             i;         }      return sb.toString();     } } 

For this sort of operation, StringBuffers provide better efficiency. You often need to do this sort of thing when building SQL query strings to send to a database or when building file paths. It might be important to you to know that StringBuffer does not override the equals() method.

Calls to StringBuffer append operations can be chained. That is, the return type of a call to append is the newly appended StringBuffer object. So we could rewrite the code above in the following manner:

 

 StringBuffer sb = new StringBuffer("Sideshow"); sb.append(" Bob").append(" Frames Krusty"); //... 

This has the same result as the more verbose code in the previous example.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net