How to Take Integer Input in Java

This article discusses the methods to take the integer input in Java.

Variables

In programs, data values are reserved in memory locations that can be identified by names (identifiers). Such named memory location which temporarily reserves data that can be changed while the program is running is called a variable.

Let’s see how variables are declared using Data types, Identifiers \& Values.

datatype identifier = value

In detail, let’s look at different data types in the diagram below.

Data types are mainly of two kinds:

  1. Primitive Data Types
  2. Non-Primitive Data Types.

In this article, we will see what is integer and how to take integer input in java.

What is Integer?

  • An integer is a primitive data type.
  • int keyword is used to define integer data type variable.
  • Integer data types have the size of 4 bytes.
  • The range of integer data type is -2^31 to 2^31 – 1.

For example:

How to take integer input?

Java Scanner class

We can take input as an integer from a user, with the help of the Scanner class. In java.util package Scanner class is present. It can also be used to take input as an integer, short, byte, double, float, string, etc.

By creating an object of the Scanner class we can use any method of the Scanner class.

Syntax:

The above line of code creates a constructor of the Scanner class. That constructor has an argument as System.in. That means it will read from the standard input stream of the program. java.util package needs to import while using Scanner class in a program.

Java Scanner class provides the different methods to read different primitives types. For example: intis read using nextInt(), floatis read using nextFloat(), double is read using nextDouble(), and String is read using nextLine() etc.

Java Program to to take Integer input in Java

We need to import java.util.Scanner class to use Scanner. To read integer input from the user first need to create an object of Scanner class by passing System.in.

Then with the help of nextInt() method of the Scanner class, we can store the value in a num integer variable. It’s best practice to close the Scanner object with the help of the close() method. Finally, we are printing the value of num.

Output:

While executing the program, it will ask to enter a number in the console. Enter the input in the console. Then it will print the value of the entered number.

Enter integer number: 32
The number entered by user is: 32

Conclusion

In this article, we learned how to declare, initialize and take integers from users with the help of the Scanner class. Using the nextInt() method of the Scanner class we can take input from the console and store the value in the Integer variable.

This is all about taking an integer input in Java.

Hope you enjoyed reading the article. Stay tuned for more articles. Happy Learning!

Was this post helpful?

Leave a Reply

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