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 CommandLine Arguments? How touse them? KeyboardinputusingBufferedReader&Scanner
classes
CommandLine 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 keyboardby InputStreamReader andBufferedReader 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 variouswaystoread inputfromthe keyboad,the java.util.Scannerclassisone of them.The Scannerclass
breaksthe inputintotokensusingadelimiterwhichiswhitespace bydefault.Itprovidesmanymethodstoreadand
parse variousprimitive 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 Outputof the Program
import java.util.Scanner;
class hasNextExample
{
publicstatic voidmain(Stringagrs[]) {
String stest=newString("Thisisan example!!!");
Scanner sc=new Scanner(stest);
while(sc.hasNext()) {
System.out.println(sc.next());
}
}
}
D:java1>javachasNextExample.java
D:java1>javahasNextExample
This
is
an
example!!!
D:java1>
import java.util.Scanner;
class hasNextExample
{
publicstatic voidmain(Stringagrs[]) {
String stest=newString("Thisisan example!!!");
Scanner sc=new Scanner(stest);
while(sc.hasNext()) {
System.out.println(sc.nextLine());
}
}
}
D:java1>javachasNextExample.java
D:java1>javahasNextExample
Thisis an example!!!
D:java1>

More Related Content

What's hot

java programming - applets
java programming - appletsjava programming - applets
java programming - applets
HarshithaAllu
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
MOHIT DADU
 
Comp 122 lab 7 lab report and source code
Comp 122 lab 7 lab report and source codeComp 122 lab 7 lab report and source code
Comp 122 lab 7 lab report and source code
pradesigali1
 
Java platform
Java platformJava platform
Java platform
Visithan
 
Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++
Richard Thomson
 
Java 8
Java 8Java 8
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
Asfand Hassan
 
Primitive data types
Primitive data typesPrimitive data types
Primitive data types
bad_zurbic
 
Serial comm matlab
Serial comm matlabSerial comm matlab
Serial comm matlab
Anwar Hassan Ibrahim, PhD
 
Java stream
Java streamJava stream
Java stream
Arati Gadgil
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
nirajmandaliya
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Siteimprove TechTalk: Demystifying Accessible Names
Siteimprove TechTalk: Demystifying Accessible NamesSiteimprove TechTalk: Demystifying Accessible Names
Siteimprove TechTalk: Demystifying Accessible Names
Tobias Christian Jensen
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
M Hussnain Ali
 
Unit 1
Unit  1Unit  1
Unit 1
donny101
 
Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
Aashish Jain
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
Riccardo Cardin
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
Tien Nguyen
 

What's hot (20)

java programming - applets
java programming - appletsjava programming - applets
java programming - applets
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
Comp 122 lab 7 lab report and source code
Comp 122 lab 7 lab report and source codeComp 122 lab 7 lab report and source code
Comp 122 lab 7 lab report and source code
 
Java platform
Java platformJava platform
Java platform
 
Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++
 
Java 8
Java 8Java 8
Java 8
 
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
 
Primitive data types
Primitive data typesPrimitive data types
Primitive data types
 
Serial comm matlab
Serial comm matlabSerial comm matlab
Serial comm matlab
 
Java stream
Java streamJava stream
Java stream
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Siteimprove TechTalk: Demystifying Accessible Names
Siteimprove TechTalk: Demystifying Accessible NamesSiteimprove TechTalk: Demystifying Accessible Names
Siteimprove TechTalk: Demystifying Accessible Names
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
Unit 1
Unit  1Unit  1
Unit 1
 
Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 

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

Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
ssuser9d7049
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
GayathriRHICETCSESTA
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
Bharat17485
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
SakkaravarthiS1
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
RathanMB
 
Class IX Input in Java using Scanner Class (1).pptx
Class IX  Input in Java using Scanner Class (1).pptxClass IX  Input in Java using Scanner Class (1).pptx
Class IX Input in Java using Scanner Class (1).pptx
rinkugupta37
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
NaorinHalim
 
An Overview Of Java | Object Oriented Programming
An Overview Of Java | Object Oriented ProgrammingAn Overview Of Java | Object Oriented Programming
An Overview Of Java | Object Oriented Programming
ArghyaGayen1
 
JAVA_BASICS.ppt
JAVA_BASICS.pptJAVA_BASICS.ppt
JAVA_BASICS.ppt
VGaneshKarthikeyan
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
Kuntal Bhowmick
 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginners
Abishek Purushothaman
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
WebStackAcademy
 
Annotations
AnnotationsAnnotations
Annotations
Knoldus Inc.
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
Muhammad Alhalaby
 
Chap03
Chap03Chap03
Chap03
Terry Yoast
 
Chap03
Chap03Chap03
Chap03
Terry Yoast
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Java files and io streams
Java files and io streamsJava files and io streams
Java files and io streams
RubaNagarajan
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
Jyoti Verma
 

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

Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
 
Class IX Input in Java using Scanner Class (1).pptx
Class IX  Input in Java using Scanner Class (1).pptxClass IX  Input in Java using Scanner Class (1).pptx
Class IX Input in Java using Scanner Class (1).pptx
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
 
An Overview Of Java | Object Oriented Programming
An Overview Of Java | Object Oriented ProgrammingAn Overview Of Java | Object Oriented Programming
An Overview Of Java | Object Oriented Programming
 
JAVA_BASICS.ppt
JAVA_BASICS.pptJAVA_BASICS.ppt
JAVA_BASICS.ppt
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginners
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
 
Annotations
AnnotationsAnnotations
Annotations
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Chap03
Chap03Chap03
Chap03
 
Chap03
Chap03Chap03
Chap03
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Java files and io streams
Java files and io streamsJava files and io streams
Java files and io streams
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
 

More from Kuntal Bhowmick

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

More from Kuntal Bhowmick (20)

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

Recently uploaded

Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
PriyankaKilaniya
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
Digital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptxDigital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptx
aryanpankaj78
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
nedcocy
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
mahaffeycheryld
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
morris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdfmorris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdf
ycwu0509
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
Atif Razi
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
ecqow
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
Gas agency management system project report.pdf
Gas agency management system project report.pdfGas agency management system project report.pdf
Gas agency management system project report.pdf
Kamal Acharya
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
harshapolam10
 
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
MadhavJungKarki
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
upoux
 
Generative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdfGenerative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdf
mahaffeycheryld
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
bijceesjournal
 

Recently uploaded (20)

Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
Digital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptxDigital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptx
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
 
morris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdfmorris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdf
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
Gas agency management system project report.pdf
Gas agency management system project report.pdfGas agency management system project report.pdf
Gas agency management system project report.pdf
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
 
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
 
Generative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdfGenerative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdf
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
 

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 CommandLine Arguments? How touse them? KeyboardinputusingBufferedReader&Scanner classes CommandLine 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 keyboardby InputStreamReader andBufferedReader 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 variouswaystoread inputfromthe keyboad,the java.util.Scannerclassisone of them.The Scannerclass breaksthe inputintotokensusingadelimiterwhichiswhitespace bydefault.Itprovidesmanymethodstoreadand parse variousprimitive 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 Outputof the Program import java.util.Scanner; class hasNextExample { publicstatic voidmain(Stringagrs[]) { String stest=newString("Thisisan example!!!"); Scanner sc=new Scanner(stest); while(sc.hasNext()) { System.out.println(sc.next()); } } } D:java1>javachasNextExample.java D:java1>javahasNextExample This is an example!!! D:java1> import java.util.Scanner; class hasNextExample { publicstatic voidmain(Stringagrs[]) { String stest=newString("Thisisan example!!!"); Scanner sc=new Scanner(stest); while(sc.hasNext()) { System.out.println(sc.nextLine()); } } } D:java1>javachasNextExample.java D:java1>javahasNextExample Thisis an example!!! D:java1>