SwadhyAI Notes

All Java notes

Java Output Methods Reference

›Short versionOpen if you only have a minute.
  • System.out and System.err are PrintStream objects already connected to the console.
  • print writes and stays on the line. println writes and then ends the line.
  • printf and format fill a pattern. They do not add a newline unless the pattern contains %n.
  • A specifier that does not match its argument compiles, then throws when that line runs.
  • println on an array prints the array object, not its elements. Arrays.toString prints the elements.

System.out and System.err are PrintStream objects. Their print, println, and printf methods convert values to text and write them to the console or redirected output stream.

Methods

APIParametersReturnsBehaviorWatch for
print(value)Primitive, char[], String, Object, or no argument for some overloads.void.Writes text without adding a newline.Multiple print() calls appear on the same line unless you include spacing.
println(value)Optional value to print.void.Writes value text and then terminates the line.println(object) calls String.valueOf(object), which may call toString().
printf(String format, Object... args)Format pattern and matching values.PrintStream.Formats values using Formatter syntax.Wrong specifier types throw formatting exceptions at runtime.
format(String format, Object... args)Same as printf().PrintStream.Alias for formatted output on PrintStream.Use %n for portable newlines inside format strings.
flush()None.void.Forces buffered output to be written.Usually automatic for console println(), but useful before waiting for input.

Which call fits

OptionBest forTradeoff
System.outNormal program output users expect to read or pipe.Mixing diagnostics here makes automation harder.
System.errErrors, warnings, and debug diagnostics.May appear interleaved with stdout in some terminals.
LoggerReal applications with levels, timestamps, and destinations.More setup than simple teaching examples.

Examples

Formatted columns

java
String item = "Book";
int count = 3;
double price = 12.5;

System.out.printf("%-10s %3d %8.2f%n", item, count, price);

Print arrays readably

java
int[] scores = {90, 85, 100};
System.out.println(scores); // not useful
System.out.println(Arrays.toString(scores)); // [90, 85, 100]

int[] scores = {90, 85}; then System.out.println(scores); What appears, and which call prints the numbers?

println calls String.valueOf, and an array's toString is its type and identity, something like [I@1b6d3586. The numbers are still in the array. System.out.println(Arrays.toString(scores)) prints [90, 85]. Arrays.toString is a method of Arrays, not of PrintStream.