JavaRush /Java Blog /Random EN /StringBuilder class in Java 8 with a practical example

StringBuilder class in Java 8 with a practical example

Published in the Random EN group
The class Stringcreates immutable strings. This means that if you apply any operation to a string or operation to a string, the result will be a new string. If this new string is not assigned to any variable, the result of the operation will be lost. Accordingly, operations on such strings necessarily lead to the creation of a new string. And this means additional memory and processor time costs. If there are a lot of operations on a string, then it is often more efficient to use dynamic strings, which are implemented by the class StringBuilder.
StringBuilder class in Java 8 with practical example - 1
Consider the code below:
String s = "Some text";
int count = 100;
for(int i = 0; i<100;i++){
   s+=i;
}
**********************
StringBuilder s = new StringBuilder(110);
int count = 100;
s.append("Some text");
for(int i = 0;i<count;i++){
s.append(i);
}
The above code addresses the same problem. When we add 100 new substrings to a given string. The first example uses the class for this purpose String, which is not very efficient since each addition of a substring leads to the construction of a new object String. And this is an additional waste of memory and time. In the second example, this problem is solved using the class StringBuilder. We create an object of the class in advance StringBuilder, and then using the method appendwe form the string we need by changing the contents of the created object StringBuilder, but without re-creating the object itself.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION