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.
We first create an object of Scanner class and then we use the
methods of Scanner class.
Syntax:
Scanner sc=new Scanner(System.in);
Here Scanner is the class neme, sc is the name of object, new
keyword is used to allocate the memory and System.in is the input
stream.
The java.util package should be import while using Scanner class.
Ex: import java.util.Scanner;
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.
Example :
import java.util.*;
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
}
}