views:

592

answers:

4

I haven't had the chance to take any serious low-level programming courses in school. (I know I really should get going on learning the "behind-the-scenes" to be a better programmer.) I appreciate the conveniences of Java, including the ability to stick anything into a System.out.print statement. However, is there any reason why you would want to use System.out.printf instead?

Also, should I avoid print calls like this in "real applications"? It's probably better to to print messages to the client's display using some kind of UI function, right?

+1  A: 

It is better if you need to control the precision of your floating-point numbers, do padding etc. System.out.print can print out all kinds of stuff, but you can't do finegrained control of precision and padding with it.

antti.huima
+2  A: 

Typically in a "real" application you would write to a logging system such as java.util.Logging or commons logging, which have the ability to log various levels of verbosity (i.e. "debug" mode, which would be disabled in a production environment). However for quick and dirty temporary debugging sometimes System.out.println() is the easiest way to do things (assuming your runtime environment dumps standard output somewhere where you can read it).

I should also mention that you can always use "String.format()" to create a string using a format and variable argument list (then pass this string into a logging method or System.out.println). This is often nicer than concatenating a bunch of variables together into a string.

Marc Novakowski
+6  A: 

The printf method of the PrintStream class provides string formatting similar to the printf function in C.

The formatting for printf uses the Formatter class' formatting syntax.

The printf method can be particularly useful when displaying multiple variables in one line which would be tedious using string concatenation:

int a = 10;
int b = 20;

// Tedious string concatenation.
System.out.println("a: " + a + " b: " + b);

// Output using string formatting.
System.out.printf("a: %d b: %d\n", a, b);

Also, writting Java applications doesn't necessarily mean writing GUI applications, so when writing console applications, one would use print, println, printf and other functions that will output to System.out.

coobird
a better example would be a floating point using %+x.yf, where x and y are different numbers.
Calyth
+2  A: 

If most real programs, logging is used. Debug messages can be turned on/off via logging configuration. See log4j as an example.

Peter Lawrey