Ad
  • Custom User Avatar

    Even better using new StringBuilder(initialLength) constructor since final string length is predictable to avoid memory copy when internal buffer is exhausted

  • Custom User Avatar

    String string = "";
    for (int i = 1; i <= num; i++) {
    string += i + " sheep...";
    }
    This method creates a new String object each time "string += " is called, but only one object is referenced by the variable. The unused objects are stored until they get deleted at the end. StringBuilder remains one object the whole time and reduces RAM use.