Hello guys, if you have learned Java in early 2000 then there is good chance that you must have written your first Java code using System.out.println(). For a long time, I have no idea what that mean but I alway use it to print messages on console. When I started working in Java and preparing for Java certification then I come to know that System is a class and out is an object of PrintStream which has println() method. That was a revelation for me. I also found that Java provides a powerful set of I/O classes for handling various input and output operations. Among these, the PrintStream class stands out as a versatile tool for writing formatted text to output streams. The print(), printf() and println() methods within the PrintStream class, as well as System.out.println(), are particularly useful for printing different types of data to the console or other output destinations.
Overview of PrintStream in Java
The PrintStream class is part of the java.io package and extends the OutputStream class. It provides methods for printing data to various output streams, including files, standard output (console), and more.
The PrintStream class is known for its simplicity and ease of use.
Constructor
The PrintStream class has multiple constructors, but one of the commonly used constructors is:
PrintStream(OutputStream out)
Here, out is the output stream to which data will be printed.
The print() Method
The print method in the PrintStream class is overloaded to accept various data types and print them to the output stream without appending a newline character. It is crucial for formatting output in a controlled and readable manner.
Method Signature
public void print(type x)
Here, type can be any primitive type, an object, or a string.
The println() Method
The println() method in the PrintStream class is similar to print(), but it automatically appends a newline character after printing the specified data. This is particularly useful when you want to separate lines of output.
Method Signature
public void println(type x)
Here, type can be any primitive type, an object, or a string.
15 Examples of PrintStream print and println Methods in Java
Now, let's explore several examples to understand how to use the print and println methods effectively.
Example 1: Printing Strings with print and println
import java.io.*; public class PrintStreamExample1 { public static void main(String[] args) { // Creating a PrintStream object for standard output PrintStream ps = new PrintStream(System.out); // Using print to print without a newline ps.print("Hello, "); ps.print("Java!"); // Using println to print with a newline ps.println(" Welcome to Java!"); // Closing the PrintStream ps.close(); } }
In this example, we create a PrintStream object using System.out as the output stream. We use both print and println to print strings. The print method prints without a newline, while println appends a newline character after printing.
Example 2: Printing Numbers with print and println
import java.io.*; public class PrintStreamExample2 { public static void main(String[] args) { // Creating a PrintStream object for standard output PrintStream ps = new PrintStream(System.out); // Using print to print numbers without a newline ps.print("Number: "); ps.print(42); // Using println to print numbers with a newline ps.println(", PI: "); ps.println(3.14); // Closing the PrintStream ps.close(); } }
This example demonstrates printing numbers using both print and println. The print method is used for part of the output, and the println method is used to start a new line.
Example 3: Printing Formatted Strings with printf and println
import java.io.*; public class PrintStreamExample3 { public static void main(String[] args) { // Creating a PrintStream object for standard output PrintStream ps = new PrintStream(System.out); // Using printf to print a formatted string without a newline ps.printf("Formatted String: %s, Number: %d", "Hello", 42); // Using println to print a formatted string with a newline ps.println(); ps.println("End of Example"); // Closing the PrintStream ps.close(); } }
In this example, we combine printf with print and println to show formatted string printing with and without newlines.
Example 4: Redirecting Output to a File with println
import java.io.*; public class PrintStreamExample4 { public static void main(String[] args) { try { // Creating a PrintStream object for a file PrintStream ps = new PrintStream(new FileOutputStream("output.txt")); // Using println to print to a file with a newline ps.println("This text is redirected to a file."); // Closing the PrintStream ps.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
Here, we redirect output to a file using PrintStream and demonstrate the use of println to automatically append a newline character.
Example 5: Redirecting Standard Error with println
import java.io.*; public class PrintStreamExample5 { public static void main(String[] args) { try { // Creating a PrintStream object for standard error PrintStream ps = new PrintStream(System.err); // Redirecting standard error to a file System.setErr(ps); // Using println to print an error message with a newline System.err.println("This is an error message."); // Restoring standard error System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.err))); // Closing the PrintStream ps.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
In this example, we show how to redirect standard error to a file temporarily using PrintStream and use println to automatically append a newline character.
Example 6: System.out.println for Quick Output
public class SystemOutPrintlnExample { public static void main(String[] args) { // Using System.out.println for quick output System.out.println("Hello, Java!"); } }
The System.out.println method is a quick way to print a line to the console without explicitly creating a PrintStream object. It is commonly used for simple output scenarios.
Example 7: Printing Numbers
import java.io.*; public class PrintStreamExample2 { public static void main(String[] args) { // Creating a PrintStream object for standard output PrintStream ps = new PrintStream(System.out); // Printing integers and floating-point numbers ps.print(42); ps.print(" "); ps.print(3.14); // Closing the PrintStream ps.close(); } }
In this example, we use the print method to print an integer and a floating-point number. Note that we can print different data types in the same line without automatically appending a newline character.
Example 8: Printing Characters
import java.io.*; public class PrintStreamExample3 { public static void main(String[] args) { // Creating a PrintStream object for standard output PrintStream ps = new PrintStream(System.out); // Printing characters ps.print('J'); ps.print('a'); ps.print('v'); ps.print('a'); // Closing the PrintStream ps.close(); } }
Here, we demonstrate how to print individual characters using the print method. Each character is printed consecutively without any separation.
Example 9: Printing Booleans
import java.io.*; public class PrintStreamExample4 { public static void main(String[] args) { // Creating a PrintStream object for standard output PrintStream ps = new PrintStream(System.out); // Printing boolean values ps.print(true); ps.print(" "); ps.print(false); // Closing the PrintStream ps.close(); } }
This example illustrates how to print boolean values using the print() method. The boolean values are printed with a space in between.
Example 10: Printing Formatted Strings
import java.io.*; public class PrintStreamExample5 { public static void main(String[] args) { // Creating a PrintStream object for standard output PrintStream ps = new PrintStream(System.out); // Using printf for formatted string printing ps.printf("Formatted String: %s, Number: %d", "Hello", 42); // Closing the PrintStream ps.close(); } }
In this example, we utilize the printf method of PrintStream to print a formatted string with placeholders. This is similar to the printf method in languages like C.
Example 11: Redirecting Output to a File
import java.io.*; public class PrintStreamExample6 { public static void main(String[] args) { try { // Creating a PrintStream object for a file PrintStream ps = new PrintStream(new FileOutputStream("output.txt")); // Redirecting output to a file ps.print("This text is redirected to a file."); // Closing the PrintStream ps.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
This example demonstrates how to redirect output to a file using the PrintStream class. We create a PrintStream object with a FileOutputStream as the output stream.
Example 12: Printing New Line Characters
import java.io.*; public class PrintStreamExample7 { public static void main(String[] args) { // Creating a PrintStream object for standard output PrintStream ps = new PrintStream(System.out); // Printing strings with newline characters ps.print("Line 1"); ps.print("\n"); ps.print("Line 2"); // Closing the PrintStream ps.close(); } }
In this example, we show how to print strings on separate lines by explicitly using the newline character (\n).
Example 13: Printing Objects
Now, let's see one example of how to print objects in Java:
import java.io.*; class Student { String name; Student(String name) { this.name = name; } } public class PrintStreamExample8 { public static void main(String[] args) { // Creating a PrintStream object for standard output PrintStream ps = new PrintStream(System.out); // Printing objects Student student = new Student("John Doe"); ps.print(student); // Closing the PrintStream ps.close(); } }
Here, we demonstrate printing custom objects using the print method. The toString() method of the object is implicitly called.
Example 14: Printing Multiple Types in a Single Line
import java.io.*; public class PrintStreamExample9 { public static void main(String[] args) { // Creating a PrintStream object for standard output PrintStream ps = new PrintStream(System.out); // Printing multiple types in a single line ps.print("Number: "); ps.print(42); ps.print(", PI: "); ps.print(3.14); // Closing the PrintStream ps.close(); } }
In this example, we combine different data types in a single line by using the print() method multiple times.
Example 15: Redirecting Standard Error
import java.io.*; public class PrintStreamExample10 { public static void main(String[] args) { try { // Creating a PrintStream object for standard error PrintStream ps = new PrintStream(System.err); // Redirecting standard error to a file System.setErr(ps); // Printing an error message System.err.print("This is an error message."); // Restoring standard error System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.err))); // Closing the PrintStream ps.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
In this example, we redirect standard error to a file temporarily using the PrintStream class.
Conclusion
That's all about how to use print() and println() method of PrintStream class in Java. Mastering the PrintStream class and its print() and println() methods, as well as understanding System.out.println(), empowers Java developers to produce well-formatted and readable output in a variety of contexts.
Whether you are printing basic data types, formatted strings, or redirecting output, these tools provide a range of functionalities to meet your needs. Incorporate these methods into your Java programs to enhance the clarity and presentation of your output.
- 10 Frameworks Java developers should learn
- 10 Example of ConcurrentHashMap in Java
- Difference between HashMap and ArrayList in Java
- 7 Best Courses to learn Java Collections and Stream API
- When to use Map, List, and Set collection in Java
- Difference between IdentityHashMap and HashMap in Java
- Difference between HashMap and HashSet in Java
- 8 Best Java Functional Programming Courses
- 21 skills Java Programmer Should Learn
- 21 Java HashMap Interview Questions with Answers
- 50+ Java Collection Interview Questions with Answers
- 10 Advanced Core Java Courses for Programmers
- Top 5 Courses to become a Fullstack Java Developer
No comments:
Post a Comment