Getting input from user in java


We discuss pre requirements, “Hello world” program and execution steps in previous post. Here we will discuss about getting input (Both String and Integer) from user.

In java we don’t have the datatypes as char. Instead of char we got String datatype, by using this datatype we can get both char ( ‘y’ ) and string (‘yes’) from user.

As we know already Java is the case sensitive language. So, In string ‘S’ should be capital. For getting input in java we can use Scanner class and DataInputStream class. Both class works on same things. We discuss one by one.

Scanner class:

We should import the package “ java.io.*;” into our program. Then we can use both the above classes. We should create object for the classes to access it.

Scanner obj_name = new Scanner(System.in);

Once we create the object for scanner class, we get access to that class. “System.in” represents that gonna get input.

In the same way DataInputStream also working

DataInputStream data = new DataInputStream(System.in);

If we use DataInputStream class to get input. We should use “try catch block” in our program as shown in the flowing picture.


Getting string input from user.

The above picture represents getting string input from the user. ‘ds’ is the object created for the DataInputStream class. By using this object we will get the input through readLine() (“ To read the user input.”)method. To print the output should use this statement.

System.out.println(“Statement to display“+Variable_name);

‘+’ is used to concatenate the variable to the statement to be display.


We have to make one small changes in the previous program to get the integer as input. Integer.parseInt is used to used to convert the string to integer. Usually java consider any input as string we have to convert that to int. So, we have to use this statement Integer.parseInt  





Getting integer input from user

The following video will demonstrate the above functionality here. Thank you.



Labels: , , ,