Java Input / Output
What Is I/O in Java?
In Java, Input and Output (I/O) refers to how a program interacts with the outside world. Input means receiving data — like reading from the keyboard or a file. Output means sending data — like printing to the screen or writing into a file.
Java provides built-in classes in the java.util and java.io packages to make I/O operations simple and efficient.
Taking User Input with Scanner
To read input from the keyboard, Java uses the Scanner class from the java.util package.
Steps to Use Scanner
Import the Scanner class
Create a Scanner object
Use Scanner methods to read input
import java.util.Scanner; Scanner sc = new Scanner(System.in); int age = sc.nextInt(); String name = sc.nextLine(); float marks = sc.nextFloat();
Example: Add Two Numbers
import java.util.Scanner;
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
int sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}Enter first number: 10 Enter second number: 20 Sum: 30
Common Scanner Methods
Method | Description |
next() | Reads a single word |
nextLine() | Reads a full line of text |
nextInt() | Reads an integer |
nextFloat() | Reads a float number |
nextDouble() | Reads a double number |
nextBoolean() | Reads true/false |
nextLong() | Reads a long integer |
nextByte() | Reads a byte value |
Displaying Output with System.out
Java uses the System.out object to print output to the console.
Method | Description |
System.out.print() | Prints text on the same line |
System.out.println() | Prints text and moves to next line |
System.out.printf() | Prints formatted text |
Example: Console Output
public class OutputExample {
public static void main(String[] args) {
System.out.print("Hello ");
System.out.println("World!");
System.out.printf("Pi is approximately: %.2f", 3.14159);
}
}Hello World! Pi is approximately: 3.14
Writing Output to a File
To save data into a file, Java provides the FileWriter class from the java.io package.
Example: Write to File
import java.io.FileWriter;
import java.io.IOException;
public class FileOutput {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("This text will be saved in a file.");
writer.close();
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}File written successfully.
Summary
Concept | Description | Example Tool |
Input | Getting data from user or file | Scanner, FileReader |
Output | Showing data or saving to file | System.out, FileWriter |
Keyboard Input | Typing in terminal | Scanner(System.in) |
Console Output | Displaying on screen | System.out.println() |
File I/O | Reading/writing files | FileReader, FileWriter |