Data Input and Output

In this exercise, you'll learn how to manipulate data input and output in Java using System.out.println() to display information to the console and Scanner to read user input. Mastering these concepts is essential for interacting with users and processing information in your programs. Practice with examples and improve your Java programming skills.

Topic

Java Fundamentals

Java Exercise

In this exercise, you will create a Java program that reads user input and displays it to the console. You will use the System.out.println() method to print messages and the Scanner class to read user input from the console. You will learn how to capture different types of data, such as numbers and text, and how to process them within your program.

Instructions:

  1. Declare a variable of type Scanner to read user input.
  2. Prompt the user to enter their name and store the input in a variable of type String.
  3. Prompt the user to enter their age and store the input in a variable of type int.
  4. Use System.out.println() to print the user's name and age.
  5. Compile and run the program to see the output in the console.

This exercise will help you understand how to interact with the user using Data Input and Output in Java, an essential step in developing interactive applications.


import java.util.Scanner;

public class InputOutputData {
    public static void main(String[] args) {
        // Create a Scanner object to read user input
        Scanner scanner = new Scanner(System.in);
        
        // Ask the user to enter their name
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        
        // Ask the user to enter their age
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        
        // Display the entered information on the console
        System.out.println("Your name is: " + name);
        System.out.println("Your age is: " + age);
        
        // Close the Scanner object
        scanner.close();
    }
}

 Output:

Enter your name: John
Enter your age: 25
Your name is: John
Your age is: 25

This code shows how to use the Scanner class to read user input, such as their name and age, and then print that data to the console using System.out.println().


 Share this JAVA exercise