get user input

How to get User Input in Java?

In this chapter you will learn:get user input

  1. How to get Integer Input?
  2. How to get String Input?
  3. How to get Float Input?

This chapter demonstrates how to get user input in java. Various times while programming in java you need to accept some value from the user end. This value might be integer, string or float. As a java programmer you must know the input mechanism of java. Once you will finish this chapter, I am sure you will be master in accepting input in Java.

How to get user input in java?

To get input in java there are several classes which allow you to accept user end data but the most popular way is using Scanner Class.

Scanner Class

It is the most popular way to accept user input. Scanner class uses following method to accept different types of data. You must import java.util.Scanner class before using scanner method.



MethodDescription only one string and break when white space detected.
sc.nextLine()Accept full line of string with white space.
sc.nextByte()Accept byte data and store in byte variable.
sc.nextShort()Accept short data and store in short variable.
sc.nextInt()Accept number and store in integer variable.
sc.nextLong()Accept long value and store it in long variable.
sc.nextFloat()Accept float value and store it in float variable.
sc.nextDouble()Accept double value and store it in double variable.

Here we are writing a program which accept some user input and print the output. The program will ask following details from the user.

Mobile No:

Programming Example



D:\JavaProgram>java ScannerClass
Enter Your Name:
Christian Bale
Enter your 4 Digit Pin Number:
Enter your age:
Enter your Mobile Number:

********************User Details**********************
Name : Christian Bale
Pin : 8841
Age : 40
MobileNumber : 878765642

D:\JavaProgram> __


In the above example we added Scanner Library to program so that we can use Scanner class.

After that we have used several Scanner Object methods for accepting different types of value as


In this chapter you have learned how to accept user input in java. In the next chapter you will learn to define classes, objects and methods in java.

Leave a Reply

Your email address will not be published. Required fields are marked *