2

Suppose I have the following code:

double median = med(10.0, 12.0, 3.0); //method returns middle number as double

Now, I want to write a message stating the median. Can this be done using println(), like the following:

System.out.println("Your number was " + median);

Or must I use printf() with double values?

The reason I ask is because I have seen both practices online 1, but when I try using println() I get an error, unless i write:

System.out.println(median);

Hence, can you use println() to print out double values and strings, or must you use printf() for that purpose?

yulai
  • 741
  • 3
  • 20
  • 36
  • 3
    I don't receive an error when writing "System.out.println("Your number was " + median);" Does this really throw an error for you? if yes which one? – ParkerHalo Dec 03 '15 at 10:36
  • 2
    Possible duplicate of [Is there a good reason to use "printf" instead of "print" in java?](http://stackoverflow.com/questions/548249/is-there-a-good-reason-to-use-printf-instead-of-print-in-java) – Fawzan Dec 03 '15 at 10:38

2 Answers2

9

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
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
2

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);
Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81