Understand and use input and output

📥 Input and Output in Programming

What is Input?

Think of input as a phone call to your program. Just like you listen to what someone says, a program listens to data that comes from the user, a file, or another program. In Java, the most common way to listen to a phone call is the Scanner class.

What is Output?

Output is the reply you send back. It could be a message on the screen, a file written to disk, or a signal sent to another program. In Java, we usually reply with System.out.println(), which prints a line on the screen.

Reading Input in Java

Here’s a simple example that asks the user for their name and age, then stores the values:

import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);          // 📥 Create a scanner
        System.out.print("Enter your name: ");            // Ask for name
        String name = scanner.nextLine();                 // Read name

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

        System.out.println("Hello, " + name + "! You are " + age + " years old."); // 📤 Reply
        scanner.close();                                  // Close scanner
    }
}

Writing Output in Java

Printing is as easy as saying something out loud. Use System.out.println() to print a line, or System.out.print() to print without a new line. Example:

System.out.println("This is a line with a newline.");   // 📤 Prints line + newline
System.out.print("This is a line without a newline."); // 📤 Prints line only

Common Mistakes ❌

  • Not closing the Scanner – can lead to resource leaks.
  • Using nextInt() then nextLine() without consuming the newline character.
  • Printing without a newline when you expect a new line.
  • Assuming the user will always input the correct type (e.g., entering text when a number is expected).

Practice Exercises ??

  1. Write a program that asks for two numbers and prints their sum.
  2. Ask the user for their favorite color and print a message that includes it.
  3. Read a sentence from the user and print the number of words in it. Hint: use String.split().
  4. Create a simple calculator that reads an operator (+, -, *, /) and two numbers, then prints the result.

Summary Table

Operation Java Code Explanation
Read a line of text String line = scanner.nextLine(); Captures everything typed until the user presses Enter.
Read an integer int n = scanner.nextInt(); Reads the next token and converts it to an int.
Print a message System.out.println("Hello!"); Outputs the string followed by a new line.

Revision

Log in to practice.

1 views 0 suggestions