JAVA NOTES-6
In this session we will learn the following
Input through keyboard using Command line Argument
Input through keyboard using BufferedReader class
Input through keyboard The Scanner class,.
From our earlier section, we know that we can pass input parameter by passing the arguments. L.
This section we discuss briefly how to take input from keyboard in java .
How to take input from Keyboard
Java offers various ways to input data from the keyboard as follows.
Command line argument
readLine() Method
Scanner class
Through Command Line:
We are using Command line for compiling and running the java code. To compile the java code
we need to run the below command.
javac <[Link]>
This will create the .class file which will be used to run the java code. To run we need to use
below command.
Java <filename>
In java, any code starts the execution with main() method. Without main() method Java program
execution will not start.
public static void main(String args[])
Here in the above statement, args[] is the array of String which stores the string argument
from the command line. During the execution of java program, we can pass this
command line argument with java code run command.
Java <filename> <argument>
Let’s us understand this with a simple example.
Example:
//File Name: [Link]
class DemoCommand{
public static void main(String args[]){
[Link](args[0])
}
}
Compile the above java program with the command
javac [Link]
The command line argument needs to be provided, during the execution phase as below. This should be
String type as we have String args[] in the main() method signature.
java DemoCommand Hello
Form the above command you can notice that we have passed the “Hello” String in command
line execution. As we have passed only one string it will take as 0th argument for main() method.
As args[] is an array, it will take the argument from command line with index and index will start
from 0 and will continue with 1,2,3,4 and so on.
What will happen if we want to pass the multiple argument in single command? Can we
do that?
Yes. Of course we can do this. We just need to pass multiple argument with comma separated.
Java DemoCommand Hello Computer Science
arg [0] arg [1] arg[2]
As the array index will starts from 0 and continue with 1,2,3,4 and so on,
if we will pass the index 1 in args[] array as args[1] in the println method command it
will print only “Computer” for the above command .
if we will pass the index 2 in args[] array as args [2] in the println method command it
will print only “Science” and so on as we send more arguments while running the
programme.
Here we need to remember that whatever input we pass from the command line; it
will take as String. If you want to take some int or float or any other except string
input from command line, you need to use separate method in code to convert this
to corresponding type from string.
Let’s understand how to pass integer value from command line argument for taking Input from
Keyboard and calculate factorial.
//File Name: [Link]
class DemoCommand{
public static void main(String args[]){
int intarg,fact=1;
if ([Link] > 0) {
intarg = [Link](args[0]);
for(int i=2;i<=intarg;i++)
fact=fact*I;
[Link]("The factorial is”+fact)
}
}
From the above example you can notice that we have used parseInt() method to convert from
String to Integer value.
Compile the programme with command javac [Link]
Execute the programme using command java DemoCommand 5
Command line argument
Output: The Factorial is 120
readLine() Method
This is not the inbuilt method available in java. This method is available in [Link] package. So
we need to import this package before using readLine() method.
Syntax:
Public String readLine() throws IOException{
------------
------------
}
readLine() method will throw an Exception called IOException. To handle this
IOException, we need to mention throws with the method signature. This readLine() is
present in BufferedReader and InputStreamReader class. And both these classed are
available inside the [Link] package.
You will learn about Exception Handling later in syllabus.
The return type of this method is String as you can notice in the method signature. Let’s
understand this with a simple example.
Example:
import [Link].*;
class Inputwithreadline{
public static void main(String args[]) throws IOException{
InputStreamReader is = new InputStreamReader([Link]);
BufferedReader br = new BufferedReader(is);
[Link]("Enter the Input from Keyboard: ");
String inpt = [Link]();
[Link]("You have entered: "+ inpt);
}
}
Output:
Enter the Input from Keyboard:
Sushree
You have entered: Sushree
Explanation
From the above example, you can notice that we have used 2 classes.
One is InputStreamReader and other is BufferedReader.
First we have created the object reference of InputStreamReader and then will pass this
object to BufferedReader object instance.
After that we have used the readLine() method which help to take input from Keyboard.
Here [Link] is in the Keyboard and InputStreamReader behaves like a channel connected to
[Link]() method takes the input from keyboard and stores in the String format.
Keyboard Input Using Scanner class in java.
Scanner class:
Scanner class has lots of benefits over the readLine() method. It can accept all types of
input from keyboard including, Numeric, String and other types. It actually reads the formatted
input and converts it into binary form.
In Java, Scanner class is present inside the [Link] package. It is the easiest way to handle the
input from Keyboard.
We need to remember some points when we will work on the scanner class.
We need to pass the predefined object [Link] when we will create the object of Scanner
class. [Link] is nothing but represented as Standard Input Stream. If we want to take
input from file, then we can pass the object of corresponding class file.
When we will ready data of Int from keyboard, we need to use nextInt() method. Like int
we can user nextFloat(), nextShort() etc to read float, short data type respectively.
But to read String data type we need to use nextLine(). Line will considered for String
datatype.
We are having some constructor for Scanner class which is used to take input from Keyboard.
Constructor:
FileReader fr = new FileReader(“[Link]”) To read from a file
Scanner s1 = new Scanner(fr)
Scanner s2 = new Scanner([Link]) To read from Keyboard
String s = “TestingLpoint” To read from a String
Scanner s3 = new Scanner(s)
We are having many methods which will help us to handle the input from keyboard and file
while using the Scanner class as shown in table below.
Method Description
boolean hasNext() Return “TRUE” if a token of any type is
available for read
boolean Return “TRUE” if a Byte value is
hasNextByte() available for read
boolean Return “TRUE” if a Short value is
hasNextShort() available for read
boolean hasNextInt() Return “TRUE” if a Int value is
available for read
boolean Return “TRUE” if a Float value is
hasNextFloat() available for read
boolean hasNextLong Return “TRUE” if a Long value is
() available for read
boolean Return “TRUE” if a Double value is
hasNextDouble() available for read
boolean Return “TRUE” if a Line is available
hasNextLine() for read
String next() Return the next token of any type from
the input source
boolean Return the next token as boolean value
nextBoolean()
byte nextByte() Return the next token as short value
short nextShort() Return the next token as byte value
int nextInt() Return the next token as int value
long nextLong() Return the next token as long value
double nextDouble() Return the next token as double value
String nextLine Return the next line of the input as
String
Let’s understand with an Example.
To work with Scanner class for taking Input from Keyboard dynamically, we need to remember
some points as below
It is determined if a specific type of input is availability by calling one of Scanner’s
hasNext() method.
If input is available, it is to be calling one of the Scanner’s next() method
The Process is to be repeated until the input is exhausted.
Example:
import [Link].*;
class Try{
public static void main(String args[]){
Scanner sc= new Scanner([Link]);
[Link]("Enter a Number from Keyboard: ");
int i = [Link]();
[Link]("Output is: "+ i);
}
}
Output:
Enter a Number from Keyboard:
34
Output is: 34
Explanation:
Here you can see that we have created the object for Scanner class. As Scanner is not the part of
core, we have to import this before use. [Link] is referring to take the input from the
Keyboard command line. nextInt is checking the available next integer in command line. As it
found 34, it returns 34 and assign to the variable i.
What if we will give a String or character in the output instead of giving integer value?
Example
import [Link].*;
class Try{
public static void main(String args[]){
Scanner sc= new Scanner([Link]);
[Link]("Enter a Number from Keyboard: ");
int i = [Link]();
[Link]("Output is: "+ i);
} }
Output: Wrong Input
Like this other methods will be implemented to byte, short, String, double, float data type.
Summary
There are 3 ways for taking Input from Keyboard dynamically.
args[] in main method is the array of String which stores the string argument from the
command line.
An array index will starts from 0 and continue with 1,2,3,4 and so on.
As parseInt() will throw an Exception named NumberFormatException we need to define
the try catch block to handle NumberFormatException Exception.
readLine() method is not the inbuilt method available in java. This method is available in
[Link] package. So we need to import this package before using readLine() method.
[Link] is in the Keyboard and InputStreamReader behaves like a channel connected to
[Link]() method takes the input from keyboard and stores in the String format.
We need to pass the predefined object [Link] when we will create the object of Scanner
class. System. In is nothing but represented as Standard Input Stream. If we want to take
input from file, then we can pass the object of corresponding class file.
When we will ready data of Int from keyboard, we need to use nextInt() method. Like int we
can user nextFloat(), nextShort() etc to read float, short data type respectively.
But to read String data type we need to use nextLine(). Line will considered for String
datatype.
This finishes your UNIT-1 of Java Syllabus..….Hope notes will help you to
prepare for exam. I will stop here. Check with your HoD if he does any
arrangement for class, otherwise get back to me if required. All the best.