How to Take Input From User in Java?

In this tutorial will learn about How to Take Input From User in Java? with some cool and easy examples.

How to Take Input From User in Java?

In Java, you can take input from users using various methods. The most common way to take input from users is by using the Scanner class from the java.util package. Here’s a basic example of how to use Scanner to take input from the user:

import java.util.Scanner;

public class UserInputExample {
    public static void main(String[] args) {
        // Create a Scanner object to read input from the console
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter their name
        System.out.print("Enter your name: ");

        // Read the user's input as a String
        String name = scanner.nextLine();

        // Display a greeting message with the user's name
        System.out.println("Hello, " + name + "!");

        // Close the Scanner object to prevent resource leaks
        scanner.close();
    }
}

In this code:

We import the Scanner class from the java.util package.
We create a Scanner object named scanner to read input from the console.
We prompt the user to enter their name using System.out.print().
We use the nextLine() method of the Scanner object to read the user’s input as a String.
We display a greeting message with the user’s name using System.out.println().
Finally, we close the Scanner object using the close() method to release system resources.
Remember to handle exceptions appropriately, especially when working with input/output operations like reading from the console. The Scanner class might throw NoSuchElementException or IllegalStateException under certain conditions, so it’s good practice to handle these exceptions in your code.

output:
Enter your name: navya
Hello, navya!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top