You are here

How to take input from a user in Java

Java program to get input from a user: we are using Scanner class to get input from the user. This program asks the user to enter an integer, a float, and a string; then they are printed on the screen. Scanner class is present in java.util package so we import this package into our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement

 Scanner a = new Scanner(;

Here Scanner is the class name, a is the name of the object, new keyword is used to allocate the memory and is the input stream. Following methods of Scanner class are used in the program:

1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string

Java input program

  1. import java.util.Scanner;
  3. class GetInputFromUser
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int a;
  8.       float b;
  9.       String s;
  11.       Scanner in = new Scanner(;
  13.       System.out.println("Enter an integer");
  14.       a = in.nextInt();
  15.       System.out.println("You entered integer " + a);
  17.       System.out.println("Enter a float");
  18.       b = in.nextFloat();
  19.       System.out.println("You entered float " + b);  
  21.       System.out.println("Enter a string");
  22.       s = in.nextLine();
  23.       System.out.println("You entered string " + s);
  24.    }
  25. }

Output of program:
Output of Java program to get input from a user

Download User input program class file.

There are other classes which can be used for getting input from a user and you can also take input from other devices.