Table of Contents

    Input and Output

    Input and Output
    Figure: Input and Output

    JAVA PROGRAMMING

    Input and Output in Java

    Talk to Your Program — Get Data In, Send Results Out! Input and Output are the ways your Java program communicates with users. Master the Scanner class for input and System.out.println() for output — and you can build any interactive program!

    Introduction

    Every useful Java program interacts with users — asking questions and showing results. This interaction is done through Input (getting data) and Output (showing results).

    In this article, we'll explore how Java handles I/O using the Scanner class and System.out methods. By the end, you'll be able to write interactive Java programs with confidence!

    Key Idea: Input gets data IN, Output shows data OUT! Master Scanner and System.out to build interactive programs!

    Real-Life Analogy

    Input and Output are like a conversation between you and a friend. You ask them a question (input), they think about it (processing), and give you an answer (output). Java programs work the same way — they ask you for data, process it, and show you the result!

    What is Input/Output?

    📥

    Input

    Data given to program

    Input is the data given TO the program by the user — usually via keyboard.

    📤

    Output

    Result shown by program

    Output is the result displayed BY the program — usually on the screen/console.

    I/O FLOW
    UserInputProgramOutputUser

    Key Points to Remember

    Essentials

    • ✅ Input comes from keyboard.
    • ✅ Output goes to screen.
    • Scanner class is used for input.
    • System.out.println() for output.
    • ✅ Data types matter (int, String, double).
    • ✅ Must import Scanner class.
    • ✅ Always create a Scanner object first.
    • ✅ Close Scanner when done (good practice).

    Java I/O Methods

    Method Purpose
    Scanner class For taking input
    System.out.println() Output with a new line
    System.out.print() Output without a new line
    System.out.printf() Formatted output
    nextInt() Read an integer
    nextDouble() Read a decimal number
    next() Read a single word (String)
    nextLine() Read a full line of text

    Input (Getting Data)

    To take input in Java, we use the Scanner class from java.util package.

    Step-by-Step: How to Take Input

    1

    Import Scanner

    Bring in the class

    Add this at the top of your file: import java.util.Scanner;

    2

    Create Scanner Object

    Set up input reader

    Create an object of Scanner class: Scanner sc = new Scanner(System.in);

    3

    Use Correct Method

    Choose based on data type

    Use appropriate method like nextInt(), nextDouble(), next(), etc.

    Scanner Methods Table

    Method Description
    nextInt() Reads integer (whole number)
    nextDouble() Reads decimal number
    nextFloat() Reads floating-point number
    next() Reads single word (String)
    nextLine() Reads full line of text
    nextBoolean() Reads true or false
    nextByte() Reads byte value
    nextLong() Reads long integer

    Output (Showing Results)

    To display output, we use System.out methods. No import needed!

    Output Methods

    1

    System.out.println()

    Print with new line

    Prints the output AND moves cursor to next line.

    Example: System.out.println("Hello!");

    2

    System.out.print()

    Print without new line

    Prints the output but stays on the same line.

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

    3

    System.out.printf()

    Formatted output

    Prints with special formatting.

    Example: System.out.printf("Price: %.2f", 99.99);

    Combining Text and Variables

    Use the + operator to combine strings and variables in output.

    int sum = 10;
    System.out.println("Sum = " + sum);
    // Output: Sum = 10
    
    String name = "Ravi";
    int age = 15;
    System.out.println(name + " is " + age + " years old.");
    // Output: Ravi is 15 years old.

    Complete Example Program

    Here's a complete program that takes two numbers as input, adds them, and shows the result.

    import java.util.Scanner;
    
    public class AddNumbers {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            // Input
            System.out.print("Enter first number: ");
            int a = sc.nextInt();
            System.out.print("Enter second number: ");
            int b = sc.nextInt();
    
            // Process
            int sum = a + b;
    
            // Output
            System.out.println("Sum = " + sum);
    
            sc.close();
        }
    }
    Sample Run
    • Enter first number: 5
    • Enter second number: 3
    • Sum = 8

    print() vs println() Comparison

    Feature print() println()
    New line after output ❌ No ✅ Yes
    Cursor position after Same line Next line
    Best for Prompts, headers Regular output

    Example 1: Using print()

    System.out.print("Hi");
    System.out.print("Bye");
    
    // Output: HiBye (same line)

    Example 2: Using println()

    System.out.println("Hi");
    System.out.println("Bye");
    
    // Output:
    // Hi
    // Bye
    // (each on new line)

    More Example Programs

    Example 1: Get User's Name

    import java.util.Scanner;
    
    public class NameProgram {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            System.out.print("Enter your name: ");
            String name = sc.next();
    
            System.out.println("Hello, " + name + "!");
    
            sc.close();
        }
    }
    Sample Run
    • Enter your name: Ravi
    • Hello, Ravi!

    Example 2: Area of a Circle

    import java.util.Scanner;
    
    public class CircleArea {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            System.out.print("Enter radius: ");
            double radius = sc.nextDouble();
    
            double area = 3.14 * radius * radius;
    
            System.out.println("Area of circle = " + area);
    
            sc.close();
        }
    }
    Sample Run
    • Enter radius: 5
    • Area of circle = 78.5

    Example 3: Get Full Name (Multiple Words)

    import java.util.Scanner;
    
    public class FullName {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            System.out.print("Enter your full name: ");
            String fullName = sc.nextLine();
    
            System.out.println("Welcome, " + fullName + "!");
    
            sc.close();
        }
    }
    Sample Run
    • Enter your full name: Ravi Kumar Sharma
    • Welcome, Ravi Kumar Sharma!
    Note: Use next() for single word input, and nextLine() for full line input (with spaces).

    Example 4: Calculator (Multiple Inputs)

    import java.util.Scanner;
    
    public class Calculator {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            System.out.print("Enter first number: ");
            double a = sc.nextDouble();
    
            System.out.print("Enter second number: ");
            double b = sc.nextDouble();
    
            System.out.println("Addition: " + (a + b));
            System.out.println("Subtraction: " + (a - b));
            System.out.println("Multiplication: " + (a * b));
            System.out.println("Division: " + (a / b));
    
            sc.close();
        }
    }

    Tips for Success

    Best Practices

    • 💡 Always import Scanner class.
    • 💡 Close Scanner when done (sc.close()).
    • 💡 Use correct data type methods (nextInt for int, etc.).
    • 💡 Check user input carefully.
    • 💡 Use meaningful prompts ("Enter your age:").
    • 💡 Add spaces in output for clarity.
    • 💡 Test with different inputs.
    • 💡 Use println() for most outputs.
    • 💡 Use print() for prompts (no new line).
    • 💡 Handle exceptions for wrong input types.

    Common Errors

    Watch Out for These!

    • Forgetting import statement — Must import Scanner!
    • Missing new Scanner(System.in) — Object creation needed.
    • Using wrong method (nextInt vs next) — Match data type!
    • Mixing next() with nextLine() — Buffer issues.
    • Missing semicolons (;) — Every statement needs one.
    • Case sensitivity errors (System vs system).
    • Not closing Scanner — May cause warnings.
    • Wrong input type — Entering text when integer expected.

    Key Concepts to Remember

    Concept Description
    Scanner Class used to read user input
    System.in Standard input (keyboard)
    System.out Standard output (console)
    import statement Brings Scanner class into your program
    Scanner object Instance of Scanner class (like sc)
    Buffer Temporary storage of user input
    Concatenation (+) Combining strings and values
    Prompt Message asking user for input

    Did You Know?

    Fun Fact

    The Scanner class was added in Java 5 (2004)! Before that, developers used BufferedReader which was more complex. Scanner made input handling much easier for beginners and pros alike!

    Common Programming Patterns

    Pattern 1: Read Single Value

    System.out.print("Enter age: ");
    int age = sc.nextInt();
    System.out.println("Age is " + age);

    Pattern 2: Read Multiple Values on One Line

    System.out.print("Enter 3 numbers: ");
    int a = sc.nextInt();
    int b = sc.nextInt();
    int c = sc.nextInt();
    // User types: 5 10 15

    Pattern 3: Read Sentence

    System.out.print("Enter message: ");
    String message = sc.nextLine();
    System.out.println("You said: " + message);

    Pattern 4: Menu-Driven Program

    System.out.println("1. Add");
    System.out.println("2. Subtract");
    System.out.print("Choose option: ");
    int choice = sc.nextInt();
    
    if (choice == 1) {
        System.out.println("You chose Add");
    } else {
        System.out.println("You chose Subtract");
    }

    Real-Life Applications

    ATM Machine

    • Input: PIN, amount
    • Output: Balance, receipt

    Video Game

    • Input: Player name, moves
    • Output: Score, graphics

    Calculator App

    • Input: Numbers, operator
    • Output: Result

    Online Shopping

    • Input: Search terms, quantity
    • Output: Products, prices

    Frequently Asked Questions

    Q1. Why do I need to import Scanner?

    Scanner is in the java.util package. Import brings it into your program so you can use it.

    Q2. What's the difference between next() and nextLine()?

    next() reads only ONE word (until space). nextLine() reads the ENTIRE line (until Enter).

    Q3. Why should I close the Scanner?

    To free up system resources. Not always necessary in simple programs, but it's a good practice.

    Q4. What if user enters wrong data type?

    You'll get an InputMismatchException. Handle it using try-catch (advanced topic).

    Q5. Can I use System.out.println without importing?

    Yes! System is in java.lang package, which is imported automatically.

    Q6. What does System.in mean?

    It represents standard input (usually the keyboard).

    Q7. Can I have multiple Scanner objects?

    Yes, but usually one is enough. Multiple objects can cause confusion.

    Q8. What's printf()?

    printf() is for formatted output. Example: System.out.printf("%.2f", 3.14159); prints 3.14.

    Q9. How to read boolean input?

    Use nextBoolean(). User must enter true or false.

    Q10. Can I skip the prompt message?

    You can, but it's not user-friendly. Always show clear prompts.

    Key Takeaways

    • Input gets data IN; Output shows data OUT.
    • Use Scanner class for input.
    • Use System.out for output.
    • Always import Scanner: import java.util.Scanner;
    • Create Scanner object: Scanner sc = new Scanner(System.in);
    • Use correct methods (nextInt, nextDouble, next, nextLine).
    • Use println() for output with new line.
    • Use print() for output without new line.
    • Combine text and variables with +.
    • Practice makes perfect!

    Key Takeaway

    Input gets data IN, Output shows data OUT! Master Scanner and System.out to build interactive programs!

    Input and Output are fundamental to programming. Every useful program needs to communicate with users. Once you master these, you can build calculators, quizzes, games, and much more!

    Practice input-output programs. You will become confident!

    INPUT SMART, PROCESS CLEAR, OUTPUT BEAUTIFUL!

    Best of Luck! Practice daily, build interactive programs, and code with confidence! 👍😊

    Flowchart → Visual Thinking → Smart Solutions → Better Results! 🚀