Introduction
Input and Output (I/O) in Java are essential concepts that allow a program to interact with the user, files, and other data sources. Input means taking data from the user or another source, while output means displaying or sending data. Java provides several ways to handle I/O operations efficiently and securely.
Types of Input and Output in Java
Java supports two main types of I/O operations:
-
Console I/O – Using the keyboard for input and the screen for output.
-
File I/O – Reading from and writing to files.
1. Console Input and Output
a. Output using System.out.print() and System.out.println()
The simplest way to display output in Java is by using the System.out object.
Example:
public class OutputExample {
public static void main(String[] args) {
System.out.println("Hello, Java!");
System.out.print("This is printed on the same line.");
}
}
Output:
Hello, Java!
This is printed on the same line.
-
System.out.println()prints text and moves to a new line. -
System.out.print()prints text without moving to a new line.
b. Input using Scanner Class
The Scanner class (from java.util package) is the most common way to take input from users.
Example:
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.println("Hello " + name + ", you are " + age + " years old.");
sc.close();
}
}
Explanation:
-
nextLine()– reads a string (entire line). -
nextInt()– reads an integer. -
Always close the
Scannerusingsc.close()after use.
2. File Input and Output
Java’s FileReader, BufferedReader, FileWriter, and BufferedWriter classes help in reading and writing files.
Example: Writing to a File
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, this is written to a file!");
writer.close();
System.out.println("Successfully written to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}
Example: Reading from a File
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("output.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading file.");
}
}
}
Conclusion
Input and Output in Java form the backbone of any interactive application. The Scanner class simplifies console input, while file-handling classes make reading and writing data easy. By mastering Java I/O, you can build programs that efficiently handle data from users and files.
Comments
Post a Comment