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

What's hot

Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
nirajmandaliya
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
cs19club
 
Writing Usable APIs in Practice by Giovanni Asproni
Writing Usable APIs in Practice by Giovanni AsproniWriting Usable APIs in Practice by Giovanni Asproni
Writing Usable APIs in Practice by Giovanni Asproni
SyncConf
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
Prof. Dr. K. Adisesha
 
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
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
M Hussnain Ali
 
Chap03
Chap03Chap03
Chap03
Terry Yoast
 
Chap03
Chap03Chap03
Chap03
Terry Yoast
 
What's New In Python 2.4
What's New In Python 2.4What's New In Python 2.4
What's New In Python 2.4
Richard Jones
 
Java 8
Java 8Java 8
ppt on scanner class
ppt on scanner classppt on scanner class
ppt on scanner class
deepsxn
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
Salahaddin University-Erbil
 
What's New In Python 2.5
What's New In Python 2.5What's New In Python 2.5
What's New In Python 2.5
Richard Jones
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
ahmed abugharsa
 
Unit 1
Unit  1Unit  1
Unit 1
donny101
 
Java stream
Java streamJava stream
Java stream
Arati Gadgil
 
Python
PythonPython
Python
Aashish Jain
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
BlackRabbitCoder
 
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
Asfand Hassan
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 

What's hot (20)

Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
Writing Usable APIs in Practice by Giovanni Asproni
Writing Usable APIs in Practice by Giovanni AsproniWriting Usable APIs in Practice by Giovanni Asproni
Writing Usable APIs in Practice by Giovanni Asproni
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
Chap03
Chap03Chap03
Chap03
 
Chap03
Chap03Chap03
Chap03
 
What's New In Python 2.4
What's New In Python 2.4What's New In Python 2.4
What's New In Python 2.4
 
Java 8
Java 8Java 8
Java 8
 
ppt on scanner class
ppt on scanner classppt on scanner class
ppt on scanner class
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
 
What's New In Python 2.5
What's New In Python 2.5What's New In Python 2.5
What's New In Python 2.5
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
 
Unit 1
Unit  1Unit  1
Unit 1
 
Java stream
Java streamJava stream
Java stream
 
Python
PythonPython
Python
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
 
Java Streams
Java StreamsJava Streams
Java Streams
 

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
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
Bharat17485
 
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
 
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
 
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
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
GayathriRHICETCSESTA
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
NaorinHalim
 
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
 
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
 
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
 
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
 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginners
Abishek Purushothaman
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
Muhammad Alhalaby
 
Annotations
AnnotationsAnnotations
Annotations
Knoldus Inc.
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
Sowri Rajan
 
C language 3
C language 3C language 3
C language 3
Arafat Bin Reza
 
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
 
Getting Program Input
Getting Program Input Getting Program Input
Getting Program Input
Dr. Rosemarie Sibbaluca-Guirre
 
intro unix/linux 05
intro unix/linux 05intro unix/linux 05
intro unix/linux 05
duquoi
 

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
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
 
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
 
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
 
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
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
 
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
 
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
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
 
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
 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginners
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Annotations
AnnotationsAnnotations
Annotations
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
C language 3
C language 3C language 3
C language 3
 
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
 
Getting Program Input
Getting Program Input Getting Program Input
Getting Program Input
 
intro unix/linux 05
intro unix/linux 05intro unix/linux 05
intro unix/linux 05
 

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

ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
upoux
 
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdfAsymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
felixwold
 
Accident detection system project report.pdf
Accident detection system project report.pdfAccident detection system project report.pdf
Accident detection system project report.pdf
Kamal Acharya
 
Height and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdfHeight and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdf
q30122000
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
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
 
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUESAN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
drshikhapandey2022
 
Digital Image Processing Unit -2 Notes complete
Digital Image Processing Unit -2 Notes completeDigital Image Processing Unit -2 Notes complete
Digital Image Processing Unit -2 Notes complete
shubhamsaraswat8740
 
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls ChennaiCall Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
paraasingh12 #V08
 
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
 
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdfSELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
Pallavi Sharma
 
Butterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdfButterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdf
Lubi Valves
 
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
 
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptxSENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
b0754201
 
Assistant Engineer (Chemical) Interview Questions.pdf
Assistant Engineer (Chemical) Interview Questions.pdfAssistant Engineer (Chemical) Interview Questions.pdf
Assistant Engineer (Chemical) Interview Questions.pdf
Seetal Daas
 
Open Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surfaceOpen Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surface
Indrajeet sahu
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
upoux
 
openshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoinopenshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoin
snaprevwdev
 
This study Examines the Effectiveness of Talent Procurement through the Imple...
This study Examines the Effectiveness of Talent Procurement through the Imple...This study Examines the Effectiveness of Talent Procurement through the Imple...
This study Examines the Effectiveness of Talent Procurement through the Imple...
DharmaBanothu
 

Recently uploaded (20)

ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
 
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdfAsymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
 
Accident detection system project report.pdf
Accident detection system project report.pdfAccident detection system project report.pdf
Accident detection system project report.pdf
 
Height and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdfHeight and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdf
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
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
 
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUESAN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
 
Digital Image Processing Unit -2 Notes complete
Digital Image Processing Unit -2 Notes completeDigital Image Processing Unit -2 Notes complete
Digital Image Processing Unit -2 Notes complete
 
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls ChennaiCall Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
 
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
 
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdfSELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
 
Butterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdfButterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).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
 
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptxSENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
 
Assistant Engineer (Chemical) Interview Questions.pdf
Assistant Engineer (Chemical) Interview Questions.pdfAssistant Engineer (Chemical) Interview Questions.pdf
Assistant Engineer (Chemical) Interview Questions.pdf
 
Open Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surfaceOpen Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surface
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
 
openshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoinopenshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoin
 
This study Examines the Effectiveness of Talent Procurement through the Imple...
This study Examines the Effectiveness of Talent Procurement through the Imple...This study Examines the Effectiveness of Talent Procurement through the Imple...
This study Examines the Effectiveness of Talent Procurement through the Imple...
 

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>