Java Input and Output – Complete Guide Using Scanner, BufferedReader, and System.out
Learn how to take input from the user and display output in Java using Scanner, BufferedReader, and System.out.println() with complete examples for beginners.
Input and Output in Java – Complete Detailed Tutorial
Input and output are essential for any Java program. Java provides multiple ways to read data from the user and display results.
1. Output in Java
- Output refers to displaying data to the console.
- Java uses the
System.outclass for output.
1.1 Using System.out.println()
- Prints message with a newline at the end
Example:
Output:
1.2 Using System.out.print()
- Prints message without newline
Output:
1.3 Using System.out.printf()
- Prints formatted output (like C
printf) - Syntax:
Example:
Output:
2. Input in Java
- Input refers to reading data from user
- Common methods:
ScannerandBufferedReader
2.1 Using Scanner Class
- Part of
java.utilpackage - Easy to use for reading primitive data types and strings
Syntax:
Example – Read integer and string:
Sample Output:
2.2 Using BufferedReader Class
- Part of
java.iopackage - More efficient for reading large input
- Needs exception handling
Syntax:
Example – Read string and integer:
3. Differences Between Scanner and BufferedReader
| FeatureScannerBufferedReader | ||
| Package | java.util | java.io |
| Speed | Slower | Faster |
| Exception Handling | No checked exceptions | Requires try-catch or throws IOException |
| Parsing | Can directly parse int, float, etc. | Needs Integer.parseInt() or Double.parseDouble() |
4. Reading Different Data Types with Scanner
| MethodDescription | |
| nextInt() | Read integer |
| nextFloat() | Read float |
| nextDouble() | Read double |
| next() | Read single word (string) |
| nextLine() | Read entire line (string) |
| nextBoolean() | Read boolean |
Example:
5. Example Program – Input and Output
Sample Output:
6. Summary
- Output:
System.out.println(),System.out.print(),System.out.printf() - Input:
Scanner(easy) andBufferedReader(efficient) - Input/output is essential for interactive programs
- Scanner handles primitive types and strings, BufferedReader requires parsing and exception handling