For console output in Java, although the use of System.out is allowed, it is most recommended for debugging or example simple programs. In real applications, using PrintWriter, a character-based class, is preferable as it facilitates internationalization.
The most common constructor of PrintWriter is:
PrintWriter(OutputStream fluxoSaída, boolean fazLiberação);
With PrintWriter, you can use print() and println() with any type of data, including objects (where the toString() method is invoked).
To use PrintWriter for console output:
PrintWriter pw = new PrintWriter(System.out, true);
Example of use:
public class PrintWriterDemo { public static void main(String args[]) { PrintWriter pw = new PrintWriter(System.out, true); int i = 10; double d = 123.65; pw.println("Using a PrintWriter."); pw.println(i); pw.println(d); pw.println(i + " + " + d + " is " + (i + d)); } }
The output will be:
Using a PrintWriter. 10 123.65 10 + 123.65 is 133.65
So, while System.out is practical for simple output or learning, PrintWriter provides a better approach for internationalized and consistent output in real applications.
The above is the detailed content of Console output using character streams. For more information, please follow other related articles on the PHP Chinese website!