Scanner Class in Java

In this tutorial will learn about Scanner Class in Java with some cool and easy examples.

Scanner Class in Java

The Scanner class in Java, located in the java.util package, is a powerful tool for parsing input data from various sources such as the keyboard, files, or strings. It provides methods to read different types of data such as integers, floating-point numbers, strings, and more, from these input sources.

import java.util.Scanner;

public class ScannerExample {
    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 Java, Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings.

Using the Scanner class in Java is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.

output:
Enter your name: navya
Hello, navya!

 

Leave a Comment

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

Scroll to Top