0
0
Javaprogramming~5 mins

Why input and output are required in Java

Choose your learning style9 modes available
Introduction

Input and output let a program talk with people. Input lets the program get information from users. Output shows results back to users.

When you want to ask a user for their name and greet them.
When you need to get numbers from a user to do math.
When you want to show the result of a calculation on the screen.
When you want to read data from a file and display it.
When you want to save user choices or answers for later.
Syntax
Java
import java.util.Scanner;

// To get input from user
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();

// To show output to user
System.out.println("Your input was: " + input);
scanner.close();

Use Scanner to read input from the keyboard.

Use System.out.println() to print output on the screen.

Examples
This example asks for a number and then shows it back.
Java
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("You are " + age + " years old.");
scanner.close();
This example asks for a name and greets the user.
Java
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
Sample Program

This program asks the user for their favorite color and then shows it back.

Java
import java.util.Scanner;

public class InputOutputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your favorite color: ");
        String color = scanner.nextLine();
        System.out.println("Your favorite color is " + color + ".");
        scanner.close();
    }
}
OutputSuccess
Important Notes

Always close the Scanner after use to free resources.

Input and output make programs interactive and useful.

Summary

Input lets programs get information from users.

Output lets programs show results or messages.

Together, they make programs interactive and helpful.