Taking Input in Java

Sometimes we have to do operations on the basis of user input. For example, we made the calculator software. So our user can do whatever calculations they want. For that, we have to take input from user. In this topic, we will know how to take different data as input from user.

How this works?

To take input, we have a class named, Scanner. Scanner class is present in "java.util" package, so we have to import this package into our program. We create an object of the class to use its methods.

Because we haven't learnt package, class and object yet, it may sound confusing to you. But don't worry, for now just remember the steps.

At the very begining of our program, we have to import "java.util" package. We can do so by:

import java.util.Scanner;
Here, "java.util" is package and "Scanner" is method present in that class.

Then inside our main method, we have to create a object of "Scanner" class. We can do so by:

Scanner inp = new Scanner(System.in);
Here, inp is the name of the object. You may keep whatever (identifiers) you want. The new keyword is used to create object and allocate memory same as data type. Finally, System.in is the input stream.

Finally, we can get input from user using method according to data type. We can do so by:

int a = inp.nextInt();
Here, we are storing input in a variable. nextInt() is method in Scanner class. And we are accessing that method by object we created earlier.

Note that we have different methods to take different data type input, and we have to choose variable data type as per the input type.

Input Types

Data TypeMethod



import java.util.Scanner; public class TakingInput { public static void main(String[] args) { Scanner inp = new Scanner(System.in); System.out.println("Enter name: "); String name = inp.nextLine(); System.out.println("Enter Age: "); int age = inp.nextInt(); System.out.println("Enter Salary: "); double salary = inp.nextDouble(); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); } }


Enter name:
BCA Boost
Enter Age:
Enter Salary:
Name: BCA Boost
Age: 2
Salary: 0.0

Math in Java Previous Next Decision Making in Java