Home  >  Article  >  Java  >  Console output using character streams

Console output using character streams

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 06:25:02525browse

Saída do console com o uso de fluxos de caracteres

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);

  • OutputStream: Defines the destination OutputStream (e.g.: System.out for console).
  • makeRelease: Controls whether the stream will be automatically unloaded after each call to the println() or print() methods. If true, the download is automatic.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn