0d: 00h: 00m: 00s

🎁 Get 3 extra months of learning — completely FREE

That's 90 extra days to master new skills, build more projects, and land your dream job.

Become a PRO
Background Image

🎁 Get 3 extra months of learning completely FREE

Become a PRO
S
PRO
3 months ago
Siddharthacountry asked

Why do we us "Scanner" in Java? Is it a keyword? And what's "nextInt"? I couldn't understand their uses.

Saujanya Poudel
Expert
yesterday

The Scanner class is not a keyword; it's a class in Java that helps us read input (like numbers or strings) from the user.

Think of this Scanner class as a utility whose main function is to read text input from the keyboard.

Scanner also has a smaller utility element within it called nextInt, which parses the input text it reads as an integer. (Technically, nextInt() is a method but there's no need to learn about that right now).

Let's clarify with the following example:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        System.out.print("Enter a number: ");

        // Create a Scanner object named 'input'
        Scanner input = new Scanner(System.in);

        // Get an integer input using the Scanner object
        int num = input.nextInt();

        // Print the input number
        System.out.println(num);
    }
}

Here, we've created an object of the Scanner class named input (usually, you need to create an object of a class in order to use the utilities inside that class).

Then, we used the nextInt() method to read integer input and store it in the num variable.

When you print num, you'll see that it prints the same number that you gave as input.

Hope that helps!

Java
This question was asked as part of the Learn Java Basics course.