Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: print double - println or printf

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?

like image 517
yulai Avatar asked Mar 10 '26 15:03

yulai


1 Answers

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
like image 100
Abdelhak Avatar answered Mar 12 '26 05:03

Abdelhak



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!