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 for it. The program asks the user to enter an integer, a floating-point number, and a string, and we print them on the screen. Scanner class is present in "java.util" package, so we import this package into our program. We create an object of the class to use its methods.

Consider the statement

 Scanner x = new Scanner(System.in);

Here, x is the name of the object, the new keyword is used to allocate memory, and System.in is the input stream. Our program uses the following three methods:

1) nextInt to input an integer
2) nextFloat to input a floating-point number
3) nextLine to input a string

Java input program

import java.util.Scanner;

class Input
{
   public static void main(String args[])
   {
      int a;
      float b;
      String s;
     
      Scanner in = new Scanner(System.in);
     
      System.out.println("Enter an integer");
      a = in.nextInt();
      System.out.println("You entered integer " + a);
     
      System.out.println("Enter a float");
      b = in.nextFloat();
      System.out.println("You entered float " + b);  
   
      System.out.println("Enter a string");
      s = in.nextLine();
      System.out.println("You entered string " + s);
   }
}

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

Download User input program class file.

You can get input from a user using other classes and also from devices.