CS Engineering Gyan

Input & Output in Java

Almost every real-world program needs to interact with its user in some way, whether that means displaying results on the screen or accepting information typed by the person using it. In Java, this interaction is handled through input and output operations, commonly referred to as I/O.

Java offers several built-in tools for handling input and output, ranging from simple console printing to more advanced classes designed for reading user-entered data. Learning how these tools work is an important step toward building interactive programs rather than ones that only display fixed, unchanging output.

In this tutorial, you will learn how to display output using different methods, how to accept user input using the Scanner class, and how to format output neatly for better readability.


Output in Java

Displaying output is one of the most basic and frequently used operations in any Java program. Java provides the System.out object, which includes several methods for printing information to the console.

Method Description
System.out.print() Displays output without moving to a new line afterward.
System.out.println() Displays output and then moves the cursor to a new line.
System.out.printf() Displays formatted output using placeholders for values.

Example

public class OutputExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        System.out.print("Welcome to ");

        System.out.println(channel);

        System.out.println("Learn Java the simple way!");

    }

}

Output

Welcome to CS Engineering Gyan

Learn Java the simple way!

Notice how print() keeps the cursor on the same line, while println() automatically moves to a new line after displaying its content. Choosing the right method depends on how you want your output arranged on the screen.


Taking Input Using the Scanner Class

To accept input from the user, Java provides the Scanner class, which is part of the java.util package. This class allows a program to pause and wait for the user to type a value before continuing execution.

Syntax

import java.util.Scanner;

Scanner scannerName = new Scanner(System.in);

Once a Scanner object is created, it provides several methods for reading different types of data entered by the user.

Method Description
nextInt() Reads an integer value entered by the user.
nextDouble() Reads a decimal value entered by the user.
nextLine() Reads a full line of text, including spaces.
next() Reads a single word, stopping at the first space.

Example

import java.util.Scanner;

public class InputExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter your favorite channel name:");

        String favoriteChannel = scanner.nextLine();

        System.out.println("You subscribed to: " + favoriteChannel);

    }

}

Sample Output

Enter your favorite channel name:

CS Engineering Gyan

You subscribed to: CS Engineering Gyan

The program pauses at the nextLine() statement until the user types something and presses enter, after which execution continues with the entered value stored inside the variable.


Reading Multiple Values from the User

Real-world programs often need to collect more than one piece of information from the user. The Scanner class makes this possible by allowing multiple input statements within the same program.

Example

import java.util.Scanner;

public class MultipleInputExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter channel name:");

        String channel = scanner.nextLine();

        System.out.println("Enter subscriber count:");

        int subscribers = scanner.nextInt();

        System.out.println(channel + " has " + subscribers + " subscribers.");

    }

}

Sample Output

Enter channel name:

CS Engineering Gyan

Enter subscriber count:

52000

CS Engineering Gyan has 52000 subscribers.

When mixing nextInt() or nextDouble() with nextLine(), developers sometimes encounter unexpected skipped input, since numeric methods do not consume the newline character left behind after the number is entered. Being aware of this behavior helps avoid confusion while debugging.


Formatted Output Using printf()

The printf() method allows you to display output in a specific format using placeholders, which is especially useful when working with numbers that need consistent alignment or decimal precision.

Format Specifier Description
%d Used for formatting integer values.
%f Used for formatting decimal (floating-point) values.
%s Used for formatting string values.
%n Inserts a new line in a platform-independent way.

Example

public class FormattedOutputExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int totalVideos = 85;

        double averageRating = 4.8;

        System.out.printf("Channel: %s%n", channel);

        System.out.printf("Total Videos: %d%n", totalVideos);

        System.out.printf("Average Rating: %.1f%n", averageRating);

    }

}

Output

Channel: CS Engineering Gyan

Total Videos: 85

Average Rating: 4.8

The %.1f specifier controls how many digits appear after the decimal point, making printf() particularly useful when displaying prices, ratings, or percentages that require consistent formatting.


Using BufferedReader for Input

While the Scanner class is the most common choice for beginners, Java also provides the BufferedReader class, which can read input more efficiently in certain situations, especially when handling large amounts of text.

Example

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.println("Enter channel name:");

        String channel = reader.readLine();

        System.out.println("Channel entered: " + channel);

    }

}

Sample Output

Enter channel name:

CS Engineering Gyan

Channel entered: CS Engineering Gyan

Unlike Scanner, BufferedReader requires handling a potential IOException, since reading input this way can technically fail due to input stream errors. For most beginner-level programs, however, Scanner remains simpler and easier to use.


Scanner vs BufferedReader

Scanner BufferedReader
Simple to use and beginner-friendly. Slightly more complex but offers better performance for large input.
Provides built-in methods for reading different data types directly. Reads input as text, requiring manual conversion for other data types.
Does not require exception handling for basic use. Requires handling IOException while reading input.

Best Practices for Input and Output


Common Mistakes Beginners Make

Mistake Correct Practice
Forgetting to import the Scanner class before using it. Always add import java.util.Scanner; at the top of the file.
Mixing nextInt() and nextLine() without handling the leftover newline. Add an extra nextLine() call after nextInt() if a line read is needed next.
Using print() when a new line is expected after output. Use println() whenever output should end with a line break.
Ignoring IOException while using BufferedReader. Handle the exception properly using a try-catch block or a throws declaration.

Frequently Asked Interview Questions

  1. What is the difference between print() and println() in Java?
    print() stays on the same line, while println() moves to a new line after output.
  2. Which package must be imported to use the Scanner class?
    The java.util package must be imported to use Scanner.
  3. What is the difference between next() and nextLine() in Scanner?
    next() reads a single word, while nextLine() reads an entire line including spaces.
  4. Why does nextInt() sometimes cause issues when followed by nextLine()?
    nextInt() leaves behind a newline character that nextLine() then reads as an empty input.
  5. What is the purpose of the printf() method?
    printf() displays output in a specific, controlled format using placeholders.
  6. What does the %.1f format specifier do?
    It displays a decimal number rounded to one digit after the decimal point.
  7. What is BufferedReader used for in Java?
    BufferedReader is used to read text input efficiently, especially for larger amounts of data.
  8. Why does BufferedReader require exception handling?
    Because reading input through a stream can throw an IOException if an error occurs.

Summary

Input and output operations allow Java programs to communicate with the people using them, turning static code into interactive applications. Using System.out methods, developers can display results clearly, while the Scanner class makes it simple to accept and process information typed by the user.

By also learning about formatted output with printf() and understanding alternatives like BufferedReader, you gain the flexibility to handle input and output in a way that best suits your program's needs. With these skills in place, you are ready to move on to conditional statements, which allow your programs to make decisions based on the data they receive.


← Previous: Operators in Java Next: Conditional Statements →

Home Visit Our YouTube Channel