Input and Output in Java
Introduction
Input and output are essential parts of any programming language. In Java, the Scanner class is commonly used to read input from the user, and the System.out class is used to print output to the console.
Steps for Input and Output in Java
Follow the steps below to understand how to take input and display output in Java:
1. Using the Scanner Class for Input
The Scanner class is part of the java.util package and provides methods to read different types of input such as integers, strings, and doubles.
2. Using System.out for Output
The System.out.println() method is used to display messages or data on the console.
Example: Reading Input and Displaying Output
Step 1: Write the Program
Create a file named InputOutputExample.java and write the following code:
import java.util.Scanner;
public class InputOutputExample {
public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);
// Prompt the user for their name
System.out.println("Enter your name: ");
String name = scanner.nextLine();
// Prompt the user for their age
System.out.println("Enter your age: ");
int age = scanner.nextInt();
// Display the input received
System.out.println("Hello, " + name + "! You are " + age + " years old.");
// Close the scanner
scanner.close();
}
}
Step 2: Compile the Program
Open the terminal or command prompt, navigate to the file location, and type:
javac InputOutputExample.java
Step 3: Run the Program
Type the following command to execute the program:
java InputOutputExample
The program will prompt the user for their name and age, then display a message based on the input.
Explanation of the Code
- Scanner scanner = new Scanner(System.in): Creates a new
Scannerobject to read input from the console. - scanner.nextLine(): Reads a line of text (e.g., the user's name).
- scanner.nextInt(): Reads an integer value (e.g., the user's age).
- System.out.println(): Prints messages or variables to the console.
- scanner.close(): Closes the
Scannerobject to free resources.
Conclusion
Using the Scanner class and System.out methods, you can handle input and output in Java efficiently. Practice by modifying the example to read and display different types of data.