Difference between String and String Buffer Classes
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   RV_RamaKrishna
Posted On:   Friday, December 17, 2004 12:19 AM

Difference between String and String Buffer ClassesEnter

Re: Difference between String and String Buffer Classes

Posted By:   Anonymous  
Posted On:   Friday, December 17, 2004 01:34 AM

Can you read 1000 times on the 'net.

Quick: String is an immutable class (you dont know what this is, or why it is very important? - find yourself an explantion on the 'net). Remember if you want to be a professional designer/architect: Try to make every class immutable.

StringBuffer is mutable.

In a few(!) cases, it is more efficient to use StringBuffer so that only a few Strings are created. Example:


public static void main(String[] args) {
String s = "";
for (int i = 0; i < args.length; i++)
s += args[i] + " ";
System.out.println(s);
}

will create about 2*args.length strings (go thru the code manually to check); and it will copy on the order of s.length()*args.length characters/2, so every character is copied about args.length characters/2 times (your math course had the formula for 1+2+3+...+n - apply it here).

public static void main(String[] args) {
StringBuffer sb = new StringBuffer(1000); // dont forget to estimate the size!!!!!!!!!!!! default is 16 - MUCH TOO SMALL.
for (int i = 0; i < args.length; i++) {
sb.append(args[i]);
sb.append(' ');
}
System.out.println(sb.toString());
}

will create only one string, and (if the result length is < 1000) copy each character only exactly once.


Regards
Harald M.

About | Sitemap | Contact