How to take Integer Input in Java?

To take a Integer input in java, we need to use Scanner class in the program. In java Scanner class takes the input by nextInt() method that comes with a Pakage “java.util.Scanner”. nextInt() method scan and stores the data in the memory location.

If user try to take integer input then users need to declare

The syntex of the nextInt() function is –

public String nextInt();

Code for Taking Integer Input

Here we wrote a code that shows how Scanner class work with nextInt() method in Java.

// Code for taking integer input with nextInt() function.

import java.util.Scanner;
public class mainClass{
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        
        System.out.println("Enter a Number: ");
        
        int num = input.nextInt();
        
        System.out.println("You Entered: "+ num);
        
        input.close();
    }
}

Output

Enter a Number: 25
You Entered: 25

In the same way we use nextLine() function to take a String type input in Java program.

Leave a Comment