Printing in Java
In Java, there are several helpful methods and classes for printing output to the console or other output destinations.
The most popular methods for printing in Java include: System.out.print()
, System.out.println()
, and System.out.printf()
.
In this tutorial, we will cover the use of these methods and see how they can be used to print to the standard output. We will also explore using the PrintStream and PrintWriter classes, which provide a great deal of functionality when it comes to printing in Java.
Printing With System.out.print()
In Java, System.out.print()
is used to print output to the console. It prints directly to the console without a new line. This means that subsequent output will appear on the same line.System.out.print()
is a method that belongs to the java.lang.System
class. It is used for printing text or other data to the standard output stream, which is typically the console or terminal where your Java program is running.
Here’s what System.out.print()
really means, and how it works:
- System:
System
is a built-in class in Java that provides access to various system-related functionalities. This includes input and output streams. - out:
out
is a public static field within theSystem
class, which represents the standard output stream. It is an instance of thePrintStream
class. - print():
print()
is a method of thePrintStream
class. When you callSystem.out.print()
, it calls theprint()
method on theout
object, which prints the specified data to the standard output.
Here’s an example of how we can use System.out.print():
System.out.print("Hello, ");
System.out.print("World!");
Output:
Hello, World!
In this example, “Hello, ” and “World!” are printed on the same line because System.out.print()
doesn’t add a newline character.
If we want to print to a new line, we can manually add a newline character ‘ \n ‘ to our print statement:
Remember that System.out.print()
does not automatically add a newline character, so if you want to start a new line, you need to explicitly use System.out.println()
or add a newline character \n
at the end of your System.out.print()
statement.
System.out.print("Hello, ");
System.out.print("\nWorld!");
Output:
Hello,
World!
Alternatively, we can use System.out.println() to append a new line.
Printing With System.out.println()
System.out.println() allows us to perform two actions at once:
- It prints the statement as would System.out.print().
- It appends a new line at the end of the statement.
The operation of System.out.println() is shown in the following example:
public class ExponentExample {
public static void main(String[] args) {
System.out.println("Hello, ");
System.out.print("World!");
}
}
Output:
Hello,
World!
In this example, I’ve intentionally used println() for the first statement and print() for the second. This highlights the fact that println() essentially appends a newline to the end of its’ statement.
Note the limitation of System.out.println(): it only results in the next (the following) statement being printed to a new line. If we need the current statement to print to a new line, we still need to use a newline character \n.
In practice, however, most of the time developers can just stick to using System.out.println(), ensuring that each print statement appears on a new line.
Printing With System.out.printf()
The System.out.printf() method is very powerful, and gives us different ways to print different kinds of data formats like strings, numbers, dates, times, and more.
This method uses rules to determine the output formatting. Rules start with a percentage character ‘%’.
String name = "Alice";
int age = 30;
System.out.printf("Name: %s, Age: %d%n", name, age);
Output:
Name: Alice, Age: 30
Printing Using the PrintStream Class
The PrintStream
class is part of the java.io
package, and it is actually what is working behind the scenes whenever we use a print() or println() statement. It provides a convenient way to print data to an output stream, such as the console or a file.
PrintStream is commonly used for simple text-based output in Java programs. It’s a subclass of OutputStream
, which means it can be used to write various data types to an output stream.
We often don’t need to use PrintStream explicitly, as we can usually just use System.out.print() statements instead. However, it is educational to understand how this works under the hood. Here’s how we can use the PrintStream
class to print in Java:
- Import the
PrintStream
class: We need to import thePrintStream
class from thejava.io
package at the beginning of our Java file:
import java.io.PrintStream;
- Create a
PrintStream
object: We can create aPrintStream
object to represent the output stream where we want to print.
The most common use case is to print to the standard output. We can create aPrintStream
object for the standard output like this:
PrintStream ps = System.out;
Here, System.out
is an instance of PrintStream
representing the standard output stream.
- Use
PrintStream
methods to print: Now we can use various methods provided by thePrintStream
class to print the data. These are identical to the print(), println(), and printf() methods that we’ve already seen. Some of the commonly used methods include:
print(String s)
: Prints without adding a newline character.println(String s)
: Prints and adds a newline character.printf(String format, Object... args)
: Formats and prints a string using the specified format and arguments. Here’s an example of how to usePrintStream
to print to the console:
import java.io.PrintStream;
public class PrintStreamExample {
public static void main(String[] args) {
// Create a PrintStream object for standard output (console)
PrintStream ps = System.out;
// Use the print and println methods to output data
ps.print("Hello, ");
ps.println("PrintStream!");
ps.printf("Formatted output: %d + %d = %d%n", 2, 3, 5);
// Close the stream (not required for System.out)
ps.close();
}
}
- Close the
PrintStream
(if necessary): In the above example, we usedps.close();
to close thePrintStream
.
However, for the standard output (System.out
), closing the stream is not necessary. For other output streams, like files, you should close thePrintStream
to flush any buffered data and release resources.
While this exercise isn’t necessary in most programs, hopefully it provides some additional information about how print statements work under the hood.
Printing Using the PrintWriter Class
The PrintWriter
class in Java is part of the java.io
package. It provides a way to print data to an output stream, such as a file or a network socket.
PrintWriter is often used for more advanced text-based output and is particularly useful for writing data to files with a high-level interface.
Here’s how we can use the PrintWriter
class to print in Java:
- Import the
PrintWriter
class: We need to import thePrintWriter
class from thejava.io
package at the beginning of our Java file:
import java.io.PrintWriter;
- Create a
PrintWriter
object: We can create aPrintWriter
object to represent the output stream where you want to print. For example, to create aPrintWriter
for writing to a file, we can do the following:
try {
PrintWriter writer = new PrintWriter("output.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
In this example, we created a PrintWriter
that writes to a file named “output.txt.” The FileNotFoundException
is caught to handle potential file-related errors.
- Use
PrintWriter
methods to print: We can use various methods provided by thePrintWriter
class to print data, including:
print(String s)
: Prints without adding a newline character.println(String s)
: Prints and adds a newline character.printf(String format, Object... args)
: Formats and prints a string using the specified format and arguments.
Here’s an example of how we can usePrintWriter
to write to a file:
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class PrintWriterExample {
public static void main(String[] args) {
try {
// Create a PrintWriter for writing to a file (example.txt)
PrintWriter pw = new PrintWriter("example.txt");
// Use the print and println methods to write data to the file
pw.print("Hello, ");
pw.println("PrintWriter!");
pw.printf("Formatted output: %d + %d = %d%n", 2, 3, 5);
// Close the PrintWriter to flush and release resources
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
- Close the
PrintWriter
(always required): It’s important to close thePrintWriter
after you’re done with it. Closing thePrintWriter
flushes any buffered data to the output stream, and it releases resources associated with it. This step is essential to ensure data integrity and good resource management.
That’s how you can use thePrintWriter
class to print output in Java, especially when you need to write data to files or other output streams.