Possible Duplicate:
what is the difference between String and StringBuffer in java?
When I test a function using StringBuffer and String. When I use StringBuffer, I get the java.lang.OutOfMemoryError within the 2 or 3 secound.But, when I use String, I did not get java.lang.OutOfMemoryError error until one minutes. What different them, I don't know exactly.
public void print() {
StringBuffer buffer = new StringBuffer();
double result = 1.0 / 7.0;
buffer.append(result);
while (result != 0) {
result = result % 7.0;
buffer.append(result);
}
System.out.println(buffer.toString());
}
public void print() {
String st = "";
double result = 1.0 / 7.0;
st = st + result;
while (result != 0) {
result = result % 7.0;
st = st + result;
}
System.out.println(st);
}
StringBufferis faster so you may run out of memory faster. You should check how many results got stored in each case to see if it's the problem with speed difference or the memory usage difference between String and StringBufferStringBufferwas replaced in Java 5.0 eight years ago byStringBuilderbutStringis still used today.