Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Printing is a crucial aspect of programming that lets programmers display information on the screen, which makes it an indispensable tool for debugging, user interaction, and outputting results. Java, being one of the most widely used programming languages, offers several printing methods, each with its unique characteristics and use cases. Without printing, every code is incomplete, and the user won't be able to interact with the final program.
In this article, we'll learn the different approaches to printing in Java, which are the print(), println(), & printf() methods. We'll also discuss the overloads of the println() method, the differences between System.out.print() & System.out.println(), and will finally analyze their performance.
print() Method
The print() method in Java displays text or other data on the console without adding a new line at the end. It belongs to the PrintStream class & is commonly used with System.out, representing the standard output stream.
The syntax of the print() method is:
System.out.print("Hello, world!");
In this example, the text "Hello, world!" will be printed on the console, & the cursor will remain on the same line after printing. You can use the print() method to display variables, literals, or any other data type. For instance:
public class Main {
public static void main(String[] args) {
int age = 25;
System.out.print("My age is: ");
System.out.print(age);
}
}
You can also try this code with Online Java Compiler
Note: Always remember that the cursor will stay on the same line after printing the age variable. The print() method is very useful when you want to display multiple items on the same line or when you need to build a string of text incrementally.
println() Method
The println() method is similar to the print() method, but it adds a new line character at the end of the output. This means that after printing the specified text or data, the cursor moves to the beginning of the next line. The println() method is also part of the PrintStream class and is frequently used with System.out.
For example:
public class Main {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println("This is a new line.");
}
}
You can also try this code with Online Java Compiler
As you can see, each call to println() prints the text on a new line. You can use println() with different data types, just like the print() method:
public class Main {
public static void main(String[] args) {
String name = "Rahul";
int age = 30;
System.out.println("My name is " + name + " & I am " + age + " years old.");
}
}
You can also try this code with Online Java Compiler
Note: The println() method is very useful when you want to display information on separate lines or when you need to create a readable output format. It's also commonly used for debugging purposes, as it helps to distinguish different parts of the output clearly
printf() Method
The printf() method is a powerful formatting tool in Java that allows you to print formatted text using format specifiers. It provides more control over the output layout than the print() and println() methods. The printf() method is also a member of the PrintStream class.
The syntax is :
System.out.printf("format string", arguments);
The format string contains plain text and format specifiers, which are special characters that define how the arguments should be formatted. Some common format specifiers are:
- %d for integers
- %f for floating-point numbers
- %s for strings
- %c for characters
For example:
public class Main {
public static void main(String[] args) {
String name = "Sinki";
int age = 25;
double score = 91.5;
System.out.printf("My name is %s, I am %d years old, & my score is %.2f%%.\n", name, age, score);
}
}
You can also try this code with Online Java Compiler
In this example, the format specifiers %s, %d, & %.2f are used to represent a string, an integer, & a floating-point number with 2 decimal places, respectively. The %% is used to print a literal % symbol. The \n at the end is an escape sequence that adds a new line character.
The output will be:
My name is Sinki, I am 25 years old, & my score is 91.50%.
Note: The printf() method is useful when you need to format numerical data, align text, or create tabular output. It offers a wide range of formatting options, like specifying the width, precision, and justification of the output.
Overloads of println() method
The println() method in Java comes with several overloaded versions that allow you to print different data types. These overloads provide convenience & flexibility whenever you are working with various types of data.
The available overloads of the println() method are:
1. println(): This overload prints an empty line, effectively adding a new line character to the output.
2. println(boolean x): Prints a boolean value (true or false) followed by a new line.
3. println(char x): Prints a character followed by a new line.
4. println(char[] x): Prints an array of characters followed by a new line.
5. println(double x): Prints a double value followed by a new line.
6. println(float x): Prints a float value followed by a new line.
7. println(int x): Prints an integer value followed by a new line.
8. println(long x): Prints a long value followed by a new line.
9. println(Object x): Prints an object's string representation (by calling its toString() method) followed by a new line.
10. println(String x): Prints a string followed by a new line.
For example:
public class Main {
public static void main(String[] args) {
boolean isTrue = true;
System.out.println(isTrue);
char ch = 'A';
System.out.println(ch);
int num = 42;
System.out.println(num);
String str = "Hello, World!";
System.out.println(str);
}
}
You can also try this code with Online Java Compiler
Note: These overloads make it easier to print different types of data without explicitly converting them to strings. The println() method automatically calls the appropriate overload based on the data type of the argument passed to it.
Difference between System.out.print() and System.out.println()
System.out.print()
System.out.println()
The print() method prints the specified text or data without adding a new line character at the end.
The println() method prints the specified text or data & adds a new line character at the end, moving the cursor to the beginning of the next line.
After printing, the cursor remains on the same line, allowing the next print statement to continue from that position.
After printing, the cursor moves to the next line, causing the next print statement to start on a new line.
The print() method is useful when you want to display multiple items on the same line or build a string of text incrementally.
The println() method is helpful when you want to display information on separate lines or create a readable output format.
Example: System.out.println("Hello"); System.out.println("World"); Output: Hello World
The print() method is used when you need to construct a single line of output from multiple parts.
The println() method is used for displaying individual pieces of information or for debugging purposes, as it clearly separates different parts of the output.
Performance Analysis of System.out.println()
When it comes to the performance of System.out.println(), there are a few factors we need to keep in mind. While System.out.println() is convenient and widely used for printing output, it may not always be the most efficient choice, especially when you are dealing with large amounts of data or frequent output operations.
Let’s discuss some performance aspects which we need to keep in mind:
1. I/O operations: System.out.println() performs I/O operations, which can be relatively slow compared to other operations in a program. Each call to println() flushes the output buffer, causing the text to be written to the console. If you have a large number of println() statements, the cumulative I/O overhead can impact the overall performance of your program.
2. String concatenation: When using System.out.println() with string concatenation (e.g., System.out.println("Hello, " + name);), Java creates a new String object for each concatenation operation. If you have multiple concatenations or if you're inside a loop, this can lead to the creation of numerous temporary String objects, which can affect performance & memory usage.
3. Alternatives for better performance: If performance is a critical concern, there are alternative approaches you can consider:
- Using a StringBuilder or StringBuffer to build the output string & then printing it once.
- Employing buffered I/O classes like BufferedWriter or PrintWriter to reduce the number of I/O operations.
- Considering logging frameworks (e.g., Log4j, SLF4J) that provide more efficient & flexible logging capabilities.
For example:
public class PerformanceTest {
public static void main(String[] args) {
long startTime, endTime;
// Using System.out.println() to print each number in a loop
startTime = System.nanoTime(); // Record the start time
for (int i = 0; i < 10000; i++) {
System.out.println("Output: " + i); // Print each number with a newline
}
endTime = System.nanoTime(); // Record the end time
System.out.println("Time taken by System.out.println(): " + (endTime - startTime) + " ns");
// Using StringBuilder to build the entire output first, then print once
StringBuilder sb = new StringBuilder();
startTime = System.nanoTime(); // Record the start time
for (int i = 0; i < 10000; i++) {
sb.append("Output: ").append(i).append("\n"); // Append each number to the StringBuilder
}
System.out.print(sb.toString()); // Print all appended numbers at once
endTime = System.nanoTime(); // Record the end time
System.out.println("Time taken by StringBuilder: " + (endTime - startTime) + " ns");
}
}
You can also try this code with Online Java Compiler
In this example, we compare the performance of printing 10,000 output lines using two different methods in Java. The first method involves using System.out.println() for each line of output, while the second method utilizes a StringBuilder to compile all the output into a single string, which is then printed at once. The StringBuilder method performs better, as it reduces the number of print operations and minimizes the overhead associated with creating numerous temporary string objects and handling multiple I/O operations.
Note: It's important to remember that the performance impact of System.out.println() may not be noticeable or significant in small-scale programs or when the output volume is low. However, if performance is a critical factor in your application, it's always advised to use alternative approaches or optimizing the usage of System.out.println() based on your specific requirements.
Frequently Asked Questions
Can I use System.out.println() to print formatted output?
While System.out.println() is primarily used for simple output, you can use string concatenation or the String.format() method to achieve basic formatting. However, for more advanced formatting options, it's recommended to use the printf() method.
Is it possible to print output to a file instead of the console?
Yes, you can redirect the output of System.out.println() to a file by using the PrintStream class & the FileOutputStream. By creating a new PrintStream object & passing it the FileOutputStream, you can send the output to a file instead of the console.
Can I use System.out.println() in a multithreaded environment?
Yes, System.out.println() can be used in a multithreaded environment. However, keep in mind that the output from multiple threads may interleave, leading to unexpected or mixed-up output. To ensure proper synchronization & avoid such issues, you can use thread-safe logging frameworks or synchronize the access to System.out.
Conclusion
In this article, we discussed the different aspects of printing in Java and focused on the print(), println(), & printf() methods. We learned how to use these methods to display different data types and format the output. Apart from this, we also discussed the overloads of the println() method, the differences between print() and println(), and analyzed the performance related factors when using System.out.println().