Javatpoint Logo
Javatpoint Logo

How to get input from user in Java

Java Scanner Class

Java Scanner class allows the user to take input from the console. It belongs to java.util package. It is used to read the input of primitive types like int, double, long, short, float, and byte. It is the easiest way to read input in Java program.

Syntax

The above statement creates a constructor of the Scanner class having System.inM as an argument. It means it is going to read from the standard input stream of the program. The java.util package should be import while using Scanner class.

It also converts the Bytes (from the input stream) into characters using the platform's default charset.

Methods of Java Scanner Class

Java Scanner class provides the following methods to read different primitives types:

Method Description
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double nextDouble() It is used to scan the next token of the input as a double.
byte nextByte() It is used to scan the next token of the input as a byte.
String nextLine() Advances this scanner past the current line.
boolean nextBoolean() It is used to scan the next token of the input into a boolean value.
long nextLong() It is used to scan the next token of the input as a long.
short nextShort() It is used to scan the next token of the input as a Short.
BigInteger nextBigInteger() It is used to scan the next token of the input as a BigInteger.
BigDecimal nextBigDecimal() It is used to scan the next token of the input as a BigDecimal.

Example of integer input from user

The following example allows user to read an integer form the System.in.

Output:

How to get input from user in Java

Example of String Input from user

Let's see another example, in which we have taken string input.

Output:

How to get input from user in Java
Next TopicJava Tutorial




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA