code: public static StringBuilder formatAndReplace(
              String compiledPattern, StringBuilder result, int[] offsets, CharSequence... values) {
          int valuesLength = values != null ? values.length : 0;
          if (valuesLength < getArgumentLimit(compiledPattern)) {
              throw new IllegalArgumentException("Too few values.");
          }
  
          // If the pattern starts with an argument whose value is the same object
          // as the result, then we keep the result contents and append to it.
          // Otherwise we replace its contents.
          int firstArg = -1;
          // If any non-initial argument value is the same object as the result,
          // then we first copy its contents and use that instead while formatting.
          String resultCopy = null;
          if (getArgumentLimit(compiledPattern) > 0) {
              for (int i = 1; i < compiledPattern.length();) {
                  int n = compiledPattern.charAt(i++);
                  if (n < ARG_NUM_LIMIT) {
                      if (values[n] == result) {
                          if (i == 2) {
                              firstArg = n;
                          } else if (resultCopy == null) {
                              resultCopy = result.toString();
                          }
                      }
                  } else {
                      i += n - ARG_NUM_LIMIT;
                  }
              }
          }
          if (firstArg < 0) {
              result.setLength(0);
          }
          return format(compiledPattern, values, result, resultCopy, false, offsets);
      }
docs: Formats the given values, replacing the contents of the result builder.
  May optimize by actually appending to the result if it is the same object
  as the value corresponding to the initial argument in the pattern.
  
  @param compiledPattern Compiled form of a pattern string.
  @param result Gets its contents replaced by the formatted pattern and values.
  @param offsets offsets[i] receives the offset of where
  values[i] replaced pattern argument {i}.
  Can be null, or can be shorter or longer than values.
  If there is no {i} in the pattern, then offsets[i] is set to -1.
  @param values The argument values.
  An argument value may be the same object as result.
  values.length must be at least getArgumentLimit().
  @return result