10 Examples of print(), println() and prinf() methods In Java - PrintStream

Hello guys, if you are working in Java or just started with Java then you have must come across statements like System.out.println("Hello world") to print something on console or command prompt. This is actually the first statement I wrote in Java when I started programming and at that time I didn't realize how it work and what is System and PrintStream class and what is out here but now I know and I am going to explain all this to you in this article, along with PrintStream class and its various print methods like print(), println() and particularly printf() to print various objects in Java. But,   Before we get to the 10 examples of Printstream printf() in Java, let me tell you a little bit more about what exactly Printstream is. 

Printstream is basically an output stream in Java that gives you various methods so that you can print representations of various data points simultaneously. The most commonly used output stream in Java, System.out, is a Printstream. 

You can think of this as an instance of the Printstream class. It can also represent a standard output stream that can be used to print text output onto the console. Another instance of the Printstream class is System.err. Printstream is also a byte outstream. It can convert all the output into bytes with the help of the specified encoding. This can be done using charset in the PrintStream() constructor invocation. 

Printstream in Java is also not limited to a console. It can act as a filter output stream that can be connected to other output streams. It provides methods to print any data values or objects in an appropriate format. These methods will never throw an IOException when writing data to an underlying output. 


10 Examples Of Printstream print(), println() and prinf() In Java


1. PrintStream Class Declaration

Since PrintStream is a concrete subclass of FilterOutputStream, it can extend the OutputStream superclass. It can also implement Closeable, Flushable, Appendable, as well as AutoCloseable interfaces. You can use the following syntax to declare the PrintStream class in Java:

public class PrintStream
  extends FilterOutputStream
     implements Appendable, Closeable

The PrintStream class was first introduced in the Java 1.0 version. You can find it in the java.io.PrintStream package. The PrintStream class can implement an Appendable interface in Java 5.0, allowing you to use it with a java.util.Formatter. 




2. PrintStream Class Constructor

  • The PrintStream class can define a wide variety of constructors in Java. 
  • The PrintStream(File file) constructor can create a new print-stream along with a specified file object and charset without any automatic line flushing. 
  • The PrintStream(File file, Charset charset) constructor creates a new print-stream with a specified file object and a charset object without any automatic line flushing. 
  • The PrintStream(OutPutStream os) constructor can also create a new print stream without any automatic line flushing. 

3. PrintStream Methods In Java

The PrintStream can also define some useful methods other than those derived from the FilterOutPutStream class. 

The PrintStream append​(char c) appends the specified character to this output stream and returns the stream.

The PrintStream append​(CharSequence cseq, int begin, int end) appends a subsequence of the specified character sequence to this output stream and returns the stream. The subsequence starts from the index begin and extends to the character at index end-1.

The PrintStream printf​(String format, Object… args) writes a formatted string to the underlying output stream using the specified format string and arguments. It returns the output stream.

4. Create A PrintStream Using Output Streams

You can create a print stream that can easily write formatted data into a file. Before creating a PrintStream, you have to import the java.io.PrintStream package. 

// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream(String file);

// Creates a PrintStream
PrintStream output = new PrintStream(file, autoFlush);




5. Create A PrintStream using Filename

You can create a PrintStream with the help of a file name that can write data into that specified file. You can also use an optional boolean parameter that can specify whether to perform autoflush or not. 

 // Creates a PrintStream
PrintStream output = new PrintStream(String file, boolean autoFlush);

6. The print() method

The print() method can be used to print the specified data to the output stream. You can also use the println() method to print the data to the output stream with a new line character at the end. 

class Main {
    public static void main(String[] args) {

        String data = "Hello World.";
        System.out.print(data);
    }
}

In this case, you do not need to create a PrintStream as you can use the print() method from the PrintStream class. 



7. The printf() Method

You can use the printf() method to print a formatted string that will include a formatted string and arguments as two parameters. 

printf("I am %d years old", 25);

You can see the following example to get an idea of how to use printf() in a program. 

import java.io.PrintStream;

class Main {
    public static void main(String[] args) {

        try {
            PrintStream output = new PrintStream("output.txt");

            int age = 25;

            output.printf("I am %d years old.", age);
            output.close();
        }
        catch(Exception e) {
            e.getStackTrace();
        }
    }
}

8. print() Method With The PrintStream Class

import java.io.PrintStream;

class Main {
    public static void main(String[] args) {

        String data = "This is a text inside the file.";

        try {
            PrintStream output = new PrintStream("output.txt");

            output.print(data);
            output.close();
        }
        catch(Exception e) {
            e.getStackTrace();
        }
    }
}

In this example, a print stream named output is created. This print stream is then linked with an output.txt file. 



9. Print Data With PrintStream

If you want to print data to a file, you can use the simple print() method. For example, 

PrintStream output = new PrintStream("output.txt");

When you run this code, the output.txt file that you have created will be filled with data. 

10. Print Data Using The printf() Method

In addition, you can also use the printf() method to print formatted text into a file. 

PrintStream output = new PrintStream("output.txt");

When you run this piece of code, the output.txt file will be filled with the necessary content. 

Frequently Asked Questions

1. What is PrintStream in Java?

Printstream is basically an output stream in Java that gives you various methods so that you can print representations of various data points simultaneously. The most commonly used output stream in Java, System.out, is a Printstream. You can think of this as an instance of the Printstream class. It can also represent a standard output stream that can be used to print text output onto the console. 

Another instance of the Printstream class is System.err. Printstream is also a byte outstream. It can convert all the output into bytes with the help of the specified encoding. This can be done using charset in the PrintStream() constructor invocation. 


2. What is the use of PrintStream?

Printstream in Java is also not limited to a console. It can act as a filter output stream that can be connected to other output streams. It provides methods to print any data values or objects in an appropriate format. These methods will never throw an IOException when writing data to an underlying output. 


That's all about PrintStream class and its various print(), println(), and printf() methods. They are very useful and probably the first few class and method you will use when you start with Java Programming. If you liked this list of 10 examples of PrintStream in Java, feel free to share it with your friends and family.  If you have any doubts, then feel free to ask in comments. 

Other Java IO tutorials you may like:
  • 2 ways to read a text file in Java? (solution)
  • What is difference between BufferedReader and Scanner in Java (example)
  • How to read an Excel file in Java? (solution)
  • How to read a CSV file in Java? (example)
  • How to create a file and directory in Java? (answer)
  • How to read an XML file in Java? (answer)
  • How to append text to an existing file in Java? (example)
  • 5 Free Java 8 and Java 9 Courses for Programmers (courses)
  • 5 Free Data Structure and Algorithm Courses (courses)
  • 5 Free courses to learn Spring Core and Spring Boot for Java developers (courses)
  • 10 tips to become a better Java developer (tips)

If you like this tutorial, don't forget to share and show your love, it motivate me to keep working hard. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.