How To Pass Input From A Console To A Java Program ?.

In this section of blog, we will look into a tutorial and a simple Java program, explaining how to pass input from a console to a Java program. Usually, Input is given to the program from the standard input device called as keyboard. In Java reading an input is not as simple as output. Java API is full of several classes which can be used for the purpose of reading the input from a keyboard. is a predefined stream object which can be used to read input. But is a byte oriented stream, it can be used only to

read bytes. In order to make it read characters we usually wrap it across a character oriented stream called as InputStreamReader. InputStreamReader is a reader class which is been used to read characters. For reading the input as string we wrap this byte stream to BufferedReader which buffers characters.

In order to apply above concepts to these streams we follow these steps :


1. BufferedReader br = new BufferedReader(new

2. InputStreamReader isr = new InputStreamReader(;
BufferedReader br = new BufferedReader(isr);


In order to read a string, we use method readLine on the BufferedReader object as


String read = br.readLine();


Program to demonstrate how to pass input from console to a Java program in order to calculate

sum and average of numbers as wished by user


package com.hubberspot.streams.example;

public class ConsoleReader {

public static void main(String[] args) throws IOException {

int number, sum=0, n, i;
float avg;

BufferedReader br = new BufferedReader(
new InputStreamReader(;

System.out.println("How many numbers? ");

n = Integer.parseInt(br.readLine());

for(i=0; i<n ; i++)
System.out.println("Enter number " + (i+1));

number = Integer.parseInt(br.readLine());
sum += number;

avg = sum / n;

System.out.println("Sum of numbers is = " + sum);
System.out.println("Average of numbers is = "+ avg);





For more of such hot topics read my other posts here :

Visit my new website

Article Written By jontymagicman

I am DInesh Varyani.

Last updated on 26-07-2016 108 0

Please login to comment on this post.
There are no comments yet.
Interfaces Vs Abstract Classes In Java
Program To Demonstrate How To Do Binary Search In Java