Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

So many ways to format the same data

Is there any difference in these four ways of formatting the same data?

    // Solution 1
    System.out.printf("%.1\n",10.99f);

    // Solution 2
    System.out.format("%.1\n",10.99f);

    // Solution 3
    System.out.print(String.format("%.1\n",10.99f));

    // Solution 4
    Formatter formatter = new Formatter();
    System.out.print(formatter.format("%.1\n",10.99f));
    formatter.close();
like image 691
user1883212 Avatar asked May 16 '13 09:05

user1883212


2 Answers

The first two are exactly the same, since printf is implemented as (source)

public PrintStream printf(String format, Object ... args) {
    return format(format, args);
}

The latter two are also exactly the same, since String.format is implemented as (source)

public static String format(String format, Object ... args) {
    return new Formatter().format(format, args).toString();
}

Finally, the 2nd and the 4th are more or less the same, as can be seen from the implementation of PrintStream.format (source). Under the hood, it also creates a new Formatter (if needed) and calls format on that Formatter.

public PrintStream format(String format, Object ... args) {
    try {
        synchronized (this) {
            ensureOpen();
            if ((formatter == null)
                || (formatter.locale() != Locale.getDefault()))
                formatter = new Formatter((Appendable) this);
            formatter.format(Locale.getDefault(), format, args);
        }
    } catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    } catch (IOException x) {
        trouble = true;
    }
    return this;
}
like image 99
Vincent van der Weele Avatar answered Oct 13 '22 01:10

Vincent van der Weele


System.out is a PrintStream For detail follow this Link : Details about various format

An invocation of this method of the form

out.printf(Locale l, String format,Object... args)

behaves in exactly the same way as the invocation

out.format(Locale l,String format,Object... args)

So 1 & 2 are same there is not any difference b/w them. and 3 & 4 are almost same only compilation time difference will be there if compared with 1 & 2.

like image 35
Vaibhav Jain Avatar answered Oct 13 '22 02:10

Vaibhav Jain