Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java.io.StringWriter class in Java
Next article icon

Java.io.PrintWriter class in Java | Set 1

Last Updated : 12 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Java PrintWriter class gives Prints formatted representations of objects to a text-output stream. It implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams. Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. 

These methods use the platform’s own notion of line separator rather than the newline character. 

Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError(). 

Declaration of Java PrintWriter Class

public class PrintWriter extends Writer  

Constructor and Description

  • PrintWriter(File file): Creates a new PrintWriter, without automatic line flushing, with the specified file.
  • PrintWriter(File file, String csn): Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.
  • PrintWriter(OutputStream out): Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
  • PrintWriter(OutputStream out, boolean autoFlush): Creates a new PrintWriter from an existing OutputStream.
  • PrintWriter(String fileName): Creates a new PrintWriter, without automatic line flushing, with the specified file name.
  • PrintWriter(String fileName, String csn): Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.
  • PrintWriter(Writer out): Creates a new PrintWriter, without automatic line flushing.
  • PrintWriter(Writer out, boolean autoFlush): Creates a new PrintWriter.

Methods of PrinterWriter class in Java

Methods of PrinterWriter Class in Java are mentioned below:

Method Description
PrintWriter append(char c) Appends the specified character to this writer
PrintWriter append(CharSequence csq, int start, int end) Appends the specified character sequence to this writer.
PrintWriter append(CharSequence csq)  Appends a subsequence of the specified character sequence to this writer.
boolean checkError() Flushes the stream and checks its error state.
protected void clearError() Clears the internal error state of this stream.
void close() Closes the stream and releases any system resources associated with it.
void flush() Flushes the stream.
PrintWriter format(Locale l, String format, Object… args) Writes a formatted string to this writer using the specified format string and arguments.
PrintWriter format(String format, Object… args) Writes a formatted string to this writer using the specified format string and arguments.
void print(boolean b) Prints a boolean value.
void print(char c) Prints a character.
void print(char[] s) Prints a character array.
void print(double d) Prints a double.
void print(float f) Prints a float.
void print(int i) Prints an integer.
void print(long l) Prints a long integer.
void print(Object obj) Prints an object.
void print(String s) Prints a string.

1. PrintWriter append(char c)

Appends the specified character to this writer

Syntax :public PrintWriter append(char c)    Parameters:  c - The 16-bit character to append    Returns:  This writer

2. PrintWriter append(CharSequence csq, int start, int end)

Appends the specified character sequence to this writer.

Syntax :public PrintWriter append(CharSequence csq,          int start,int end)            Parameters:          csq - The character sequence from which a subsequence will be appended.          start - The index of the first character in the subsequence          end - The index of the character following the last character in the subsequence    Returns:This writer    Throws:          IndexOutOfBoundsException

3. PrintWriter append(CharSequence csq)

Appends a subsequence of the specified character sequence to this writer.

Syntax :public PrintWriter append(CharSequence csq)    Parameters:          csq - The character sequence to append.    Returns: This writer

4. boolean checkError()

Flushes the stream and checks its error state.

Syntax :public boolean checkError()    Returns: true if and only if this stream   has encountered an IOException other than InterruptedIOException,   or the setError method has been invoked

5. protected void clearError()

Clears the internal error state of this stream.

Syntax :protected void clearError()

6. void close()

Closes the stream and releases any system resources associated with it.

Syntax :public void close()    Specified by:close in class Writer

7. void flush()

Flushes the stream.

Syntax :public void flush()    Specified by:flush in interface Flushable    Specified by:flush in class Writer

8. PrintWriter format(Locale l, String format, Object… args)

Writes a formatted string to this writer using the specified format string and arguments.

Syntax :public PrintWriter format(Locale l,          String format,          Object... args)    Parameters:          l - The locale to apply during formatting. If l is null,   then no localization is applied.          format - A format string as described in Format string syntax          args - Arguments referenced by the format specifiers in the format string.   The number of arguments is variable and may be zero.    Returns: This writer    Throws:          IllegalFormatException          NullPointerException

9. PrintWriter format(String format, Object… args)

Writes a formatted string to this writer using the specified format string and arguments.

Syntax :public PrintWriter format(String format,          Object... args)    Parameters:          format - A format string as described in Format string syntax          args - Arguments referenced by the format specifiers in the format string.   The number of arguments is variable and may be zero.    Returns: This writer    Throws:          IllegalFormatException          NullPointerException 

10. void print(boolean b)

Prints a boolean value.

Syntax :public void print(boolean b)

11. void print(char c)

Prints a character.

Syntax :public void print(char c)

12. void print(char[] s)

Prints an array of characters.

Syntax :public void print(char[] s)

13. void print(double d)

Prints a double-precision floating-point number.

Syntax :public void print(double b)

14. void print(float f)

Prints a floating-point number.

Syntax :public void print(float f)

15. void print(int i)

Prints an integer.

Syntax :public void print(int i)

16. void print(long l)

Prints a long integer.

Syntax :public void print(long l)

17. void print(Object obj)

Prints an object.

Syntax :public void print(Object obj)

18. void print(String s)

Prints a string.

Syntax :public void print(String s)

Example

Java




// Java program to demonstrate PrintWriter
import java.io.*;
import java.util.Locale;
  
// Driver Class
class PrintWriterDemo {
    // Main Function
    public static void main(String[] args)
    {
        String s = "GeeksforGeeks ";
  
        // create a new writer
        PrintWriter out = new PrintWriter(System.out);
        char c[] = { 'G', 'E', 'E', 'K' };
  
        // illustrating print(boolean b) method
        out.print(true);
  
        // illustrating print(int i) method
        out.print(1);
  
        // illustrating print(float f) method
        out.print(4.533f);
  
        // illustrating print(String s) method
        out.print("GeeksforGeeks");
        out.println();
  
        // illustrating print(Object Obj) method
        out.print(out);
        out.println();
  
        // illustrating append(CharSequence csq) method
        out.append("Geek");
        out.println();
  
        // illustrating checkError() method
        out.println(out.checkError());
  
        // illustrating format() method
        out.format(Locale.UK, "This is my % s program", s);
  
        // illustrating flush method
        out.flush();
  
        // illustrating close method
        out.close();
    }
}
 
 

Output

        true14.533GeeksforGeeks          java.io.PrintWriter@1540e19d          Geek          false          This is my GeeksforGeeks program

Next Article: Java.io.PrintWriter class in Java | Set 2



Next Article
Java.io.StringWriter class in Java

N

Nishant Sharma
Improve
Article Tags :
  • Java
  • Java-I/O
Practice Tags :
  • Java

Similar Reads

  • Java.io.PrintWriter class in Java | Set 2
    Java.io.PrintWriter class in Java | Set 1 More methods: PrintWriter printf(Locale l, String format, Object... args) : A convenience method to write a formatted string to this writer using the specified format string and arguments. Syntax :public PrintWriter printf(Locale l, String format, Object...
    7 min read
  • Java.io.Printstream Class in Java | Set 1
    A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the c
    5 min read
  • Java.io.Printstream Class in Java | Set 2
    Java.io.Printstream Class in Java | Set 1More Methods: PrintStream printf(Locale l, String format, Object... args) : A convenience method to write a formatted string to this output stream using the specified format string and arguments. Syntax :public PrintStream printf(Locale l, String format, Obje
    6 min read
  • Java.io.StringWriter class in Java
    Java StringWriter class creates a string from the characters of the String Buffer stream. Methods of the StringWriter class in Java can also be called after closing the Stream as this will raise no IO Exception. Declaration in Java StringWriter Classpublic class StringWriter extends WriterConstructo
    6 min read
  • Java.io.Writer class in Java
    This abstract class for writing to character streams. The only methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.
    4 min read
  • Java.io.ObjectInputStream Class in Java | Set 1
    ObjectInputStream Class deserializes the primitive data and objects previously written by ObjectOutputStream. Both ObjectOutputStream and ObjectInputStream are used as it provides storage for graphs of object.It ensures that the object it is working for, matches the classes of JVM i.e Java Virtual M
    9 min read
  • Java.io.ObjectInputStream Class in Java | Set 2
    Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStrea
    6 min read
  • Java.io.ObjectOutputStream Class in Java | Set 1
    An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. Only objects that support the java.io.Serializable in
    9 min read
  • Java.io.PipedInputStream class in Java
    Pipes in IO provides a link between two threads running in JVM at the same time. So, Pipes are used both as source or destination. PipedInputStream is also piped with PipedOutputStream. So, data can be written using PipedOutputStream and can be written using PipedInputStream.But, using both threads
    5 min read
  • Java.io.OutputStream class in Java
    This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Constructo
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences