Skip to content

Tag: String

Java, printing arrays

As I keep forgetting, this post is to remind me that Java Java doesn’t have a pretty toString() for arrays objects, and it does for Lists.

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class ListsExample {
    public static void main (String args[]) {
        // as an array
        String[] list1 = {"a","b","c"};
        // as an List provided by Arrays
        List<String> list2 = Arrays.asList("d", "e", "f");

        // as an implementation of the interface List
        // ArrayList (could also be LinkedList, Vector, etc)
        List<String> list3 = new ArrayList<String>();

The output is:

[a, b, c]
[d, e, f]
[g, h, i]

Beware the locale

See-ming Lee 李思明 SML Photo

Today I was programming a toString method for a class widely used in a application, using the very useful String.format that provides a C’s like printf formatter.

public String toString() {
   return String.format("VO[a: %.1f, b: %.1f, c: %.1f]", a, b, a+b);

%.1f means a float with one digit precision after the dot separator. The code produces something like:

VO[a: 1.0, b: 2.0, c: 3.0]

The problem arises when running a JUnit test on this method wrote using a regular expression to extract the values from the String to test it correctness. We cannot assume that the dot will be always the separator for displaying a float value, in my locale pt_BR would be a comma. So the output would be:

VO[a: 1,0, b: 2,0, c: 3,0]

For a predictable output we can set a Locale for String.format:

Locale en = new Locale("en");
return String.format(en, "VO[a: %.1f, b: %.1f, c: %.1f]", a, b, a+b);

So it will always use the dot as common separator. Of course you should follow and respect the localization and internationalization efforts in others moments but in this toString case we are using it internally for debug and unitary testing so we can set a English default locale for safety reasons.