File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes printf format Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "printf format" Watch "printf format" New topic
Author

printf format

Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
Source: Get Certified Exam Lab by Devaka Cooray
Practice Exam 1 / Q No. 35

System.out.printf("%02.2f%s%b",new Double(7),new StringBuffer("set"),"fAlSE");

The output of this statement comes out to be 7.00settrue

I do not understand what the initial 02 (just before the decimal point) means. API says that if 0 is present as the flag, the argument will be padded by zeroes.Based on this, I thought the output would be 07.00settrue, but it is not.

On the other hand, if I have the format string as
System.out.printf("%02d%s%b",new Integer(7),new StringBuffer("set"),"fAlSE");
the output is 07settrue where the padded zeroes come into effect.

The same thing is not happening for float type. Why?
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

I think you are not getting any padding as there is no extra space to use padding. In you example

%02d you have to print 7 and you have two characters to print it. So there is one padded 0.

But in the question %02.2f, you have to represent 7 in min two characters and there must be a fractional part of 2 digits. So the text will be displayed in three characters i.e. 7.00 so there is no place for extra padding.

I am not sure about this so let's see what others have to say...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
If the frmat string is %08.2f, the output is 00007.00 which accounts to 8 characters including the decimal point.

Similarly, %07.2f gives 0007.00

I think for float values, the number after the 0 indicates the total number of characters - before the decimal point, the decimal point and after the decimal point

And in case of %02.2f, the .2f rule alone gets satisfied because of, as Ankit said, lack of space.

Lets hear others' thoughts.
Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Hi ,
why the last argument gives true? and if it is not in String format it's giving false.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

@Preetha if you use %b on any value other than boolean value, than the answer will be true for any value exception for null values...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: printf format