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

printf method formats int values as booleans

Hello,

I am trying to take scjp6 in coming few weeks.But I still does not understand well how printf works even I read http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html . In this example, System.out.printf("45%2$b%3$+04d",978,654,321,111) result get is "45true+321. In here,second argument is boolean and I saw is that 978,654,321,111 only so where is boolean value included? and also +321 is how get? in this 978,654,321,111 321 is second argument I think. so what will print for %3$? Please explain me.


Thank you alot!

So your confusion seems to be on the part which prints "true", and "+321", right?


You are right that the given format expects the second argument to be a boolean. In particular, %2$b instructs to treat the second argument as a boolean value. Here, the second argument is 654 (not 321 as you thought). Then we have the problem on treating 654 as a boolean value, because, you know, 654 is an int value - not a boolean. However, if you look closely at the Formatter documentation you linked, it says how it treats something to be boolean:


If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is "true".


So basically, if the argument is boolean or Boolean we have no problem - we can treat a boolean as a boolean. If the argument is null, it is treated as "false". In ALL OTHER CASES, the argument is treated as "true".


Since the int value 654 falls under this "ALL OTHER CASES" category, it prints "true".



Moving on, we have this part remaining in the format: %3$+04d


I think it should be obvious that %3$ suggests to consider the third argument (which is 321). Appended to that, we have the other part which says +04d. We cab split into three parts:


+ : always include the negative/positive sign

4 : the width should be 4

0 : if there are less than 4 digits, pad the leading with 0's.


In other words, this means there should always be a negative/positive sign even when the number was positive, the number of characters should be 4, and the remaining slots (if any) should be filled up with zeros.


So, as we are dealing with the third argument, which is 321, adding the positive sign gives +321. As this already has four characters, no 0's will be added.


And that's it! That's how we got true+321.


As for an exercise, I suggest changing the third argument to something with two digits and try again. In other words, instead of having 321 in the third argument, use something like 57 in the third argument and see how it changes the result.


ExamLab © 2008 - 2024