in this tutorial we will learn how java get input from user in java. java brings various streams with its I/O package which helps the user to perform all input-output operations. These streams support all types of objects, data types, characters, files, etc. to perform I/O operations. It can take input in four ways, either from the user or from a file
BufferReader class
Scanner class
Using Console Class
Using File Handling
Java Scanner Class
Syntax
import java.util.*;
class AdditonDemo
{
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();
int c = a + b ;
System.out.println(" Addition of two numbers is =
" +c);
}
}
java -cp /tmp/L4TkW7X9nO AdditonDemo
Enter first number 23
Enter second number 23
Addition of two numbers is = 46
Methods of Java Scanner Class
Method |
Description |
int
nextInt() |
This method used to scan the next token of the input as an integer. |
float
nextFloat() |
This method used to scan the next token of the input as a float. |
double
nextDouble() |
This method used to scan the next token of the input as a double. |
byte
nextByte() |
This method 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() |
This method 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() |
This method used to scan the next token of the input as a BigInteger. |
BigDecimal
nextBigDecimal() |
This method used to scan the next token of the input as a BigDecimal. |