Popular Searches
Popular Course Categories
Popular Courses

Introduction to Java Input and Output

Introduction to Java Input and Output

File Handling, I/O Streams, and Serialization

Introduction to Java Input and Output

Course: Core Java Training

Topic: Introduction to Java Input and Output

Course URL: Core Java Training Course

Demo URL: Register for Course Demo

Website: JustAcademy


1. Introduction to Java Input and Output

Java Input and Output (I/O) refers to the process of receiving information from a source and presenting or transferring information to a destination. Input allows a Java program to accept data from users, files, or other systems. Output allows the program to display results on the console, save information to files, or send data to external destinations.

Java provides several classes and packages for performing I/O operations, including the Scanner class, standard input and output streams, the java.io package, and the java.nio.file package.

Learning Objectives

  • Understand the fundamentals of Java input and output.
  • Learn how to accept input from the keyboard.
  • Display information using Java output methods.
  • Understand standard input, output, and error streams.
  • Explore byte streams and character streams.
  • Read and write files using Java.
  • Handle input/output exceptions.
  • Apply Java I/O concepts through practical programs.

2. What Is Input in Java?

Input is the process of receiving data from an external source so that a program can process it. In beginner-level Java programs, input commonly comes from the keyboard.

Examples of Input

  • Entering a student's name and roll number.
  • Providing two numbers for a mathematical calculation.
  • Entering employee salary information.
  • Reading text from a file.
  • Receiving information from another application or network connection.

Example: Taking User Input

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("Name: " + name);
        System.out.println("Age: " + age);

        sc.close();
    }
}

Explanation

  • import java.util.Scanner; imports the Scanner class.
  • Scanner sc = new Scanner(System.in); creates a scanner that reads standard input.
  • nextLine() reads a complete line of text.
  • nextInt() reads an integer value.
  • System.out.println() displays the entered information.
  • close() closes the scanner and its underlying input source.

Important: Closing a Scanner created with System.in also closes standard input. In larger applications, avoid closing it if other parts of the program still need to read keyboard input.


3. What Is Output in Java?

Output is the process of displaying or transferring information generated by a program. Java supports console output, file output, and output to other data destinations.

Common Output Methods

Method Description Example
print() Displays content without automatically moving to a new line. System.out.print("Hello");
println() Displays content and moves to a new line. System.out.println("Hello");
printf() Displays formatted output. System.out.printf("Age: %d", 20);

Example: Displaying Output

public class OutputExample {
    public static void main(String[] args) {
        String name = "Amit";
        int age = 25;
        double salary = 35000.75;

        System.out.println("Employee Details");
        System.out.print("Name: ");
        System.out.println(name);

        System.out.printf("Age: %d%n", age);
        System.out.printf("Salary: %.2f%n", salary);
    }
}

Expected Output

Employee Details
Name: Amit
Age: 25
Salary: 35000.75

Common Formatting Symbols

Symbol Purpose Example
%d Integer printf("%d", 10);
%f Floating-point value printf("%f", 12.5);
%.2f Two digits after the decimal point printf("%.2f", 12.567);
%s String printf("%s", "Java");
%c Character printf("%c", 'A');
%n Platform-specific line separator printf("Hello%n");
%% Literal percent sign printf("90%%");

4. Understanding System.in, System.out, and System.err

The Java System class provides three standard streams that support common console input and output operations.

Stream Purpose Java Type
System.in Receives standard input, usually from the keyboard. InputStream
System.out Displays normal output. PrintStream
System.err Displays error messages and diagnostic information. PrintStream

Example

public class StandardStreamsExample {
    public static void main(String[] args) {
        System.out.println("Program started successfully.");
        System.err.println("This is an example error message.");
    }
}

Explanation: The first statement writes a normal message to standard output. The second writes a diagnostic message to standard error. Both streams may appear in the same console depending on the development environment.


5. Taking Input Using the Scanner Class

The Scanner class belongs to the java.util package. It provides convenient methods for reading strings, integers, decimal numbers, Boolean values, and other input tokens.

Important Scanner Methods

Method Purpose Example
next() Reads the next token, generally stopping at whitespace. sc.next()
nextLine() Reads the remaining text on the current line. sc.nextLine()
nextInt() Reads an integer. sc.nextInt()
nextDouble() Reads a double-precision number. sc.nextDouble()
nextFloat() Reads a floating-point number. sc.nextFloat()
nextLong() Reads a long integer. sc.nextLong()
nextBoolean() Reads a Boolean value. sc.nextBoolean()
hasNextInt() Checks whether the next token can be interpreted as an integer. sc.hasNextInt()

Example: Reading Multiple Values

import java.util.Scanner;

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

        System.out.print("Enter student name: ");
        String name = sc.nextLine();

        System.out.print("Enter roll number: ");
        int rollNumber = sc.nextInt();

        System.out.print("Enter percentage: ");
        double percentage = sc.nextDouble();

        System.out.println("\nStudent Details");
        System.out.println("Name: " + name);
        System.out.println("Roll Number: " + rollNumber);
        System.out.println("Percentage: " + percentage);

        sc.close();
    }
}

Handling the nextInt() and nextLine() Issue

Methods such as nextInt() and nextDouble() read a token but usually leave the line separator unread. Calling nextLine() immediately afterward may consume the remaining part of that same line instead of waiting for new input.

System.out.print("Enter age: ");
int age = sc.nextInt();
sc.nextLine(); // Consume the remaining line

System.out.print("Enter city: ");
String city = sc.nextLine();

System.out.println("Age: " + age);
System.out.println("City: " + city);

Consuming the remaining line before requesting a complete line helps prevent unexpected empty strings.


6. Using BufferedReader for Input

BufferedReader is a class used to read text efficiently. It is commonly combined with InputStreamReader to receive keyboard input as characters.

Example

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

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

        System.out.print("Enter your city: ");
        String city = br.readLine();

        System.out.println("Your city is " + city);
    }
}

Advantages of BufferedReader

  • Reads text line by line.
  • Uses buffering to reduce repeated low-level read operations.
  • Works well for processing large amounts of text input.
  • Provides the convenient readLine() method.

Scanner vs BufferedReader

Feature Scanner BufferedReader
Input handling Reads tokens and lines. Reads characters and lines.
Numeric input Provides methods such as nextInt(). Usually requires parsing text into numbers.
Ease of use Beginner-friendly for mixed data types. Simple for line-based text input.
Performance Parsing features can add overhead. Often suitable for high-volume text input.
Exception handling May throw scanning or input mismatch exceptions. Read operations may throw IOException.

7. Introduction to Java I/O Streams

A stream represents a flow of data between a source and a destination. Java's traditional I/O functionality is provided mainly through the java.io package.

7.1 Byte Streams

Byte streams process raw bytes and are useful for binary files such as images, audio files, PDFs, and other non-text data.

  • InputStream – base class for reading bytes.
  • OutputStream – base class for writing bytes.
  • FileInputStream – reads bytes from a file.
  • FileOutputStream – writes bytes to a file.
  • BufferedInputStream – buffers byte input.
  • BufferedOutputStream – buffers byte output.

7.2 Character Streams

Character streams are designed for text data. They work with characters and use character encoding and decoding when converting between bytes and text.

  • Reader – base class for reading characters.
  • Writer – base class for writing characters.
  • FileReader – reads text from a file.
  • FileWriter – writes text to a file.
  • BufferedReader – supports buffered text reading.
  • BufferedWriter – supports buffered text writing.

Byte Streams vs Character Streams

Feature Byte Streams Character Streams
Data type Raw bytes Text characters
Base classes InputStream, OutputStream Reader, Writer
Common applications Binary files and raw data Text files and textual content
Encoding Does not automatically interpret text encoding Supports character conversion where required

8. Writing Data to a File

Java supports file output through classes such as FileWriter and BufferedWriter. File writing is useful for saving reports, logs, configuration details, and user-generated information.

Example: Writing Text to a File

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteExample {
    public static void main(String[] args) {
        try (BufferedWriter writer =
                 new BufferedWriter(new FileWriter("message.txt"))) {

            writer.write("Welcome to Java Input and Output.");
            writer.newLine();
            writer.write("This text is saved in a file.");

            System.out.println("File written successfully.");

        } catch (IOException e) {
            System.err.println("Unable to write file: " + e.getMessage());
        }
    }
}

Explanation

  • FileWriter opens the file for text output.
  • BufferedWriter buffers text to improve writing efficiency.
  • write() writes characters to the file.
  • newLine() inserts a line separator.
  • Try-with-resources automatically closes the writer.
  • catch handles an I/O failure.

Important: This example replaces existing file contents by default. The file is created relative to the program's working directory unless another path is provided.


9. Reading Data from a File

File input allows a Java application to retrieve previously saved information. Text files can be read using BufferedReader and FileReader.

Example: Reading a Text File

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

public class FileReadExample {
    public static void main(String[] args) {
        try (BufferedReader reader =
                 new BufferedReader(new FileReader("message.txt"))) {

            String line;

            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            System.err.println("Unable to read file: " + e.getMessage());
        }
    }
}

Explanation

  • FileReader opens the text file.
  • BufferedReader supports efficient line-by-line reading.
  • readLine() returns the next line of text.
  • It returns null when the end of the file is reached.
  • The loop displays each line until the file ends.
  • Try-with-resources closes the reader automatically.

For applications requiring a specific character encoding, use modern file APIs such as Files.newBufferedReader() with StandardCharsets.UTF_8.


10. Introduction to Java NIO Files API

The java.nio.file package provides modern tools for working with files and directories. The Path and Files classes simplify common file operations and allow explicit character encoding.

Example: Writing and Reading Text

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class NIOExample {
    public static void main(String[] args) {
        Path path = Path.of("notes.txt");

        try {
            Files.writeString(
                path,
                "Learning Java Input and Output",
                StandardCharsets.UTF_8
            );

            String content = Files.readString(
                path,
                StandardCharsets.UTF_8
            );

            System.out.println(content);

        } catch (IOException e) {
            System.err.println("File operation failed: " + e.getMessage());
        }
    }
}

Note: Path.of(), Files.writeString(), and Files.readString() are available in Java 11 and later. For older versions, use compatible alternatives such as Paths.get() and buffered readers or writers.


11. Exception Handling in Java I/O

I/O operations may fail because a file is missing, permissions are insufficient, the input is invalid, or a device becomes unavailable. Java uses exceptions to report these problems.

Exception Description Example
IOException General input/output failure. A file operation fails.
FileNotFoundException A file cannot be opened as requested. The specified file does not exist or cannot be accessed.
InputMismatchException Input does not match the expected type. Text is entered when an integer is expected.
NoSuchElementException The requested input is unavailable. A scanner attempts to read a token when none remains.
NumberFormatException Text cannot be converted to the required numeric format. Integer.parseInt("abc")

Example: Handling Invalid Input

import java.util.InputMismatchException;
import java.util.Scanner;

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

        try {
            System.out.print("Enter an integer: ");
            int number = sc.nextInt();

            System.out.println("You entered: " + number);

        } catch (InputMismatchException e) {
            System.err.println("Invalid input. Please enter an integer.");
        } finally {
            sc.close();
        }
    }
}

The try block contains the operation that might fail. The catch block handles invalid input, while finally executes as control leaves the structure. Because this example closes System.in, avoid the same approach when other parts of the application need standard input afterward.


12. Best Practices for Java Input and Output

  • Choose an input method that suits the application's requirements.
  • Validate user input before using it in calculations or business logic.
  • Use hasNextInt() or appropriate parsing and validation for uncertain input.
  • Use byte streams for raw binary data and character streams for text.
  • Specify a character encoding, such as UTF-8, when reading or writing text files where encoding matters.
  • Use try-with-resources to close readers, writers, and other closeable resources.
  • Handle exceptions with clear and useful error messages.
  • Avoid closing shared streams such as System.in unnecessarily.
  • Use buffered I/O where it improves performance.
  • Use Path and Files for convenient modern file operations.
  • Understand whether a file-writing operation replaces existing content or appends to it.
  • Check file paths and permissions when file operations fail.

13. Common Mistakes and Troubleshooting

Problem Possible Cause Solution
nextLine() returns an empty string unexpectedly. A previous token-based method left the line separator unread. Consume the remaining line before reading the next full line.
Input causes an exception. The supplied value does not match the expected data type. Validate the input or handle the appropriate exception.
A file cannot be found. The path or working directory is incorrect. Check the file path and confirm that the file exists.
Existing file contents disappear. The output API replaces file contents by default. Enable append mode when appending is required.
Text displays incorrectly. The file was decoded using an incompatible character encoding. Use a consistent encoding, such as UTF-8.
Resources remain open. A reader or writer was not closed. Use try-with-resources.

Example: Appending Text to a File

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class AppendFileExample {
    public static void main(String[] args) {
        try (BufferedWriter writer =
                 new BufferedWriter(new FileWriter("message.txt", true))) {

            writer.newLine();
            writer.write("This line is appended.");

            System.out.println("Text appended successfully.");

        } catch (IOException e) {
            System.err.println("Unable to append text: " + e.getMessage());
        }
    }
}

The second argument true enables append mode for FileWriter. New text is added to the existing file rather than replacing its contents.


14. Practical Project: Student Information Program

This practical program accepts a student's name, age, and marks, then displays a formatted summary and determines whether the student has passed.

import java.util.Scanner;

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

        System.out.print("Enter student name: ");
        String name = sc.nextLine();

        System.out.print("Enter student age: ");
        int age = sc.nextInt();

        System.out.print("Enter marks: ");
        double marks = sc.nextDouble();

        System.out.println("\n----- Student Summary -----");
        System.out.printf("Name: %s%n", name);
        System.out.printf("Age: %d%n", age);
        System.out.printf("Marks: %.2f%n", marks);

        if (marks >= 40) {
            System.out.println("Result: Pass");
        } else {
            System.out.println("Result: Fail");
        }

        sc.close();
    }
}

Sample Output

Enter student name: Priya Sharma
Enter student age: 20
Enter marks: 78.5

----- Student Summary -----
Name: Priya Sharma
Age: 20
Marks: 78.50
Result: Pass

Concepts Covered

  • Accepting text using nextLine().
  • Reading integers and decimal values.
  • Displaying formatted output using printf().
  • Using conditional statements to determine a result.
  • Combining input, processing, and output in one application.

15. Practice Exercises

  1. Personal Introduction: Accept a user's name, age, and city, then print a formatted introduction.
  2. Simple Calculator: Read two numbers and display their sum, difference, product, and quotient. Handle division by zero.
  3. Employee Salary: Accept an employee's name and salary, calculate a bonus, and display the final salary.
  4. File Writing: Ask the user for a message and save it in a text file.
  5. File Reading: Read a text file line by line and display its contents.
  6. Input Validation: Modify a program to handle invalid numeric input without terminating unexpectedly.
  7. Student Report: Accept student details and marks, calculate the average, and display a formatted report.

16. Java Input and Output Interview Questions

Q1. What is input and output in Java?

Answer: Input receives data from a source, while output displays or transfers processed information to a destination.

Q2. What is the Scanner class?

Answer: Scanner is a class in java.util that reads and parses tokens and lines from sources such as keyboard input and files.

Q3. What is the difference between print() and println()?

Answer: print() displays content without automatically adding a line separator. println() displays content and then moves to a new line.

Q4. What is System.in?

Answer: System.in is the standard input stream, commonly used to receive keyboard input.

Q5. What is the difference between byte streams and character streams?

Answer: Byte streams process raw bytes and are suitable for binary data. Character streams are designed for text and support character encoding and decoding where needed.

Q6. What is BufferedReader?

Answer: BufferedReader reads text efficiently using buffering and provides the readLine() method.

Q7. What is IOException?

Answer: IOException is a checked exception representing certain failures during input and output operations.

Q8. Why should I/O resources be closed?

Answer: Closing resources releases system and application resources. Try-with-resources automates this process for resources that implement AutoCloseable.

Q9. What is the difference between FileReader and FileInputStream?

Answer: FileReader is intended for reading text characters, while FileInputStream reads raw bytes and is suitable for binary data.

Q10. What is System.err?

Answer: System.err is the standard error stream, commonly used for error messages and diagnostic information.

Q11. What is try-with-resources?

Answer: It is a Java language feature that automatically closes declared resources when the try block finishes.

Q12. How can Java read a text file?

Answer: Java can read text files using BufferedReader, FileReader, or modern methods such as Files.readString(), depending on the Java version and requirements.


17. Quick Revision Checklist

  • Input receives information; output displays or transfers information.
  • Scanner provides convenient methods for reading different data types.
  • System.in is used for standard input.
  • System.out displays normal output.
  • System.err displays diagnostic messages.
  • print(), println(), and printf() provide different output formats.
  • Byte streams handle raw binary data.
  • Character streams are designed for text processing.
  • BufferedReader supports efficient line-based reading.
  • FileWriter and BufferedWriter can write text files.
  • Path and Files provide modern file operations.
  • Exceptions should be handled appropriately and resources should be closed.

18. Conclusion

Java Input and Output is a fundamental concept that allows applications to interact with users, files, and external systems. Beginners should first learn keyboard input using Scanner and console output using System.out. They can then progress to streams, file operations, character encoding, and exception handling.

Regular practice with small programs helps learners build reliable Java applications and prepares them for advanced topics such as file processing, data serialization, networking, and enterprise application development.


Learn Core Java with JustAcademy

Explore the Core Java Training Course to strengthen your Java programming fundamentals.

Register for a Course Demo to learn more about the training and available learning opportunities.

Visit the JustAcademy website to explore additional courses.

Previous Next
whatsapp