Getting Program Input from User in Java

(Last Updated On: February 24, 2019)

Learn how to get input from user / keyboard like int, string and double data types etc in java program. Example of taking integer / string input using scanner class in java.

We have learned how to print program output in java, now you are going to learn how to take input in a program from user.

To get the input from user, we use predefined Scanner class methods.

Some of the frequently used methods of Scanner class are as below, though there are many. you can follow java doc.

  • nextInt() // Read int value
  • nextFloat()// Read float value
  • next() // read first word on a string / sentence
  • nextLine() // Read complete string including spaces.
  • nextDouble(); //Read double value etc.


How to take integer input from user in Java

Steps you can follow to read an int value from user given below.

  • import java.util.Scanner;
  • Create an object of the Scanner class
  • Read the number using scanner method nextInt() using scanner class object.
  • Store in an int variable and print the output using out.println method

Reading a string input from User in java

In this section, you will learn how to take string input using scanner class in java program. To read a string / sentence from the user we use nextLine() method of scanner class.

Java Code:

Enter Your Name:
Rakesh Singh
You entered your name as Rakesh Singh



If you use next() method instead of nextLine(), then the program will read only first word of the string. So, in above example , only “Rakesh” string will be display on using next() method.


Reading Two Integers input from user in Java

Below program read two integers from user one by one. It prompt user to integer first and second number. The program displays the sum of both numbers entered by user. It will display the output as below


Enter first integer:
Enter Second integer:
Sum :50