Accepting input in JAVA

 

There are 3 most used ways of accepting input in java are :-

  1. Command Line
  2. BufferedReader
  3. Scanner

1. Command Line

The main() method is capable of accepting arrays of strings recollect this syntax

public static void main(String args[])

Hence we can pass parameters while executing the program.

These arguments are generally used by main() method as input from the user.

Note that the input accepted from user through command line has data type String, hence if we want to convert this String to another data type(say integer or float) we must use the wrapper classes.

Let us take a program in which we take user input through command line

Program

Output

 

 

2. BufferedReader

In java the BufferedReader class is used to read the text from a character based input stream.

The readLine() method in the BufferedReader class is use to accept string from the user.

Note : Import package java.io when using BufferedReader class and also while using readLine() method do not forget that it throws an IOException

Program

Output

 

 

3. Scanner

The Scanner class in java breaks the input into tokens by using a whitespace as a delimiter.

Note – Do not forget to import package java.util as this package contains the Scanner class

scannerclass_table_1

Check this link if you want to know how is it used in the program

Share Me!
  •  
  •  
  •  
  •  
  •  
  •