Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a printf statement in Java? [duplicate]

When is it considered good code to format a string output like this:

int count = 5;
double amount = 45.6;
System.out.printf("The count is %d and the amount is %45.6", count, amount);

utilising a printf statement, over code like this:

int count = 5;
double amount = 45.6;
System.out.print("The count is " + count + "and the amount is " + amount);

using a print statement?

I have read the JavaDocs which state that printf is "A convenience method to write a formatted string to this output stream using the specified format string and arguments."

But it doesn't state when, by convention, we should use one over the other?

So, when is it good coding to use a printf, and when is it good coding not to?

Thanks for any help.

like image 311
Dobhaweim Avatar asked Apr 17 '26 02:04

Dobhaweim


1 Answers

Two methods are provided for the convenience of a coder and for different needs. If you need string formatting then go for printf method but if there is no formatting required simply use print method and void %d,%s, etc formatters.

If you want to control the precision & padding of floating point numbers then use printf otherwise go for print.

like image 88
Juned Ahsan Avatar answered Apr 18 '26 16:04

Juned Ahsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!