Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
SCJP Online Training » Discussions

formatting done by System.out.printf

System.out.printf("12%1$s","13%1$s","14%1$s");

Answer for this is given as : 1213%1$s

can you provide more explanation on this.

Hi Venkatrc,


Basically, printf uses Java formatter syntaxes, which is what the java.util.Formatter class uses. Since you have already read the study guide, you might want to read the formatter stuff a little bit again to make sure you know the basics of String formatting. If you like reading something online, here is a quick Oracle tutorial which explains the basics:


https://docs.oracle.com/javase/tutorial/java/data/numberformat.html


We have a full documentation of conversions, flags, precision, etc, in this documentation:


http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax


Please, do NOT proceed to read the rest of this email, until you read the above two articles.


After you have completed reading the above two articles, we have the following statement in this question:

System.out.printf("12%1$s","13%1$s","14%1$s");


Here we have three arguments. The first argument 12%1$s is the pattern String. Other two arguments are just normal Strings - it can be anything - even your name. This question shows these two arguments as patterns as a trick only to confuse you.


Let's consider each part of our pattern: 12%1$s


We can divide this pattern into three parts as in:


12

%1$

s


The first part, 12 is a numeric value, which says just takes "12".


The second part, as is ended with $, signifies that it take a text argument (remember, we have 3 arguments: 1 pattern and 2 texts). The number after %, which is 1, signifies we should take the first text (which is the second argument), that is 13%1$s.


The third part, "s" signifies it to be considered as a String.


Please let me know if you find anything in this not clear enough.

ExamLab © 2008 - 2024