Data input methods in java: There are many data input methods in java like Hard coded values, through main method, with Scanner class, with Buffered Reader

click here for java videos

input methods in java

Hard Coded Values:-
The values are stored in a variable and  used later.

public class AddTwoNumbers 
    public static void main()
        int num1 = 5, num2 = 15, sum; 
        sum = num1 + num2; 
        System.out.println("Sum of numbers: "+sum);

This method is easy and žsimple but it gives same output every time

Taking values through main method

Pubic static void main(int a, int b)
    int sum=a+b;
    System.out.println(“The sum is”+sum);

This method is easy, simple, different values can be passed for each execution according the input.  It will give different output

 Scanner class:-
The scanner class is in util package so this statement is compulsory if you want to take input through scanner class.
import java.util.*;    Make an object of the class Scanner.
Scanner sc=new Scanner(;   It is used to take input through the keyboard using different methods according the data type.
The Scanner class methods are as follows.

boolean nextBoolean() To read a boolean value from the user
byte nextByte() To read a byte value from the user
double nextDouble() To read a double value from the user
float nextFloat() To read a float value from the user
int nextInt() To read an int value from the user
String nextLine() To read a String value from the user
long nextLong() To read a long value from the user
short nextShort() To read a short value from the user

Advantages žData is input at run time. žGives output according the input

import java.util.Scanner; 
public class AddTwoNumbers2 
     public static void main(String[] args)
    int num1, num2, sum; 
    Scanner sc = new Scanner(; 
    System.out.println("Enter First Number: "); 
   num1 = sc.nextInt(); 
   System.out.println("Enter Second Number: "); num2 = sc.nextint(); 
   sum = num1 + num2;
   System.out.println("Sum of these numbers: +sum); 

Enter First Number: 121
Enter Second Number: 19

Buffered Reader :
Buffered Reader class is used to take input in java. žIt has only one method to take input from the user at run time. žIt is in package. žThe object of the class is created with this syntax. ž
BufferedReader br=new BufferedReader(new InputStreamReader( ž
The input is taken in string form only.
Write a program to add two numbers (taking input with BufferedReader)

class Addition {
public static void main() throws Exception 
	int a, b, c;
	BufferedReader br = new BufferedReader(new InputStreamReader(;
	System.out.println("Enter the two numbers to add:");
	a = int.parseint(br.readLine());
	b = int.parseint(br.readLine());
	c = a + b;
	System.out.println("\n Sum of two numbers:" + c);

Enter the two numbers to add :2.3 3.5  
Sum of two numbers:   5.8

For more java tutorials click


Please enter your comment!
Please enter your name here