• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Formating with printf() and format()

 
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,

Can anyone explain me the code and the output



int i1 = -123;
int i2 = 12345;
System.out.printf(">%1$(7d< \n", i1);
System.out.printf(">%0,7d< \n", i2);
System.out.format(">%+-7d< \n", i2);
System.out.printf(">%2$b + %1$5d< \n", i1, false);
This produces:
> (123)<
>012,345<
>+12345 <
>false + -123<


Thanks in advance
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can find the description of format strings in the API documentation for the class java.util.Formatter. That will explain exactly the output for those statements.
 
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following article could be of interest.

System.out.printf() - J2SE5.0
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the first printf statement 1$ represents which argument to select from those given after a "," and ( represents that if the no. is -tive then it wll wrap it in "()".n 7 means it provides a space of 7 bits for it.d is used for integers...
In the second printf statement "0 and ," means it will insert 0's and ,'s in empty spaces that will remain after the digits.for instance here i2 is of 5 digits but we provide a space of 7 digits for it so this statement inserted a 0 and a , in blank spaces.
In the format statement "+-" represents that it will insert either + or - depending upon whether the no. is +tive or -tive.
In third printf statement "2$" means it will select the 2nd one and "b" is for boolean....
well it is explained in k&b you can check it from there.
best of luck.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic