SlideShare a Scribd company logo
Page 1 of 9
Class Notes on Command line arguments and basics of I/O
operations (Week - 5)
Contents: - What are Command Line Arguments? How to use them? Keyboard input using BufferedReader & Scanner
classes
Command Line Arguments
During program execution, information passed following a programs name in the command line is called
Command Line Arguments. Java application can accept any number of arguments directly from the command
line. The user can enter command-line arguments when invoking the application. When running the java
program from java command, the arguments are provided after the name of the class separated by space.
Example : While running a class Demo, you can specify command line arguments as
java Demo arg1 arg2 arg3 …
class Demo{
public static void main(String b[]){
System.out.println("Argument one = "+b[0]);
System.out.println("Argument two = "+b[1]);
}
}
Run the code as javac Demo apple orange
You must get an output as below.
A Java application can accept any number of arguments from the command line. This allows the user to
specify configuration information when the application is launched.
The user enters command-line arguments when invoking the application and specifies them after the name of
the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a
file named friends.txt, a user would enter:
java Sort friends.txt
Page 2 of 9
When an application is launched, the runtime system passes the command-line arguments to the application's
main method via an array of Strings. In the previous example, the command-line arguments passed to the Sort
application in an array that contains a single String: "friends.txt".
Command Line Arguments Important Points:
 Command Line Arguments can be used to specify configuration information while launching your
application.
 There is no restriction on the number of command line arguments. You can specify any number of
arguments
 Information is passed as Strings.
 They are captured into the String argument of your main method
How to use command line arguments in java program
Consider the following example. The number of arguments passed during program execution is stored in the
length field of argument name (commonly it is args, note we use String[] args in main method of any
java program)
class CmndLineArguments {
public static void main(String[] args) {
int length = args.length;
if (length <= 0) {
System.out.println("You need to enter some arguments.");
}
System.out.println("Command line arguments were passed:");
for (int i = 0; i < length; i++) {
System.out.println(args[i]);
}
}
}
Output of the program:
Run program with some command line arguments like:
C:>java CmndLineArguments Mahendra zero one two three
OUTPUT
Command line arguments were passed :
Mahendra
zero
one
two
three
Page 3 of 9
How Java Application Receive Command-line Arguments
In Java, when you invoke an application, the runtime system passes the command-line arguments to the
application‘s main method via an array of Strings.
public static void main( String[] args )
Each String in the array contains one of the command-line arguments.
args[ ] array
Consider a java program sort, which sorts some numbers entered as Command Line Arguments. We run:
java Sort 5 4 3 2 1
the arguments are stored in the args array of the main method declaration as…
Conversion of Command-line Arguments
• If your program needs to support a numeric command-line argument, it must convert a String
argument that represents a number, such as "34", to a number. Here's a code snippet that converts a
command-line argument to an integer,
int firstArg = 0;
if (args.length > 0){
firstArg = Integer.parseInt(args[0]);
}
The parseInt() method is used to get the primitive data type of a certain String. parseInt(String s): This returns
an integer (decimal only). For example consider the following example. The string 9 is converted to int 9.
public class Test{
public static void main(String args[]){
int x =Integer.parseInt("9");
}
}
All of the Number classes — Integer, Float, Double, and so on — have parseXXX methods that convert a String
representing a number to an object of their type.
Command-line Arguments Coding Guidelines:
• Before using command-line arguments, always check the number of arguments before accessing the
array elements so that there will be no exception generated.
• For example, if your program needs the user to input 5 arguments,
Page 4 of 9
Another example
class StringCLA{
public static void main(String args[]){
int length=str.length;
if (length<=0){
System.out.println("Enter Some String.");
}
for(int i=0;i<length;i++){
System.out.println(str[i]);
}
}
}
c:> javac StringCLA.java
c:>java StringCLA Its Work !!!
Its
Work
!!!
Note: The application displays each word- Its, Work, and !!!-- on a line by itself. This is because the space
character separates command-line arguments. To have Its, Work, and !!! interpreted as a single argument, the
user would join them by enclosing them within quotation marks.
c:>java StringCLA "Its Work !!!"
Its Work !!!
Reading data from keyboard by InputStreamReader and BufferedReader class:
InputStreamReader class can be used to read data from keyboard. It performs two tasks:
 connects to input stream of keyboard
 converts the byte-oriented stream into character-oriented stream
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.
Page 5 of 9
Example of reading data from keyboard by InputStreamReader and BufferdReader class:
In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for
reading the line by line data from the keyboard.
//Program of reading data
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter ur name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:
Enter ur name
Amit
Welcome Amit
Another Example of reading data from keyboard by InputStreamReader and BufferdReader class
until the user writes stop
In this example, we are reading and printing the data until the user prints stop.
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close(); // BufferedReader Stream is Closed
r.close(); // InputStreamReader Stream is Closed
}
}
Output:
Enter data: Amit
data is: Amit
Enter data: 10
Page 6 of 9
data is: 10
Enter data: stop
data is: stop
The following figure shows how the stream flows from device buffer to System.in, InputStreamReader object r
and then to BufferedReader object r, and at last to the java program.
Class InputStreamReader
public class InputStreamReader
extends Reader
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them
into characters using a specified charset. The charset that it uses may be specified by name or may be given
explicitly, or the platform's default charset may be accepted.
Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read
from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes
may be read ahead from the underlying stream than are necessary to satisfy the current read operation.
For top efficiency, consider wrapping an InputStreamReader within a BufferedReader. For example:
BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));
Class BufferedReader
public class BufferedReader
extends Reader
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of
characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for most
purposes.
Page 7 of 9
In general, each read request made of a Reader causes a corresponding read request to be made of the
underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader
whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could
cause bytes to be read from the file, converted into characters, and then returned, which can be very
inefficient.
Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream
with an appropriate BufferedReader.
Input from the keyboard by java.util.Scanner class:
There are various ways to read input from the keyboad, the java.util.Scanner class is one of them. The Scanner class
breaks the input into tokens using a delimiter which is whitespace bydefault. It provides many methods to read and
parse various primitive values.
Commonly used methods of Scanner class:
There is a list of commonly used Scanner class methods:
 public String next(): it returns the next token from the scanner.
 public String nextLine(): it moves the scanner position to the next line and returns the value as a string.
 public byte nextByte(): it scans the next token as a byte.
 public short nextShort(): it scans the next token as a short value.
 public int nextInt(): it scans the next token as an int value.
 public long nextLong(): it scans the next token as a long value.
 public float nextFloat(): it scans the next token as a float value.
 public double nextDouble(): it scans the next token as a double value.
Example of java.util.Scanner class:
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
}
}
Page 8 of 9
Output:
Enter your rollno
111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000
Class Scanner
public final class Scanner
extends Object
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The
resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
As another example, this code allows long types to be assigned from entries in a file myNumbers:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("s*fishs*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace.
A scanning operation may block waiting for input.
Page 9 of 9
The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt())
first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext
and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to
whether or not its associated next method will block.
Another example showing the use of hasNext(), next() and nextLine():
Source Code Output of the Program
import java.util.Scanner;
class hasNextExample
{
public static void main(String agrs[]) {
String stest=new String("This is an example!!!");
Scanner sc=new Scanner(stest);
while(sc.hasNext()) {
System.out.println(sc.next());
}
}
}
D:java1>javac hasNextExample.java
D:java1>java hasNextExample
This
is
an
example!!!
D:java1>
import java.util.Scanner;
class hasNextExample
{
public static void main(String agrs[]) {
String stest=new String("This is an example!!!");
Scanner sc=new Scanner(stest);
while(sc.hasNext()) {
System.out.println(sc.nextLine());
}
}
}
D:java1>javac hasNextExample.java
D:java1>java hasNextExample
This is an example!!!
D:java1>

More Related Content

PPTX
Full Python in 20 slides
rfojdar
 
DOCX
Class notes(week 5) on command line arguments
Kuntal Bhowmick
 
PPT
Exercises for ja se
sshhzap
 
PPTX
Java OOP Concepts 1st Slide
sunny khan
 
PPTX
Java Input and Output
Ducat India
 
PPTX
Java platform
Visithan
 
PPTX
I/O Streams
Ravi Chythanya
 
PDF
Data file handling
Prof. Dr. K. Adisesha
 
Full Python in 20 slides
rfojdar
 
Class notes(week 5) on command line arguments
Kuntal Bhowmick
 
Exercises for ja se
sshhzap
 
Java OOP Concepts 1st Slide
sunny khan
 
Java Input and Output
Ducat India
 
Java platform
Visithan
 
I/O Streams
Ravi Chythanya
 
Data file handling
Prof. Dr. K. Adisesha
 

What's hot (20)

PPSX
Object oriented concepts & programming (2620003)
nirajmandaliya
 
DOCX
Oodp mod4
cs19club
 
PDF
Writing Usable APIs in Practice by Giovanni Asproni
SyncConf
 
PDF
Introduction to c++
Prof. Dr. K. Adisesha
 
PPTX
Operator Overloading and Scope of Variable
MOHIT DADU
 
PDF
A COMPLETE FILE FOR C++
M Hussnain Ali
 
PPT
Chap03
Terry Yoast
 
PPT
Chap03
Terry Yoast
 
KEY
What's New In Python 2.4
Richard Jones
 
PPTX
Java 8
Sudipta K Paik
 
PPT
ppt on scanner class
deepsxn
 
PPT
Object-Oriented Programming Using C++
Salahaddin University-Erbil
 
KEY
What's New In Python 2.5
Richard Jones
 
PPT
Chapter 2 java
ahmed abugharsa
 
PPTX
Unit 1
donny101
 
PPT
Java stream
Arati Gadgil
 
PPTX
Python
Aashish Jain
 
PPT
Of Lambdas and LINQ
BlackRabbitCoder
 
PPTX
Chap2java5th
Asfand Hassan
 
PPT
Java Streams
M Vishnuvardhan Reddy
 
Object oriented concepts & programming (2620003)
nirajmandaliya
 
Oodp mod4
cs19club
 
Writing Usable APIs in Practice by Giovanni Asproni
SyncConf
 
Introduction to c++
Prof. Dr. K. Adisesha
 
Operator Overloading and Scope of Variable
MOHIT DADU
 
A COMPLETE FILE FOR C++
M Hussnain Ali
 
Chap03
Terry Yoast
 
Chap03
Terry Yoast
 
What's New In Python 2.4
Richard Jones
 
ppt on scanner class
deepsxn
 
Object-Oriented Programming Using C++
Salahaddin University-Erbil
 
What's New In Python 2.5
Richard Jones
 
Chapter 2 java
ahmed abugharsa
 
Unit 1
donny101
 
Java stream
Arati Gadgil
 
Python
Aashish Jain
 
Of Lambdas and LINQ
BlackRabbitCoder
 
Chap2java5th
Asfand Hassan
 
Java Streams
M Vishnuvardhan Reddy
 
Ad

Similar to Class notes(week 5) on command line arguments (20)

PPTX
Getting Program Input
Dr. Rosemarie Sibbaluca-Guirre
 
PPTX
Reading and writting v2
ASU Online
 
PPTX
Reading and writting
andreeamolnar
 
PDF
Java Fundamentals
Shalabh Chaudhary
 
PPT
Command line arguments.21
myrajendra
 
PPTX
JAVA (UNIT 3)
Dr. SURBHI SAROHA
 
PDF
Learn Java Part 4
Gurpreet singh
 
PPT
7 streams and error handling in java
Jyoti Verma
 
PPTX
java: basics, user input, data type, constructor
Shivam Singhal
 
PPT
2 1 data
Ken Kretsch
 
PPTX
L21 io streams
teach4uin
 
PDF
Command line-arguments-in-java-tutorial
Kuntal Bhowmick
 
PPT
Stream Based Input Output
Bharat17485
 
PPTX
Stream In Java.pptx
ssuser9d7049
 
PPT
Java ppt
Rohan Gajre
 
PDF
Lecture 2 java.pdf
SantoshSurwade2
 
PPS
Java session08
Niit Care
 
PPTX
Basics java programing
Darshan Gohel
 
PPTX
Java Basics 1.pptx
TouseeqHaider11
 
PDF
Java I/O
Jussi Pohjolainen
 
Getting Program Input
Dr. Rosemarie Sibbaluca-Guirre
 
Reading and writting v2
ASU Online
 
Reading and writting
andreeamolnar
 
Java Fundamentals
Shalabh Chaudhary
 
Command line arguments.21
myrajendra
 
JAVA (UNIT 3)
Dr. SURBHI SAROHA
 
Learn Java Part 4
Gurpreet singh
 
7 streams and error handling in java
Jyoti Verma
 
java: basics, user input, data type, constructor
Shivam Singhal
 
2 1 data
Ken Kretsch
 
L21 io streams
teach4uin
 
Command line-arguments-in-java-tutorial
Kuntal Bhowmick
 
Stream Based Input Output
Bharat17485
 
Stream In Java.pptx
ssuser9d7049
 
Java ppt
Rohan Gajre
 
Lecture 2 java.pdf
SantoshSurwade2
 
Java session08
Niit Care
 
Basics java programing
Darshan Gohel
 
Java Basics 1.pptx
TouseeqHaider11
 
Ad

More from Kuntal Bhowmick (20)

PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Kuntal Bhowmick
 
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Kuntal Bhowmick
 
PDF
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Kuntal Bhowmick
 
PPT
1. introduction to E-commerce
Kuntal Bhowmick
 
DOCX
Computer graphics question for exam solved
Kuntal Bhowmick
 
PDF
DBMS and Rdbms fundamental concepts
Kuntal Bhowmick
 
PDF
Java questions for interview
Kuntal Bhowmick
 
PDF
Java Interview Questions
Kuntal Bhowmick
 
PDF
Operating system Interview Questions
Kuntal Bhowmick
 
PDF
Computer Network Interview Questions
Kuntal Bhowmick
 
PDF
C interview questions
Kuntal Bhowmick
 
PDF
C question
Kuntal Bhowmick
 
PDF
Distributed operating systems cs704 a class test
Kuntal Bhowmick
 
DOCX
Cs291 assignment solution
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Kuntal Bhowmick
 
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Kuntal Bhowmick
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Kuntal Bhowmick
 
1. introduction to E-commerce
Kuntal Bhowmick
 
Computer graphics question for exam solved
Kuntal Bhowmick
 
DBMS and Rdbms fundamental concepts
Kuntal Bhowmick
 
Java questions for interview
Kuntal Bhowmick
 
Java Interview Questions
Kuntal Bhowmick
 
Operating system Interview Questions
Kuntal Bhowmick
 
Computer Network Interview Questions
Kuntal Bhowmick
 
C interview questions
Kuntal Bhowmick
 
C question
Kuntal Bhowmick
 
Distributed operating systems cs704 a class test
Kuntal Bhowmick
 
Cs291 assignment solution
Kuntal Bhowmick
 

Recently uploaded (20)

PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
PPT
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
PDF
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PDF
Software Testing Tools - names and explanation
shruti533256
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PPTX
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PDF
top-5-use-cases-for-splunk-security-analytics.pdf
yaghutialireza
 
PDF
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
Software Testing Tools - names and explanation
shruti533256
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
top-5-use-cases-for-splunk-security-analytics.pdf
yaghutialireza
 
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 

Class notes(week 5) on command line arguments

  • 1. Page 1 of 9 Class Notes on Command line arguments and basics of I/O operations (Week - 5) Contents: - What are Command Line Arguments? How to use them? Keyboard input using BufferedReader & Scanner classes Command Line Arguments During program execution, information passed following a programs name in the command line is called Command Line Arguments. Java application can accept any number of arguments directly from the command line. The user can enter command-line arguments when invoking the application. When running the java program from java command, the arguments are provided after the name of the class separated by space. Example : While running a class Demo, you can specify command line arguments as java Demo arg1 arg2 arg3 … class Demo{ public static void main(String b[]){ System.out.println("Argument one = "+b[0]); System.out.println("Argument two = "+b[1]); } } Run the code as javac Demo apple orange You must get an output as below. A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched. The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt, a user would enter: java Sort friends.txt
  • 2. Page 2 of 9 When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String: "friends.txt". Command Line Arguments Important Points:  Command Line Arguments can be used to specify configuration information while launching your application.  There is no restriction on the number of command line arguments. You can specify any number of arguments  Information is passed as Strings.  They are captured into the String argument of your main method How to use command line arguments in java program Consider the following example. The number of arguments passed during program execution is stored in the length field of argument name (commonly it is args, note we use String[] args in main method of any java program) class CmndLineArguments { public static void main(String[] args) { int length = args.length; if (length <= 0) { System.out.println("You need to enter some arguments."); } System.out.println("Command line arguments were passed:"); for (int i = 0; i < length; i++) { System.out.println(args[i]); } } } Output of the program: Run program with some command line arguments like: C:>java CmndLineArguments Mahendra zero one two three OUTPUT Command line arguments were passed : Mahendra zero one two three
  • 3. Page 3 of 9 How Java Application Receive Command-line Arguments In Java, when you invoke an application, the runtime system passes the command-line arguments to the application‘s main method via an array of Strings. public static void main( String[] args ) Each String in the array contains one of the command-line arguments. args[ ] array Consider a java program sort, which sorts some numbers entered as Command Line Arguments. We run: java Sort 5 4 3 2 1 the arguments are stored in the args array of the main method declaration as… Conversion of Command-line Arguments • If your program needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "34", to a number. Here's a code snippet that converts a command-line argument to an integer, int firstArg = 0; if (args.length > 0){ firstArg = Integer.parseInt(args[0]); } The parseInt() method is used to get the primitive data type of a certain String. parseInt(String s): This returns an integer (decimal only). For example consider the following example. The string 9 is converted to int 9. public class Test{ public static void main(String args[]){ int x =Integer.parseInt("9"); } } All of the Number classes — Integer, Float, Double, and so on — have parseXXX methods that convert a String representing a number to an object of their type. Command-line Arguments Coding Guidelines: • Before using command-line arguments, always check the number of arguments before accessing the array elements so that there will be no exception generated. • For example, if your program needs the user to input 5 arguments,
  • 4. Page 4 of 9 Another example class StringCLA{ public static void main(String args[]){ int length=str.length; if (length<=0){ System.out.println("Enter Some String."); } for(int i=0;i<length;i++){ System.out.println(str[i]); } } } c:> javac StringCLA.java c:>java StringCLA Its Work !!! Its Work !!! Note: The application displays each word- Its, Work, and !!!-- on a line by itself. This is because the space character separates command-line arguments. To have Its, Work, and !!! interpreted as a single argument, the user would join them by enclosing them within quotation marks. c:>java StringCLA "Its Work !!!" Its Work !!! Reading data from keyboard by InputStreamReader and BufferedReader class: InputStreamReader class can be used to read data from keyboard. It performs two tasks:  connects to input stream of keyboard  converts the byte-oriented stream into character-oriented stream BufferedReader class: BufferedReader class can be used to read data line by line by readLine() method.
  • 5. Page 5 of 9 Example of reading data from keyboard by InputStreamReader and BufferdReader class: In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by line data from the keyboard. //Program of reading data import java.io.*; class G5{ public static void main(String args[])throws Exception{ InputStreamReader r=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(r); System.out.println("Enter ur name"); String name=br.readLine(); System.out.println("Welcome "+name); } } Output: Enter ur name Amit Welcome Amit Another Example of reading data from keyboard by InputStreamReader and BufferdReader class until the user writes stop In this example, we are reading and printing the data until the user prints stop. import java.io.*; class G5{ public static void main(String args[])throws Exception{ InputStreamReader r=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(r); String name=""; while(name.equals("stop")){ System.out.println("Enter data: "); name=br.readLine(); System.out.println("data is: "+name); } br.close(); // BufferedReader Stream is Closed r.close(); // InputStreamReader Stream is Closed } } Output: Enter data: Amit data is: Amit Enter data: 10
  • 6. Page 6 of 9 data is: 10 Enter data: stop data is: stop The following figure shows how the stream flows from device buffer to System.in, InputStreamReader object r and then to BufferedReader object r, and at last to the java program. Class InputStreamReader public class InputStreamReader extends Reader An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted. Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation. For top efficiency, consider wrapping an InputStreamReader within a BufferedReader. For example: BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Class BufferedReader public class BufferedReader extends Reader Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
  • 7. Page 7 of 9 In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example, BufferedReader in = new BufferedReader(new FileReader("foo.in")); will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader. Input from the keyboard by java.util.Scanner class: There are various ways to read input from the keyboad, the java.util.Scanner class is one of them. The Scanner class breaks the input into tokens using a delimiter which is whitespace bydefault. It provides many methods to read and parse various primitive values. Commonly used methods of Scanner class: There is a list of commonly used Scanner class methods:  public String next(): it returns the next token from the scanner.  public String nextLine(): it moves the scanner position to the next line and returns the value as a string.  public byte nextByte(): it scans the next token as a byte.  public short nextShort(): it scans the next token as a short value.  public int nextInt(): it scans the next token as an int value.  public long nextLong(): it scans the next token as a long value.  public float nextFloat(): it scans the next token as a float value.  public double nextDouble(): it scans the next token as a double value. Example of java.util.Scanner class: import java.util.Scanner; class ScannerTest{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); System.out.println("Enter your rollno"); int rollno=sc.nextInt(); System.out.println("Enter your name"); String name=sc.next(); System.out.println("Enter your fee"); double fee=sc.nextDouble(); System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee); } }
  • 8. Page 8 of 9 Output: Enter your rollno 111 Enter your name Ratan Enter 450000 Rollno:111 name:Ratan fee:450000 Class Scanner public final class Scanner extends Object A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. For example, this code allows a user to read a number from System.in: Scanner sc = new Scanner(System.in); int i = sc.nextInt(); As another example, this code allows long types to be assigned from entries in a file myNumbers: Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); } The scanner can also use delimiters other than whitespace. This example reads several items in from a string: String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("s*fishs*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close(); prints the following output: 1 2 red blue The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace. A scanning operation may block waiting for input.
  • 9. Page 9 of 9 The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block. Another example showing the use of hasNext(), next() and nextLine(): Source Code Output of the Program import java.util.Scanner; class hasNextExample { public static void main(String agrs[]) { String stest=new String("This is an example!!!"); Scanner sc=new Scanner(stest); while(sc.hasNext()) { System.out.println(sc.next()); } } } D:java1>javac hasNextExample.java D:java1>java hasNextExample This is an example!!! D:java1> import java.util.Scanner; class hasNextExample { public static void main(String agrs[]) { String stest=new String("This is an example!!!"); Scanner sc=new Scanner(stest); while(sc.hasNext()) { System.out.println(sc.nextLine()); } } } D:java1>javac hasNextExample.java D:java1>java hasNextExample This is an example!!! D:java1>