Created: 2023-09-06 14:45
Status: #concept
Subject: Programming
Tags: Java java.lang Java Package Java String

java.lang.StringBuilder

By default, Java creates a new String everytime we do "" + something.

  • so, when we do "" + 1 + "\n", we are actually creating two strings, but only keeping the last one.
  • a new StringBuilder() acts like a "" String, but we can .append() to it.
  • we can use new StringBuilder(someStr).reverse().toString() to reverse strings.

String numbers = ""; // creating a new string: ""
int i = 1;
// first creating the string "1" and then the string "1\n"
numbers = numbers + i + "\n";
i++;
// first creating the string "1\n2" and then the string "1\n2\n"
numbers = numbers + i + "\n"
i++;
// first creating the string "1\n2\n3" and then the string "1\n2\n3\n"
numbers = numbers + i + "\n"
i++;
// and so on
numbers = numbers + i + "\n"
i++;

System.out.println(numbers); // outputting the string
StringBuilder numbers = new StringBuilder();
for (int i = 1; i < 5; i++) {
    numbers.append(i); // only 1 string is built & manipulated
}
System.out.println(numbers.toString());

References