The printf method can be particularly useful when displaying multiple variables in one line which would be tedious using string concatenation:
The println() which can be confusing at times. (Although both can be used in almost all cases).
double a = 10;
double b = 20;
System.out.println("a: " + a + " b: " + b);// Tedious string concatenation.
System.out.printf("a: %f b: %f\n", a, b);// Output using string formatting.
Output:
a: 10.0 b: 20.0
a: 10,000000 b: 20,000000
Answer from Abdelhak on Stack OverflowVideos
The printf method can be particularly useful when displaying multiple variables in one line which would be tedious using string concatenation:
The println() which can be confusing at times. (Although both can be used in almost all cases).
double a = 10;
double b = 20;
System.out.println("a: " + a + " b: " + b);// Tedious string concatenation.
System.out.printf("a: %f b: %f\n", a, b);// Output using string formatting.
Output:
a: 10.0 b: 20.0
a: 10,000000 b: 20,000000
You can do both (if System.out.println("Your number was " + median); is not working you have something else wrong. Show us the stack trace). printf allows you some more formatting options (such as the number of decimal places) without having to use a DecimalFormat, but it is a choice on style rather than anything else.
Personally I find string concatenation easer on the eyes and easer to maintain. The %blah gets lost in the string, errors in string concatenation is a compile time error and adding a new variable requires less thought. However I'm in the minority on this.
The pros in printf is that you don't need to construct a bunch of formatters, others find its format easer on the eyes and when using a printf like method provided by a logging framework the string building only happens if actually required.
double value = 0.5;
System.out.println("value: " + value);
System.out.printf("value: %f", value);
If you want to set a number of decimal places:
double value = 0.5;
// String concatenation
DecimalFormat df = new DecimalFormat("0.000");
System.out.println("value: " + df.format(value));
// printf
System.out.printf("value: %.3f", value);
System.out.printf("%.0f",x);
- The .0 specifies the precision. Number is rounded off according to the precision specified here. (e.g. if you want 2 decimal places you would specify 0.2)
- The f specifies it's a floating point - including doubles (d is for decimal integer)
You can also use %g as well to round-off and print double as integer:
System.out.printf("x=%g%n", x);