Home > Java > javaTutorial > body text

Console output using character streams

Barbara Streisand
Release: 2024-11-12 06:25:02
Original
524 people have browsed it

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

Copy after login
  • 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);

Copy after login

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

Copy after login

The output will be:

Using a PrintWriter.
10
123.65
10 + 123.65 is 133.65

Copy after login

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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template