Java Tutorial Series: This lesson is part of our comprehensive Complete Java Tutorial: Learn Java from Beginner to Advanced.

Java Input and Output: Read Input and Display Output

Java input and output allow programs to communicate with users and external data sources. Console I/O is the first step toward files, streams, networking, and application-level data handling.

What You Will Learn

  • System.out
  • System.err
  • Scanner
  • Command-line arguments
  • Formatted output
  • Input validation
  • nextInt and nextLine
  • Resource handling

1. Standard Output

System.out is the standard output stream. println adds a line terminator while print does not automatically do so.

2. Standard Error

System.err.println("Invalid input");

System.err is commonly used for error and diagnostic output.

3. Scanner

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
int age = scanner.nextInt();

Scanner can parse primitive values and strings from input sources. Its default delimiter matches whitespace.

4. Reading Strings

String name = scanner.nextLine();

nextLine reads a complete line.

5. nextInt and nextLine

int age = scanner.nextInt();
scanner.nextLine();
String name = scanner.nextLine();

After nextInt reads a numeric token, the line terminator can remain for nextLine. Consuming the remainder intentionally avoids an unexpected empty read.

6. Command-Line Arguments

public static void main(String[] args) {
    System.out.println(args.length);
}

Arguments supplied at launch are available through the String[] parameter of main.

7. Formatted Output

String name = "Ravi";
double price = 99.5;
System.out.printf("Name: %s, Price: %.2f%n", name, price);

8. Input Validation

Real applications should not assume input is valid. Validate ranges, handle parsing failures, and provide useful feedback.

9. Scanner and Resources

Scanner implements Closeable. Closing a Scanner over System.in also closes the underlying input stream, so close it deliberately when the program no longer needs that stream.

10. Beyond Console I/O

Later Java I/O topics include paths, files, readers, writers, byte and character streams, buffering, and network I/O.

11. Common Mistakes

  • Mixing nextInt and nextLine without understanding line consumption
  • Ignoring invalid input
  • Closing shared input unexpectedly
  • Using console printing where structured logging is appropriate
  • Assuming input always has the expected format

4. Scanner Input in Detail

Scanner provides convenient methods for reading tokens and lines from an input source such as System.in. Common methods include next(), nextInt(), nextLong(), nextDouble(), and nextLine().

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);

Scanner is convenient for beginner programs, command-line utilities, and simple input handling. For larger or performance-sensitive input workloads, other approaches may be more appropriate.

5. nextInt() and nextLine() Pitfall

A common beginner issue occurs when nextInt() is followed by nextLine(). nextInt() reads the integer token but leaves the line terminator in the input buffer, so the following nextLine() can consume the remainder of that line immediately.

int age = scanner.nextInt();
scanner.nextLine(); // consume the remaining line break
String name = scanner.nextLine();

Understanding whether your program is reading tokens or complete lines makes Scanner behavior much easier to predict.

6. Validating User Input

Programs should not assume that users always provide the expected type or format. Scanner provides methods such as hasNextInt() that can be used before reading typed input.

if (scanner.hasNextInt()) {
    int age = scanner.nextInt();
} else {
    System.out.println("Please enter a whole number.");
}

Validation becomes more important when input affects calculations, database operations, files, or external services.

7. Command-Line Arguments

The main method receives command-line arguments through String[] args. These values are useful for simple configuration or scripts.

public static void main(String[] args) {
    if (args.length > 0) {
        System.out.println("First argument: " + args[0]);
    }
}

Command-line arguments arrive as strings. If a numeric value is expected, parse it explicitly and handle invalid input appropriately.

8. Formatted Output

System.out.printf can format output using format specifiers. This is useful when displaying aligned or numeric information.

String name = "Ravi";
double score = 91.5;
System.out.printf("Name: %s, Score: %.1f%n", name, score);

Formatted output can make command-line reports easier to read than a long chain of string concatenations.

9. System.out, System.err and System.in

System.in represents standard input, System.out standard output, and System.err standard error. Separating normal output from diagnostic or error output can help command-line tools and operating environments handle messages appropriately.

System.out.println("Application started");
System.err.println("Configuration file not found");

10. Closing Scanner and Resource Handling

When Scanner wraps System.in, closing the scanner also closes the underlying input stream. That can be appropriate when the application is finished with standard input, but it can be inconvenient if another part of the program still needs System.in.

For resources that should always be closed after use, Java provides try-with-resources. The appropriate resource-management strategy depends on whether the input source is owned by the current method or shared by the application.

11. Input and Output Beyond the Console

Console I/O is only the beginning of Java input and output. Java also provides APIs for files, byte streams, character streams, buffering, and other external data sources. Later learning should connect console I/O to file handling and application-level data processing.

12. Common Input and Output Mistakes

  • Forgetting that Scanner input can contain invalid data.
  • Mixing nextInt() and nextLine() without understanding the remaining line break.
  • Treating command-line arguments as numeric values without parsing them.
  • Closing shared input resources unexpectedly.
  • Using console output as a substitute for proper application logging.

13. Practical Console Program

import java.util.Scanner;

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

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

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

        System.out.println("Hello " + name);
        System.out.println("Age: " + age);
    }
}

This small program demonstrates the normal flow of console interaction: display a prompt, read input, convert or validate it when necessary, and display a result. Once this pattern is comfortable, you can move toward files, APIs, databases, and other input sources.

14. Input, Conversion and Validation Flow

A robust console program usually follows a simple sequence: prompt the user, read the input, validate its shape and range, convert it to the required type, perform the operation, and display the result. Keeping these stages distinct makes errors easier to handle.

System.out.print("Enter quantity: ");
if (scanner.hasNextInt()) {
    int quantity = scanner.nextInt();
    if (quantity > 0) {
        System.out.println("Accepted");
    }
}

15. Reading Different Input Sources

Scanner is not limited to System.in. It can read from other input sources such as strings or files. This makes the same token-oriented API useful for small parsing tasks, although file resources should be handled with appropriate resource-management techniques.

16. Console Output for Debugging

System.out.println is useful while learning and for simple command-line applications. In larger applications, use a logging framework and appropriate log levels rather than scattering console statements throughout production code.

System.out.println("Starting calculation");
System.err.println("Invalid configuration");

This distinction becomes important when an application runs as a service, where standard output and error streams may be collected or routed separately.

17. Input and Security

Input should always be treated as untrusted data. Validate expected formats, ranges, and lengths before using values in calculations, database queries, file paths, or other external operations. Console examples are simple, but the same principle applies to web requests, files, and API data.

18. Practice Tasks for Java Input and Output

  • Read a name with nextLine() and print a greeting.
  • Read two integers and print their sum.
  • Read a decimal value and format it with printf.
  • Use hasNextInt() to validate an integer input.
  • Read command-line arguments and display them.
  • Build a small menu-driven console program using input and conditional statements.

19. Input/Output Review Checklist

  • Know the difference between System.in, System.out, and System.err.
  • Understand token versus line-based Scanner methods.
  • Validate input before using it.
  • Parse command-line strings into required types.
  • Manage resources deliberately.
  • Move from console I/O to files, streams, APIs, and logging as your Java skills advance.

Practical Mini Project

Create a console-based student registration program. Ask for a name, age, and score. Validate numeric input, display a formatted summary, and print invalid input messages to System.err. Then extend the program to accept command-line arguments. Finally, separate input, validation, calculation, and output into methods so the program is easier to maintain.

Input/Output Mini Project

A useful extension is to improve the first version rather than immediately building something large. Give each important value a clear name, keep methods short, validate inputs at the boundary, and test normal, boundary, and invalid cases. This turns a language concept into a small engineering habit.

Input/output questions to practice

  • What is System.out?
  • What is System.err?
  • How does Scanner read tokens and lines?
  • Why can nextInt followed by nextLine be surprising?
  • What are command-line arguments?
  • When should console output be replaced by application logging?

How This Topic Connects to the Next Java Concepts

After basic input/output, continue into file handling, exceptions, methods, collections, and application architecture. Console I/O is a foundation for understanding broader Java data flows.

20. Input/Output Error Handling

Input operations can fail because the data is malformed, missing, or outside the expected range. A production-quality program should distinguish invalid user input from unexpected application failures. For a console program, a friendly validation message may be enough. For larger applications, errors should be handled at the appropriate layer and recorded through structured logging when necessary.

21. Input/Output and Testing

Console programs are easier to test when input, processing, and output are separated. Instead of placing all logic inside main, move calculations and validation into methods that can be tested independently. The console layer can then focus on reading values and displaying results. This design also makes it easier to replace console input later with files, HTTP requests, or another source.

Frequently Asked Questions

How do I print output?

Use System.out.print, println, or formatting methods such as printf.

How do I read console input?

Scanner is a common beginner option.

What is System.err?

The standard error output stream.

Why can nextLine be empty after nextInt?

The line terminator may remain after the numeric token.

Can Scanner read files?

Yes, although file handling is covered separately.

Conclusion

Input and output connect Java programs to the outside world. Start with console I/O, understand validation and resource behavior, then progress into file handling and the broader Java I/O APIs.

  • Java Hello World Program
  • Java Variables
  • Java Data Types
  • Java File Handling
  • Java Exception Handling