LearnContact
Lesson 1150 min read

Input & Output in Java

Learn how Java programs display output and receive user input using System.out, print(), println(), printf(), Scanner, Console, formatting, escape sequences, and best practices.

Introduction

In the previous lesson, you learned how operators perform calculations, comparisons, assignments, and logical operations. However, a useful program must also communicate with the outside world.

A Java program often needs to display information to the user and receive information from the user. These two operations are known as output and input.

Simple Input and Output
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.println("Hello, " + name + "!");

    }
}
Program Communication
USER

  │
  │ Input
  ▼

JAVA PROGRAM

  │
  │ Output
  ▼

USER
What You Will Learn
  • What input and output mean.
  • Why programs need input and output.
  • How Java communicates with users.
  • What standard streams are.
  • What System.out represents.
  • How print() works.
  • How println() works.
  • The difference between print() and println().
  • How to print variables and expressions.
  • How String concatenation works in output.
  • How escape sequences work.
  • How printf() creates formatted output.
  • How format specifiers work.
  • How to format integers.
  • How to format decimal values.
  • How to control decimal precision.
  • How to align formatted output.
  • How Java receives keyboard input.
  • What the Scanner class is.
  • How to import Scanner.
  • How to create a Scanner object.
  • How to read String values.
  • The difference between next() and nextLine().
  • How to read int values.
  • How to read long values.
  • How to read float values.
  • How to read double values.
  • How to read boolean values.
  • How to read a single character.
  • Why Scanner sometimes appears to skip input.
  • How to solve the Scanner newline problem.
  • How to validate input.
  • How hasNextInt() works.
  • How hasNextDouble() works.
  • How to handle invalid input.
  • When Scanner should be closed.
  • What the Console class is.
  • How to read passwords securely with Console.
  • The difference between Scanner and Console.
  • What System.in represents.
  • What System.err represents.
  • How command-line arguments work.
  • How to convert String input to numeric values.
  • How to build interactive Java programs.
  • Common input and output errors.
  • Best practices for Java input and output.

What is Input & Output?

Input is data received by a program. Output is data produced and displayed or sent by a program.

Input and Output
INPUT

Data enters the program

Examples:

Keyboard
File
Database
Network
Sensor


OUTPUT

Data leaves the program

Examples:

Console
File
Database
Network
Screen
Output Example
System.out.println("Welcome to Java!");
Input Example
Scanner scanner = new Scanner(System.in);

String name = scanner.nextLine();

Why Input & Output is Needed

User Communication

Programs display messages, instructions, results, and errors to users.

User Input

Programs receive names, numbers, choices, commands, and other information.

Dynamic Calculations

Programs can calculate results using values entered while the program is running.

Data Processing

Programs can read data from external sources and produce processed output.

Interaction

Input and output allow programs to respond dynamically instead of using only fixed values.

Debugging

Output statements help developers inspect values and understand program behavior.

Real-World Analogy

Think of a Java program as a restaurant. The customer gives an order, the restaurant processes it, and then returns the prepared food.

Restaurant Analogy
CUSTOMER ORDER

      │
      │ Input
      ▼

   RESTAURANT

      │
      │ Processing
      ▼

 PREPARED FOOD

      │
      │ Output
      ▼

   CUSTOMER

Java I/O Overview

Java Input and Output
JAVA INPUT & OUTPUT

├── Standard Input
│   └── System.in
│
├── Standard Output
│   └── System.out
│
├── Standard Error
│   └── System.err
│
├── Scanner
│   └── Convenient formatted input
│
├── Console
│   └── Console-based interaction
│
└── Command-Line Arguments
    └── Input supplied at program startup

Standard Streams

Java provides three standard streams through the System class.

Standard Streams
STREAM         PURPOSE

System.in      Standard input

System.out     Standard output

System.err     Standard error output
Standard Streams Example
System.out.println("Normal message");

System.err.println("Error message");

System.out

System.out is the standard output stream. It is commonly used to display information in the console.

System.out
System.out.println("Hello, Java!");
Understanding the Statement
System.out.println("Hello");

System
  │
  └── Java System class

out
  │
  └── Standard output stream

println()
  │
  └── Method that prints a value

The print() method displays output without automatically moving the cursor to a new line.

print() Example
System.out.print("Hello ");
System.out.print("Java");
System.out.print("!");
Output
Hello Java!

println() Method

The println() method displays output and then moves the cursor to the next line.

println() Example
System.out.println("Hello");
System.out.println("Java");
System.out.println("Programming");
Output
Hello
Java
Programming
Comparison
print()

Prints value

      │
      ▼

Cursor remains
on same line


println()

Prints value

      │
      ▼

Cursor moves
to next line
Comparison Example
System.out.print("A");
System.out.print("B");

System.out.println();

System.out.println("C");
System.out.println("D");
Output
AB
C
D

Printing Variables

Print Variables
String name = "Alex";
int age = 25;
double salary = 50000.50;

System.out.println(name);
System.out.println(age);
System.out.println(salary);
Output
Alex
25
50000.5

Printing Expressions

Output methods can print the result of expressions directly.

Print Expressions
int first = 10;
int second = 20;

System.out.println(first + second);

System.out.println(first > second);

System.out.println(first * 5);
Output
30
false
50

String Concatenation in Output

The + operator combines Strings with other values when output is created.

Concatenation
String name = "Alex";
int age = 25;

System.out.println(
        "Name: " + name
);

System.out.println(
        "Age: " + age
);
Output
Name: Alex
Age: 25

Concatenation Evaluation

Evaluation Order
int first = 10;
int second = 20;

System.out.println(
        "Total: " + first + second
);

System.out.println(
        "Total: " + (first + second)
);
Output
Total: 1020
Total: 30
Use Parentheses for Calculations
  • The + operator performs both addition and String concatenation.
  • Evaluation proceeds from left to right for operators with the same precedence.
  • Once String concatenation begins, later numeric values may be converted to text.
  • Use parentheses when a calculation must happen before concatenation.

Escape Sequences

Escape sequences represent special characters inside String and character literals.

Common Escape Sequences
SEQUENCE    MEANING

\n          New line

\t          Horizontal tab

\"          Double quote

\'          Single quote

\\          Backslash

\r          Carriage return

\b          Backspace

\f          Form feed

New Line

New Line Escape
System.out.println(
        "Java\nPython\nJavaScript"
);
Output
Java
Python
JavaScript

Tab Character

Tab Escape
System.out.println(
        "Name\tAge\tCity"
);

System.out.println(
        "Alex\t25\tMumbai"
);
Output
Name    Age    City
Alex    25     Mumbai

Quotes and Backslash

Special Characters
System.out.println(
        "He said, \"Learn Java\""
);

System.out.println(
        "C:\\Users\\Alex"
);

System.out.println(
        '\''
);
Output
He said, "Learn Java"
C:\Users\Alex
'

printf() Method

The printf() method creates formatted output using a format String and format specifiers.

printf() Example
String name = "Alex";
int age = 25;

System.out.printf(
        "Name: %s, Age: %d%n",
        name,
        age
);
Output
Name: Alex, Age: 25

Format Specifiers

Common Format Specifiers
SPECIFIER    PURPOSE

%s           String

%d           Decimal integer

%f           Floating-point value

%c           Character

%b           Boolean

%x           Hexadecimal integer

%o           Octal integer

%e           Scientific notation

%n           Platform-specific new line

%%           Percent sign

Formatting Integers

Integer Formatting
int number = 255;

System.out.printf(
        "Decimal: %d%n",
        number
);

System.out.printf(
        "Hexadecimal: %x%n",
        number
);

System.out.printf(
        "Octal: %o%n",
        number
);
Output
Decimal: 255
Hexadecimal: ff
Octal: 377

Formatting Floating-Point Values

Floating-Point Formatting
double price = 99.98765;

System.out.printf(
        "Price: %f%n",
        price
);

System.out.printf(
        "Price: %.2f%n",
        price
);
Output
Price: 99.987650
Price: 99.99

Formatting Strings

String Formatting
String language = "Java";

System.out.printf(
        "Language: %s%n",
        language
);
Output
Language: Java

Formatting Characters and Booleans

Character and Boolean Formatting
char grade = 'A';
boolean passed = true;

System.out.printf(
        "Grade: %c%n",
        grade
);

System.out.printf(
        "Passed: %b%n",
        passed
);
Output
Grade: A
Passed: true

Width and Alignment

Formatted Table
System.out.printf(
        "%-15s %10s%n",
        "Product",
        "Price"
);

System.out.printf(
        "%-15s %10.2f%n",
        "Keyboard",
        1500.50
);

System.out.printf(
        "%-15s %10.2f%n",
        "Mouse",
        750.00
);
Output
Product              Price
Keyboard           1500.50
Mouse               750.00
Formatting Width
  • %10s reserves at least 10 character positions.
  • %-10s left-aligns the value.
  • %10s right-aligns the value.
  • Width is useful when creating console tables.
  • Values longer than the specified width are not truncated automatically.

Decimal Precision

Precision Examples
double value = 12.345678;

System.out.printf("%.1f%n", value);
System.out.printf("%.2f%n", value);
System.out.printf("%.3f%n", value);
System.out.printf("%.4f%n", value);
Output
12.3
12.35
12.346
12.3457

Formatting Multiple Values

Multiple Values
String product = "Laptop";
int quantity = 2;
double price = 75000.50;

System.out.printf(
        "Product: %s | Quantity: %d | Price: %.2f%n",
        product,
        quantity,
        price
);

Input in Java

Java provides multiple ways to receive input. For beginner console programs, the Scanner class is one of the most convenient options.

Input Process
KEYBOARD

    │
    ▼

System.in

    │
    ▼

Scanner

    │
    ▼

Java Variable

Scanner Class

Scanner is a class in the java.util package that can read and parse input from sources such as the keyboard, Strings, and files.

Basic Scanner 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.println(
                "Hello, " + name
        );

    }
}

Importing Scanner

Scanner Import
import java.util.Scanner;
Import Structure
java

  │
  ▼

util

  │
  ▼

Scanner

Creating a Scanner Object

Create Scanner
Scanner scanner =
        new Scanner(System.in);
Scanner Object
Scanner scanner
      │
      └── Reference variable

new Scanner(...)
      │
      └── Creates Scanner object

System.in
      │
      └── Standard keyboard input

Reading String Input

Read Full Line
Scanner scanner =
        new Scanner(System.in);

System.out.print(
        "Enter your full name: "
);

String name =
        scanner.nextLine();

System.out.println(
        "Welcome, " + name
);

next() Method

The next() method reads the next token and stops at whitespace.

next() Example
Scanner scanner =
        new Scanner(System.in);

System.out.print(
        "Enter your name: "
);

String name =
        scanner.next();

System.out.println(name);
Example Input
Alex Smith
Stored Value
Alex

nextLine() Method

The nextLine() method reads an entire line, including spaces, until the line separator is reached.

nextLine() Example
Scanner scanner =
        new Scanner(System.in);

System.out.print(
        "Enter your full name: "
);

String name =
        scanner.nextLine();

System.out.println(name);
Example Input
Alex Smith
Stored Value
Alex Smith

next() vs nextLine()

Comparison
next()

Input:
Alex Smith

Reads:
Alex


nextLine()

Input:
Alex Smith

Reads:
Alex Smith
Which Method Should You Use?
  • Use next() when you need one whitespace-separated token.
  • Use nextLine() when spaces are allowed in the input.
  • Names, addresses, descriptions, and sentences usually require nextLine().

Reading Integer Input

Read int
Scanner scanner =
        new Scanner(System.in);

System.out.print(
        "Enter your age: "
);

int age =
        scanner.nextInt();

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

Reading Long Input

Read long
System.out.print(
        "Enter population: "
);

long population =
        scanner.nextLong();

System.out.println(
        "Population: " + population
);

Reading Float Input

Read float
System.out.print(
        "Enter temperature: "
);

float temperature =
        scanner.nextFloat();

System.out.println(
        "Temperature: " + temperature
);

Reading Double Input

Read double
System.out.print(
        "Enter price: "
);

double price =
        scanner.nextDouble();

System.out.printf(
        "Price: %.2f%n",
        price
);

Reading Boolean Input

Read boolean
System.out.print(
        "Are you active? "
);

boolean active =
        scanner.nextBoolean();

System.out.println(
        "Active: " + active
);
Boolean Input
  • nextBoolean() expects true or false, ignoring case.
  • Values such as yes and no are not automatically converted to boolean.
  • Custom yes/no handling requires reading text and checking the value.

Reading Character Input

Scanner does not provide a nextChar() method. A common approach is to read a String and take its first character.

Read Character
System.out.print(
        "Enter your grade: "
);

char grade =
        scanner.next().charAt(0);

System.out.println(
        "Grade: " + grade
);
Process
Input:

A

   │
   ▼

scanner.next()

"A"

   │
   ▼

charAt(0)

'A'

Complete Input Example

Student Input 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.print(
                "Enter your percentage: "
        );

        double percentage =
                scanner.nextDouble();

        System.out.println(
                "\n--- Student Details ---"
        );

        System.out.println(
                "Name: " + name
        );

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

        System.out.printf(
                "Percentage: %.2f%%%n",
                percentage
        );

    }
}

Scanner Buffer Problem

A common beginner problem occurs when nextLine() is used immediately after methods such as nextInt(), nextDouble(), or next().

Problem Example
Scanner scanner =
        new Scanner(System.in);

System.out.print(
        "Enter age: "
);

int age =
        scanner.nextInt();

System.out.print(
        "Enter name: "
);

String name =
        scanner.nextLine();

System.out.println(
        "Name: " + name
);

The name input may appear to be skipped because nextInt() reads the integer token but leaves the line separator in the input.

Why the Problem Happens

Input Buffer
User enters:

25 [ENTER]

Buffer:

2 5 \n

nextInt()

Reads:
25

Leaves:
\n

nextLine()

Reads remaining:
\n

Result:
Empty String

Fixing the Scanner Buffer Problem

Consume the remaining line separator before reading the next full line.

Correct Solution
Scanner scanner =
        new Scanner(System.in);

System.out.print(
        "Enter age: "
);

int age =
        scanner.nextInt();

scanner.nextLine();

System.out.print(
        "Enter name: "
);

String name =
        scanner.nextLine();

System.out.println(
        "Name: " + name
);
Correct Process
nextInt()

Reads:
25

        │
        ▼

nextLine()

Consumes:
Remaining line separator

        │
        ▼

nextLine()

Reads:
Actual name
One of the Most Common Scanner Problems
  • Token-reading methods do not necessarily consume the end of the line.
  • nextLine() reads everything remaining on the current line.
  • After nextInt(), nextDouble(), and similar methods, an extra nextLine() is often needed before reading a full line.
  • Do not add extra nextLine() calls blindly; understand what remains in the input.

Input Validation

Input validation checks whether the user entered data in the expected format before the program tries to read it.

Validation Process
USER INPUT

    │
    ▼

IS INPUT VALID?

   / \
  /   \

YES    NO

 │      │
 ▼      ▼

READ   SHOW ERROR

hasNextInt()

Validate Integer Input
Scanner scanner =
        new Scanner(System.in);

System.out.print(
        "Enter your age: "
);

if (scanner.hasNextInt()) {

    int age =
            scanner.nextInt();

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

} else {

    System.out.println(
            "Invalid integer input."
    );

}

hasNextDouble()

Validate Decimal Input
System.out.print(
        "Enter price: "
);

if (scanner.hasNextDouble()) {

    double price =
            scanner.nextDouble();

    System.out.printf(
            "Price: %.2f%n",
            price
    );

} else {

    System.out.println(
            "Invalid price."
    );

}

Invalid Input Handling

When invalid input is detected, the invalid token should usually be consumed before the program tries again.

Consume Invalid Input
if (scanner.hasNextInt()) {

    int number =
            scanner.nextInt();

    System.out.println(number);

} else {

    String invalid =
            scanner.next();

    System.out.println(
            "Invalid input: " + invalid
    );

}

Closing Scanner

Close Scanner
Scanner scanner =
        new Scanner(System.in);

// Read input

scanner.close();

Closing a Scanner also closes its underlying input source. When the Scanner wraps System.in, closing it closes the standard input stream for the entire application.

Be Careful When Closing System.in
  • A Scanner should generally be closed when it owns a resource that should be released.
  • Closing a Scanner created from System.in also closes System.in.
  • After System.in is closed, other parts of the application cannot continue reading from it.
  • Small standalone programs often use one Scanner for the entire program.

Scanner and System.in

Input Flow
KEYBOARD

    │
    ▼

System.in

Raw byte input

    │
    ▼

Scanner

Parses tokens

    │
    ▼

nextInt()
nextDouble()
next()
nextLine()

    │
    ▼

Java Values

Console Class

The Console class provides methods for interacting with a character-based console.

Get Console
Console console =
        System.console();
System.console() May Return null
  • A Console object is not available in every execution environment.
  • Many IDEs do not provide a system console to the Java process.
  • Always check whether System.console() returned null before using it.

Reading with Console

Console Input
import java.io.Console;

public class Main {

    public static void main(String[] args) {

        Console console =
                System.console();

        if (console == null) {

            System.out.println(
                    "Console is unavailable."
            );

            return;
        }

        String name =
                console.readLine(
                        "Enter your name: "
                );

        System.out.println(
                "Hello, " + name
        );

    }
}

Reading Passwords

Console provides readPassword(), which can read sensitive character input without displaying the characters on the screen.

Read Password
char[] password =
        console.readPassword(
                "Enter password: "
        );
Why char[] is Used for Passwords
  • Strings are immutable.
  • A String cannot be directly cleared after use.
  • A char array can be overwritten when the password is no longer needed.
  • Sensitive values should not be printed or logged.

Scanner vs Console

Comparison
SCANNER

Easy for beginners
Reads many data types
Works well in IDEs
Supports token parsing
Can validate numeric input


CONSOLE

Designed for console interaction
Can read passwords without echo
May be unavailable in IDEs
Mostly returns text input

System.in

System.in is the standard input stream. By default, it is usually connected to keyboard input.

Direct System.in Read
int value =
        System.in.read();

System.out.println(value);

Direct use of System.in works with raw bytes and is less convenient for beginner programs than Scanner.

System.err

System.err is the standard error output stream. It is intended for error and diagnostic messages.

Error Output
System.err.println(
        "Error: Invalid input."
);

System.out vs System.err

Output Stream Comparison
System.out

Normal program output

Examples:
Results
Messages
Reports


System.err

Error and diagnostic output

Examples:
Invalid input
Failure messages
Debugging information
Separate Output Types
System.out.println(
        "Program started successfully."
);

System.err.println(
        "Warning: Configuration missing."
);

Command-Line Arguments

Command-line arguments allow values to be supplied when a Java program starts.

Main Method
public static void main(
        String[] args
) {

}
Command-Line Input
java Main Alex 25

           │    │
           │    └── args[1]
           │
           └─────── args[0]

Reading Command-Line Arguments

Command-Line Arguments Example
public class Main {

    public static void main(String[] args) {

        System.out.println(
                "First argument: "
                + args[0]
        );

        System.out.println(
                "Second argument: "
                + args[1]
        );

    }
}
Check Argument Length
  • Accessing an argument that does not exist causes ArrayIndexOutOfBoundsException.
  • Check args.length before accessing command-line values.
  • Command-line arguments are received as Strings.
Safe Argument Access
if (args.length >= 2) {

    System.out.println(args[0]);
    System.out.println(args[1]);

} else {

    System.out.println(
            "Two arguments are required."
    );

}

Converting Input Types

Text input can be converted into numeric values using wrapper class parsing methods.

Conversion Flow
"25"

String

   │
   ▼

Integer.parseInt()

   │
   ▼

25

int

Parsing Integers

Parse Integer
String input = "25";

int age =
        Integer.parseInt(input);

System.out.println(
        age + 5
);
Output
30

Parsing Decimal Values

Parse Double
String input = "99.50";

double price =
        Double.parseDouble(input);

System.out.printf(
        "%.2f%n",
        price
);
Invalid Numeric Text
  • Integer.parseInt("25") succeeds.
  • Integer.parseInt("Java") throws NumberFormatException.
  • Double.parseDouble("10.5") succeeds.
  • Input should be validated or errors should be handled when invalid text is possible.

Simple Calculator

Calculator Program
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter first number: "
        );

        double first =
                scanner.nextDouble();

        System.out.print(
                "Enter second number: "
        );

        double second =
                scanner.nextDouble();

        double sum =
                first + second;

        double difference =
                first - second;

        double product =
                first * second;

        System.out.println(
                "\n--- Results ---"
        );

        System.out.printf(
                "Sum: %.2f%n",
                sum
        );

        System.out.printf(
                "Difference: %.2f%n",
                difference
        );

        System.out.printf(
                "Product: %.2f%n",
                product
        );

        if (second != 0) {

            System.out.printf(
                    "Division: %.2f%n",
                    first / second
            );

        } else {

            System.err.println(
                    "Division by zero is not allowed."
            );

        }

    }
}

Student Information Program

Student Program
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter student name: "
        );

        String name =
                scanner.nextLine();

        System.out.print(
                "Enter age: "
        );

        int age =
                scanner.nextInt();

        System.out.print(
                "Enter marks: "
        );

        double marks =
                scanner.nextDouble();

        System.out.print(
                "Enter grade: "
        );

        char grade =
                scanner.next().charAt(0);

        System.out.println(
                "\n--- Student Report ---"
        );

        System.out.printf(
                "%-12s : %s%n",
                "Name",
                name
        );

        System.out.printf(
                "%-12s : %d%n",
                "Age",
                age
        );

        System.out.printf(
                "%-12s : %.2f%n",
                "Marks",
                marks
        );

        System.out.printf(
                "%-12s : %c%n",
                "Grade",
                grade
        );

    }
}

Common Input & Output Errors

Common Errors
INPUT & OUTPUT ERRORS

├── Forgetting Scanner Import
├── Forgetting to Create Scanner
├── Using Wrong Scanner Method
├── Entering Text for Numeric Input
├── Confusing next() with nextLine()
├── Scanner Skipping nextLine()
├── Forgetting Remaining Newline
├── Adding Extra nextLine() Calls Blindly
├── Reading Character Incorrectly
├── Forgetting charAt(0)
├── Using Wrong printf Specifier
├── Forgetting printf Arguments
├── Forgetting %n or New Line
├── Incorrect String Concatenation
├── Forgetting Parentheses Around Calculations
├── Closing System.in Too Early
├── Using System.console() Without null Check
├── Accessing Missing Command-Line Arguments
├── Parsing Invalid Numeric Text
├── Printing Sensitive Information
└── Failing to Validate User Input
Wrong Scanner Method
Scanner scanner =
        new Scanner(System.in);

// User enters:
// Alex

// Wrong:
// int age = scanner.nextInt();
Wrong printf Specifier
String name = "Alex";

// Wrong:
// System.out.printf("%d", name);

// Correct:
System.out.printf("%s", name);
Wrong Concatenation
int first = 10;
int second = 20;

System.out.println(
        "Total: " + first + second
);

// Output:
// Total: 1020
Correct Concatenation
System.out.println(
        "Total: " + (first + second)
);

// Output:
// Total: 30

Best Practices

  • Display clear prompts before requesting user input.
  • Tell users exactly what type of value is expected.
  • Use print() when input should appear on the same line as the prompt.
  • Use println() when the next output should begin on a new line.
  • Use printf() when output requires structured formatting.
  • Use %n for portable line breaks in formatted output.
  • Use the correct format specifier for each value.
  • Use %.2f when displaying common decimal values such as prices.
  • Use field widths when creating console tables.
  • Use left and right alignment consistently.
  • Use parentheses when calculations are mixed with String concatenation.
  • Use escape sequences only when they improve output structure.
  • Use nextLine() when input may contain spaces.
  • Use next() when only one token is required.
  • Use nextInt() for int values.
  • Use nextLong() for long values.
  • Use nextFloat() for float values.
  • Use nextDouble() for double values.
  • Use nextBoolean() only when true or false input is expected.
  • Use next().charAt(0) to read a single character.
  • Understand the difference between token input and line input.
  • Consume the remaining line separator before switching from token input to nextLine().
  • Do not add extra nextLine() calls without understanding the input state.
  • Validate numeric input before reading when invalid input is possible.
  • Use hasNextInt() before nextInt() when appropriate.
  • Use hasNextDouble() before nextDouble() when appropriate.
  • Consume invalid tokens before requesting input again.
  • Give useful error messages when input is invalid.
  • Do not expose technical exception details to ordinary users unnecessarily.
  • Use one Scanner for System.in when practical.
  • Do not create many Scanner objects for the same System.in stream.
  • Be careful when closing a Scanner connected to System.in.
  • Remember that closing the Scanner also closes System.in.
  • Use Console when hidden password input is required and a console is available.
  • Check System.console() for null before using it.
  • Do not print passwords.
  • Do not store passwords in immutable Strings when avoidable.
  • Clear sensitive character arrays after use when appropriate.
  • Use System.out for normal output.
  • Use System.err for error and diagnostic messages.
  • Check args.length before reading command-line arguments.
  • Remember that command-line arguments are Strings.
  • Parse command-line values before numeric calculations.
  • Handle invalid numeric text when parsing user-controlled values.
  • Use meaningful variable names for input values.
  • Separate input, processing, and output when programs become larger.
  • Keep user prompts consistent.
  • Use labels when printing multiple values.
  • Format monetary values consistently.
  • Do not rely on console formatting for permanent data storage.
  • Test input with spaces.
  • Test empty input when allowed.
  • Test invalid numeric input.
  • Test zero values.
  • Test negative values.
  • Test large numeric values.
  • Test decimal values.
  • Test mixed Scanner methods.
  • Test command-line argument counts.
  • Keep console interaction simple and predictable.
  • Prefer readable output over decorative complexity.
  • Avoid unnecessary output in production applications.
  • Do not log sensitive user data.
  • Use dedicated logging tools for larger applications instead of relying only on System.out.
  • Understand that Scanner is convenient but not always the fastest input solution.
  • Choose input tools according to application requirements.
  • Use clear validation rules.
  • Repeat input requests only when the program is designed to recover from invalid input.
  • Explain accepted formats to users.
  • Use constants for repeated prompt text when appropriate.
  • Keep formatting logic maintainable.
  • Use methods to separate repeated input operations in larger programs.
  • Remember that input and output are boundaries between the program and the outside world.

Input & Output Checklist

Checklist
INPUT & OUTPUT CHECKLIST

[ ] Correct output method selected

[ ] print() and println() difference understood

[ ] Variables printed correctly

[ ] Calculations grouped with parentheses

[ ] Escape sequences used correctly

[ ] printf() format string is valid

[ ] Correct format specifiers selected

[ ] Decimal precision is appropriate

[ ] Output alignment is readable

[ ] Scanner imported

[ ] Scanner object created correctly

[ ] Correct Scanner method selected

[ ] next() vs nextLine() understood

[ ] Numeric input type matches variable type

[ ] Character input uses charAt(0)

[ ] Remaining newline handled correctly

[ ] Input validation considered

[ ] Invalid tokens consumed

[ ] Error messages are clear

[ ] Scanner lifecycle considered

[ ] System.in not closed too early

[ ] Console checked for null

[ ] Passwords not printed

[ ] System.out used for normal output

[ ] System.err used for errors

[ ] Command-line argument count checked

[ ] String input parsed safely

[ ] Sensitive information protected

[ ] Boundary values tested

[ ] Invalid input tested

[ ] User prompts are clear

[ ] Program interaction is predictable

Common Misconceptions

Avoid These Misconceptions
  • print() does not automatically move to a new line.
  • println() moves to a new line after printing.
  • println() can be called without an argument to print only a line separator.
  • printf() does not automatically add a new line unless the format includes one.
  • %n is commonly used for a platform-specific new line in formatted output.
  • The + operator can perform both addition and String concatenation.
  • "Total: " + 10 + 20 produces Total: 1020.
  • "Total: " + (10 + 20) produces Total: 30.
  • next() does not read an entire line containing spaces.
  • nextLine() reads the remainder of the current line.
  • nextInt() does not consume the entire line in the same way as nextLine().
  • The Scanner newline problem is caused by remaining input, not by nextLine() randomly failing.
  • An extra nextLine() should be added only when there is a remaining line separator to consume.
  • Scanner has no nextChar() method.
  • A character can be read using next().charAt(0).
  • nextBoolean() does not automatically treat yes as true.
  • Invalid numeric input can cause input mismatch errors.
  • hasNextInt() checks whether the next token can be interpreted as an int.
  • System.in is a standard input stream.
  • System.out is a standard output stream.
  • System.err is a separate standard error stream.
  • Closing Scanner can close System.in.
  • System.console() can return null.
  • Console is not always available inside IDEs.
  • Command-line arguments are received as Strings.
  • args[0] is the first command-line argument, not the program name.
  • Accessing a missing argument causes an exception.
  • Integer.parseInt() can fail for invalid numeric text.
  • printf() format specifiers must match compatible argument types.
  • Field width does not automatically truncate long values.
  • Scanner is convenient but not necessarily the fastest input mechanism.
  • System.out is useful for learning and simple programs but larger applications often use logging frameworks.
  • Input should not always be trusted.
  • Sensitive values should not be printed or logged.

Practice Exercises

Exercise 1: Basic Output
  • Print your name.
  • Print your age.
  • Print your city.
  • Use separate println() statements.
  • Then print everything on one line using print().
Exercise 2: Escape Sequences
  • Print three programming languages on separate lines using one statement.
  • Create a tab-separated table.
  • Print a sentence containing double quotes.
  • Print a Windows-style path containing backslashes.
Exercise 3: Formatted Output
  • Create variables for product name, quantity, and price.
  • Use printf() to display them.
  • Display the price with two decimal places.
  • Create aligned columns.
Exercise 4: Personal Information
  • Ask the user for a full name.
  • Ask for age.
  • Ask for height.
  • Ask for a grade character.
  • Display all information in a formatted report.
Exercise 5: next() vs nextLine()
  • Read a full name using next().
  • Observe what happens when spaces are entered.
  • Replace next() with nextLine().
  • Compare both results.
  • Explain the difference.
Exercise 6: Scanner Newline Problem
  • Read an integer using nextInt().
  • Immediately read a full line using nextLine().
  • Observe the problem.
  • Add a nextLine() call to consume the remaining line separator.
  • Verify that the program now works correctly.
Exercise 7: Input Validation
  • Ask the user for an integer.
  • Use hasNextInt() to validate the input.
  • Print the number when valid.
  • Print a useful error message when invalid.
Exercise 8: Simple Calculator
  • Read two numbers.
  • Calculate addition.
  • Calculate subtraction.
  • Calculate multiplication.
  • Calculate division.
  • Prevent division by zero.
  • Format decimal results to two decimal places.
Exercise 9: Command-Line Arguments
  • Read a name from args[0].
  • Read an age from args[1].
  • Check args.length first.
  • Convert the age to int.
  • Print a formatted message.
Exercise 10: Student Report
  • Read student name.
  • Read marks for three subjects.
  • Calculate the total.
  • Calculate the average.
  • Display a formatted report.
  • Use two decimal places for the average.

Common Interview Questions

What is input in Java?

Input is data received by a Java program from a source such as the keyboard, a file, a network connection, or another system.

What is output in Java?

Output is data produced by a Java program and sent to a destination such as the console, a file, or another system.

What is System.out?

System.out is the standard output stream, represented by a PrintStream object.

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

print() displays output without automatically adding a line separator, while println() adds a line separator after the output.

What does printf() do?

printf() produces formatted output using a format String and format arguments.

What does %d represent?

%d formats a decimal integer.

What does %f represent?

%f formats a floating-point value.

What does %s represent?

%s formats a String representation.

What does %n represent?

%n produces a platform-specific line separator in formatted output.

What is Scanner?

Scanner is a class in java.util that can parse primitive values and Strings from input sources.

How do you read an integer using Scanner?

Use the nextInt() method.

How do you read a complete line using Scanner?

Use the nextLine() method.

What is the difference between next() and nextLine()?

next() reads the next token separated by whitespace, while nextLine() reads the remainder of the current line.

Why does nextLine() sometimes appear to be skipped?

A previous token-reading method may leave the line separator in the input, and nextLine() immediately consumes the remainder of that line.

How do you read a character with Scanner?

A common approach is scanner.next().charAt(0).

What does hasNextInt() do?

It checks whether the next input token can be interpreted as an int.

What happens when a Scanner wrapping System.in is closed?

The Scanner closes its underlying input source, which means System.in is also closed.

What is System.in?

System.in is the standard input stream, represented by an InputStream.

What is System.err?

System.err is the standard error output stream.

What is the Console class?

Console provides methods for interacting with a character-based console, including reading lines and passwords.

Why can System.console() return null?

A console is not available in every execution environment, especially in many IDE configurations.

What are command-line arguments?

They are String values supplied to a Java program when it starts and received through the args array.

Frequently Asked Questions

Should I use print() or println() for prompts?

print() is commonly used for prompts because the user can enter input on the same line.

Does printf() automatically move to the next line?

No. Add %n or another line separator when a new line is required.

Why does %.2f round the displayed value?

The precision in the format specifier controls how many digits are displayed after the decimal point.

Can Scanner read a full name?

Yes. Use nextLine() when the name may contain spaces.

Why does next() only read the first word?

next() reads one token and uses whitespace as a delimiter by default.

Does Scanner have nextChar()?

No. A common solution is scanner.next().charAt(0).

Why does nextInt() fail when I enter text?

nextInt() expects the next token to be a valid integer. Invalid text cannot be parsed as int.

How can I check input before nextInt()?

Use hasNextInt().

Should I always call scanner.close()?

Resources should normally be closed appropriately, but closing a Scanner connected to System.in also closes System.in. Consider the lifetime and ownership of the shared input stream.

Can I create multiple Scanner objects for System.in?

It is usually better to use one Scanner for System.in because multiple wrappers and resource closing can create confusing behavior.

Can Console read passwords?

Yes. readPassword() can read a password without echoing the entered characters.

Why does System.console() return null in my IDE?

Many IDE execution environments do not attach a real system console to the Java process.

Are command-line arguments numbers?

No. They are received as Strings and must be parsed before numeric calculations.

What should I learn after input and output?

The next lesson covers conditional statements in Java.

Key Takeaways

  • Input is data received by a program.
  • Output is data produced by a program.
  • Input and output allow programs to communicate with users and external systems.
  • Java provides standard input, output, and error streams.
  • System.in represents standard input.
  • System.out represents standard output.
  • System.err represents standard error output.
  • print() displays output without automatically adding a new line.
  • println() displays output and adds a line separator.
  • println() can be called without an argument.
  • Output methods can print literals, variables, and expressions.
  • The + operator performs String concatenation when a String operand is involved.
  • Parentheses should be used when calculations must happen before String concatenation.
  • Escape sequences represent special characters.
  • \n represents a new line character.
  • \t represents a horizontal tab.
  • \" represents a double quote inside a String literal.
  • \\ represents a backslash.
  • printf() produces formatted output.
  • %s formats Strings.
  • %d formats decimal integers.
  • %f formats floating-point values.
  • %c formats characters.
  • %b formats boolean values.
  • %x formats hexadecimal integers.
  • %o formats octal integers.
  • %e formats scientific notation.
  • %n produces a platform-specific line separator.
  • %% prints a percent sign.
  • Field widths can align console output.
  • A negative width flag can left-align formatted values.
  • Precision controls displayed decimal places.
  • Scanner is located in java.util.
  • Scanner can read input from System.in.
  • next() reads one token.
  • nextLine() reads the remainder of a line.
  • nextInt() reads int values.
  • nextLong() reads long values.
  • nextFloat() reads float values.
  • nextDouble() reads double values.
  • nextBoolean() reads boolean values.
  • Scanner does not provide nextChar().
  • A character can be read using next().charAt(0).
  • Token-reading methods and nextLine() handle line separators differently.
  • A remaining line separator can cause nextLine() to return an empty String.
  • An extra nextLine() can consume the remaining line separator when necessary.
  • Input validation checks data before reading or processing it.
  • hasNextInt() checks whether the next token can be read as an int.
  • hasNextDouble() checks whether the next token can be read as a double.
  • Invalid tokens should be consumed before retrying input.
  • Closing Scanner closes its underlying input source.
  • Closing a Scanner connected to System.in closes System.in.
  • Console supports character-based console interaction.
  • System.console() may return null.
  • Console can read passwords without displaying entered characters.
  • Password character arrays can be cleared after use.
  • System.err should be used for error and diagnostic output.
  • Command-line arguments are stored in the args array.
  • Command-line arguments are Strings.
  • args.length should be checked before accessing arguments.
  • String numeric input can be converted using parsing methods.
  • Integer.parseInt() converts numeric text to int.
  • Double.parseDouble() converts numeric text to double.
  • Invalid numeric text can cause NumberFormatException.
  • Clear prompts improve user interaction.
  • Input should be validated when invalid values are possible.
  • Sensitive information should never be printed unnecessarily.
  • Input and output form the communication boundary between a program and the outside world.

Summary

Input and output allow Java programs to communicate with users and external systems. Input brings data into a program, while output sends information from the program to a destination.

Java provides System.in for standard input, System.out for standard output, and System.err for standard error output.

The print() method displays output without automatically moving to a new line, while println() displays output and then adds a line separator.

The printf() method creates formatted output. Format specifiers such as %s, %d, %f, %c, and %b control how values are displayed, while width and precision options help create readable reports and tables.

The Scanner class provides convenient methods for reading user input. Different methods are used for different data types, including nextInt(), nextLong(), nextFloat(), nextDouble(), nextBoolean(), next(), and nextLine().

The difference between token-based methods and nextLine() is important. Token methods may leave a line separator in the input, causing a following nextLine() call to return an empty String unless the remaining line is consumed first.

Input validation helps prevent programs from failing when users enter unexpected values. Scanner methods such as hasNextInt() and hasNextDouble() can check input before it is consumed.

The Console class provides another way to interact with users and supports hidden password input, but a Console object is not available in every execution environment.

Command-line arguments provide input when a program starts. They are received as Strings and can be converted to numeric types when necessary.

Understanding input and output is essential because interactive programs depend on receiving data, processing it, and communicating meaningful results.

Lesson 11 Completed
  • You understand what input means.
  • You understand what output means.
  • You understand why programs need input and output.
  • You understand standard streams.
  • You understand System.in.
  • You understand System.out.
  • You understand System.err.
  • You can use print().
  • You can use println().
  • You can compare print() and println().
  • You can print variables.
  • You can print expressions.
  • You understand String concatenation in output.
  • You understand concatenation evaluation order.
  • You understand escape sequences.
  • You can print new lines and tabs.
  • You can print quotes and backslashes.
  • You can use printf().
  • You understand common format specifiers.
  • You can format integers.
  • You can format floating-point values.
  • You can format Strings.
  • You can format characters and booleans.
  • You can control field width.
  • You can align formatted values.
  • You can control decimal precision.
  • You can format multiple values.
  • You understand Java keyboard input.
  • You understand the Scanner class.
  • You can import Scanner.
  • You can create a Scanner object.
  • You can read String input.
  • You understand next().
  • You understand nextLine().
  • You can compare next() and nextLine().
  • You can read int values.
  • You can read long values.
  • You can read float values.
  • You can read double values.
  • You can read boolean values.
  • You can read a single character.
  • You understand the Scanner newline problem.
  • You understand why nextLine() can appear to skip input.
  • You can fix the Scanner newline problem.
  • You understand input validation.
  • You can use hasNextInt().
  • You can use hasNextDouble().
  • You can handle invalid input tokens.
  • You understand Scanner resource closing.
  • You understand the relationship between Scanner and System.in.
  • You understand the Console class.
  • You can read input using Console.
  • You understand password input.
  • You can compare Scanner and Console.
  • You understand command-line arguments.
  • You can safely read command-line arguments.
  • You can convert String input to numeric values.
  • You can parse integers.
  • You can parse decimal values.
  • You can build an interactive calculator.
  • You can build a student information program.
  • You can identify common input and output errors.
  • You know best practices for Java input and output.
  • You are ready to learn conditional statements.
Next Lesson →

Conditional Statements in Java