JAVA Tutorial



INPUT OUTPUT IN JAVA


Input and Output in Java

In Java, Input and Output (I/O) operations allow us to interact with the outside world by accepting user input and displaying output. These operations are crucial for building interactive programs. In Java, we typically use classes from the java.util and java.io packages to handle I/O operations.

Key Concepts:

  • Input: Accepting data from the user or external sources.
  • Output: Displaying data to the user or sending data to external devices.
  • Java uses streams to perform I/O operations, with byte streams and character streams being the two primary categories.

πŸ’‘ Using Scanner for User Input

Java provides the Scanner class from the java.util package to accept input from the user. The Scanner class makes it easy to read different types of input like integers, strings, and floating-point numbers.

import java.util.Scanner;

public class UserInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine(); // Reading a string

        System.out.print("Enter your age: ");
        int age = scanner.nextInt(); // Reading an integer

        System.out.println("Hello, " + name + ". You are " + age + " years old.");
    }
}
  

βš™οΈ Output with System.out.println()

In Java, System.out.println() is used to output data to the console. It can be used to display messages, variables, and expressions.

public class OutputExample {
    public static void main(String[] args) {
        String message = "Welcome to Java!";
        System.out.println(message); // Output a string
    }
}
  

πŸ“– Formatting Output

You can also format your output in Java using printf() method, which allows you to specify the format for numbers, strings, and other data types.

public class FormatOutput {
    public static void main(String[] args) {
        double price = 9.99;
        System.out.printf("The price of the item is $%.2f\n", price); // Format output to 2 decimal places
    }
}
  

πŸ’‘ Using BufferedReader for Efficient Input

The BufferedReader class is another option for reading input from the user. It is faster and more efficient for reading large amounts of text compared to Scanner.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class BufferedReaderExample {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter your country: ");
        String country = reader.readLine(); // Reading a string

        System.out.println("You live in " + country);
    }
}
  

πŸ“š Java I/O Streams

Java uses streams to handle input and output. There are two main types:

  • Byte Streams: Used for handling raw binary data (e.g., reading and writing files).
  • Character Streams: Used for handling characters (e.g., reading and writing text).

βš™οΈ Reading and Writing Files

You can use FileReader and FileWriter classes to read from and write to files. These classes are part of the java.io package.

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileIOExample {
    public static void main(String[] args) throws IOException {
        // Writing to a file
        FileWriter writer = new FileWriter("example.txt");
        writer.write("Hello, Java File IO!");
        writer.close();

        // Reading from a file
        FileReader reader = new FileReader("example.txt");
        int data = reader.read();
        while (data != -1) {
            System.out.print((char) data); // Displaying the file content
            data = reader.read();
        }
        reader.close();
    }
}
  

πŸ”΄ Handling Exceptions in I/O

I/O operations in Java can throw exceptions. It's important to handle exceptions using try-catch blocks to ensure smooth execution and error handling.

import java.io.FileReader;
import java.io.IOException;

public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("nonexistentfile.txt");
            reader.read();
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
  

πŸ’‘ Key Takeaways

  • Use Scanner for simple user input in console-based applications.
  • Use BufferedReader for efficient input of large text data.
  • Java uses streams for reading and writing dataβ€”byte streams for binary data and character streams for text.
  • Use try-catch blocks to handle exceptions that might occur during I/O operations.

Practice Challenge: Create a Java program that reads user input, writes it to a file, and then reads the content from that file to display it back to the user.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review