6th Java Sushil Goel
6th Java Sushil Goel
~
Introduction
1
tS, A computer user need a bas1c. app1·1cat1on
.
to write data to the. standard output device
or any other source like file, network connection and read from the standard input or
anY other source like file, network connection. For providing read and write facilities
in the Java application, Java introduced the 1/0 Streams.
In Java, we deal with different kinds of data, e.g. bytes, primitive data types, object
etc. So Java streams support most of these types of data to read and write.
Programmer does not bothered about how they are working internally, only he/she
has to use the corresponding stream and call the methods. To read the data from
any resource input stream is used, and to write the data on any resource output
stream is used.
[ 453]
Input refers to flow of data into a program and output means the flow of d
atao
program. Input to a program may come from the keyboard, the mouse th lJto1~
, e flle
the disk or a network. Similarly, output from a program may go to the s
ere l'l'1orv,
printer, the memory, the disk or a network etc. as shown in figure 1a. 1. en, the
Sources Destinations
Keyboard Screen
Mouse Printer
Java Program
Memory or Memory
Application
FIGURE 18.1
Therefore, 1/0 is the mechanism provided by the Java language, which facilitates
the programmer to write an application to give 1/0 support to 1/0 devices as well as
files and networks.
(i) A program can get input by reading characters from a stream attached to a
data source.
h8 dtoa
(ii) A program can produce output by writing characters to a stream attac
data destination as shown in figure 18.2.
111111111
Input
Stream Output
- -- - - - - . Read Java Stream
1010101010 ~___;~ Program or Write
1010101010 Destination
Application
FIGURE 18.2
As shown in figure 1B- 2 , a java program uses an input stream to read data from a
source, one item at a time .
Similarly, a Java program can w rite information to a destination by using an output
stream, one item at time.
1. Byte Stream
It provides a convenient means for handling input and output of byte. Byte
stream supports byte (8-byte) 1/0 operations.
2. Character Stream
It provides a convenient means for handing input and output of characters.
Character stream suppo rts 16-bits Unicode character 1/0 and therefore can
be internationalized .
84 1
' • Byte Stream Classes
BYte stream is defined by using two abstract class at the top of hierarchy, they are
lnputStream and OutputStream as shown in figure 18.3.
[455)
Byte Stream
lnputStream OutputStream
FIGURE 18.3
FilelnputStream
FilterlnputStream
lnputStream
ObjectlnputStream
PipedlnputStream
FIGURE 18.4
[4561
ly used methods of lnputStream class are .•
co rn rnon
,-1ethods Description
~ b l i c abstract int read( ) throws reads the next byte of data from the
ioException{ } input stream. It returns -1 at the end of
file.
2 . public int read (byte b[ ]) throws Reads b.lengths bytes (i.e. an array of
10Exception{ } bytes) from the input stream into an
array. It returns -1 aN:he end of file.
4. public void close( ) throws Is used to close the current input stream.
IOException{ }
Fi leOutputStream
FilterOutputStre am
OutputStream t-~
PipedOutputStre am PrintStream
FIGURE 18.5
[457]
Commonly used methods of OutputStream class are :
Methods Description
2 . public void write (byte b[]) throw~ Is used to write an array of byte to the
IOException { } current output stream.
Character Stream
Reader Writer
FIGURE 18.6
These two abstract classes have several concrete classes that handle Unicode
character.
This is used to feed or enter the data to user's program by using keyboard
Keyboard is used as standard input stream and is represented as System.in.
This is used to output the data produced by the user's program by usmg
monitor. Monitor is used to standard output stream and represented as
. System.out.
This is used to output the error data produced by the user's program arid
usually a monitor is used to standard error stream and represented as
System.err.
• lnputStreamReader
• Scanner
• DatalnputStream
• Console
we use the object of buffered reader class to take inputs from the keyboard
In other ways :
481
Example:
importjava.io.*;
class lnputchar
{
public static void main(String args[]) throws Exception
{
charc;
Buffered.Reader br-new Buffered.Reader(new
InputStream.Reader(System.in));
c=(char)br.readO; //Reading character
System.out.println(c); // Writing character
}
}
Output:
M
M
Example
Following example illustrate the readline() function.
importjava.io. *;
class Inputline
{
public static void main(String args[])throws Exception
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
Buffered.Reader br= new Buffered.Reader(isr);
[4621
text= br.readLineO; //Reading String
System.out.println(text);
}
}
output:
RaJll
-
RaJll
ScannerClass
18•6'2
The scanner c Iass 1s
· a c Iass .1n Java.u
. t"II package, which
. allows the user to rea d
values of various types. To use the Scanner class, we need to reference it in our
code. This is done with the keyword import as follows :
import java.util.Scanner;
Accepting keyboard input in Java is done using a Scanner object. There is a
System.in object in Java that can be used to get input in Java, but it is not very
functional. Instead, Java programmers usually prefer to use a Scanner object that
has been mapped to the System.in object. The System.in object (like the System.out
object) already exists and is available for use. However, you must create a Scanner
object.
Once you have created a Scanner object and "mapped" it to the System.in object
you can use the following methods to get input. Input always comes in to a Java
program as a string of characters (String type). There are methods that can be
used to convert the String to a character, an integer number, a floating-point number,
etc. Some commonly used Scanner methods are :
hasNextO //is something available to read? Returns true or false.
nextlntO //get an int
nextDoubleO //get a double
nexto //get a String ( delimited by whitespace)
nextLineO //get the rest of the line as a String
nextByteO // get a byte
nextShortQ // get a short
nextLongO // get along
nextFloatQ I I get a float
(463}
Example
import java.util.Scanner;
class Sample 1
{
//Read the string form keyboard and assigned to string variable naine
name=- s.nextO;
Output:
What is your name?
Raj
Your name is Raj
[4641
4
et the user input, we can call into action one of the many methods available to
fog scanner object. Here, we have used next()
our new
method as :
Name= s.next( );
fJ<ample
Write a Java program to find the sum of two numbers.
import java.util.Scanner,
classAddl
{
//Read numbers
a= s.nextlntO;
b = s.nextlntO;
sum=a+b;
//Wrtie Result
System.out.println("Sum = 11 + sum);
}
}
Output:
Enter two numben
10 20
Sum=30
(-465]
18·6·3 DatalnputStr eam Class
To get user input, we can also use the DatalnputStream class. This class is definect
m Java.io package.
While using DatalnputStream to take input from the user, exception handling is
required as we have done using BufferedReader class.
Example
r----- ------ ------ ------ ---
import java.io.*;
class Readlnput
example
class DataWriteDemo
{
g args□)
public static void main(Strin
{
intx;
x='A'·
'
System.out.write(x);
System.out.write(\t');
x='P' ·
'
System.out.write(x);
System.out.write('\n');
}
}
O ut pu t:
A p
Files
18.8 Reading an d Writing and write
class es an d m ethod s that allows us to read from
In Java, there are many ite to files.
som e classes that are used to read from and wr
to files. Let us discuss
Output:
Dyal Singh College
Example
. . *
importJ8V8.IO. ;
class Sample
[ 469]
18.8.4 FileReader Class
Java FileReader class is
us ed to read data from the
file .
Example
import java.io. *;
class Samplel
{
public static void main(String
args[]) throws Exception
{
FileReader fread =new FileR
eader("xyz.txt");
inti;
while( (i=fread. read( ))!= -1)
System.out.print( (char) i);
fread.clo se( );
}
}
Output :
Natraj Publications
_____......
fbe volatile Modifier
0
tS.1 ultithreaded program, sometimes, two or more thread
s share the same instance
In a.mble For eff1c1
· · ency cons,'d erat·
vana . .
ions, eac h thread can keep ·its own private copy
h a shared variable. '
of su C
or master) copy of the variable is updated at variou
The real ( s times such as when
nchronized method is entered. In some cases, all that '
really matters is that the
~:Stercopy of a variable always reflects its current state.
To ensure this, simply specify the variable as volat
ile, which tells the compiler that
. must always use the master copy of a volatile variab
le (or, atleast, always keep
,t ny private copies up-to-date with the master copy,
and vice versa). Also, accesses
~o the master variable must be executed in the precise
order in which they are
e)(ecuted on any private copy.
Volatile modifier will tell the JVM to be cautious of the
threads which runs concurrently
Essentially, volatile is used to indicate that a variab
le's value will be modified by
ditterent5~a ds.
Decla.t'ing a volatile Java variable means :
,I
(471]
'