Formatter.java – replacing StringBuilder

In most cases, I can replace StringBuilder with a Formatter, but of course Formatter offers more!

new Formatter(new StringBuilder()) painlessly appends!

import java.util.Formatter;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;

public class FormatterTest {
    private Formatter formatter;
    private StringBuilder sb;
    @Before
    public void setUp() {
        this.formatter = new Formatter(new StringBuilder());
        this.sb = new StringBuilder();
    }
    @Test
    public void testArray() {
        char[] var= new char[] {‘a’, ‘b’, ‘c’};
        sb.append(var+””);
        formatter.format(var+””, “”);
        assertEquals(sb.toString(), formatter.toString());
    }
    @Test
    public void testInt() {
        int var=902;
        sb.append(var);
        formatter.format(var+””, “”);
        assertEquals(sb.toString(), formatter.toString());
    }
    @Test
    public void testFloat() {
        float var=902;
        sb.append(var);
        formatter.format(var+””, “”);
        assertEquals(sb.toString(), formatter.toString());
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s