PatternedStringBuilder { public String sprintf(Object... args) { ByteArrayOutputStream retval = new ByteArrayOutputStream(); new PrintStream(retval).printf(getPattern(), args); return retval.toString(); } PatternedStringBuilder(String pattern); void setPattern(String pattern); String getPattern(); String sprintf(Object... args);  }
@Test public void testSprintf() { double pi = Math.PI; PatternedStringBuilder patterenedStringBuilder = new PatternedStringBuilder("pi = %5.3f"); String expectedVal = patterenedStringBuilder.sprintf(pi); assertEquals("pi = 3.142", expectedVal); patterenedStringBuilder.setPattern("%4$2s %3$2s %2$2s %1$2s"); assertEquals(" z y x w", patterenedStringBuilder.sprintf("w", "x", "y", "z")); patterenedStringBuilder.setPattern(""); assertEquals("", patterenedStringBuilder.sprintf("somethingElse")); }