SlideShare une entreprise Scribd logo
1  sur  191
UNIT 3
Exceptions, I/O and Threads Input and Output in
Java:
Muhammed Mashahil
Introduction
File : A file is collection of related records placed in a particular area on disk.
Record : A record is composed of several fields.
Fields : A field is group of characters
Character : A Character in java is sequence of Unicode characters.
file processing:
-Storing and manipulating data using files is known as file processing.
-Reading/Writing of data in a file can beperformed at the level of bytes,
characters, or fields depending on application requirements.
-Java also provides capabilities to read and write class objects directly. The
process of reading and writing objects is called object serialisation.
I/O and Data Movement
The flow of data into a program (input) may
come from different devices such as keyboard,
mouse, memory, disk, network, or another
program.
The flow of data out of a program (output) may
go to the screen, printer, memory, disk,
network, another program.
Both input and output share a certain common
property such as unidirectional movement of
data – a sequence of bytes and characters and
support to the sequential access to the data.
Data representation in java files
Marks field
Roll no. field
Name field
❏ Java.io.File class represents the files and directory pathnames in an
abstract manner.
❏ This class is used for creation of files and directories, file searching, file
deletion, etc.
❏ The File object represents the actual file/directory on the disk
❏ Instances of the File class are immutable; that is, once created, the
abstract pathname represented by a File object will never change.
❏ Class File provides information about The class provides
❏ Files and directories
❏ The class provides
❏ A constructor with a String argument
❏ Specifying the name of a file or directory
❏ The name can be either an absolute path or a relative path
File class
File class fields
Modifier Type Field Description
static String pathSeparator
public static final String pathSeparator
The system-dependent path-separator character, represented as a string
for convenience. This string contains a single character, namely pathSeparatorChar.
static char pathSeparatorChar
public static final char pathSeparatorChar
The system-dependent path-separator character. This field is initialized to
contain the first character of the value of the system property
path.separator. This character is used to separate filenames in a sequence
of files given as a path list. On UNIX systems, this character is ':'; on
Microsoft Windows systems it is ';'
static String separator
public static final String separator
This is the system-dependent default name-separator character,
represented as a string for convenience.
static char separatorChar
public static final char separatorChar
The system-dependent default name-separator character. This field is
initialized to contain the first character of the value of the system property
file.separator. On UNIX systems the value of this field is '/'; on Microsoft
Windows systems it is ''.
File class Constructors
Constructor Description
File(File parent, String child) It creates a new File instance from a parent abstract
pathname and a child pathname string.
File(String pathname) It creates a new File instance by converting the given
pathname string into an abstract pathname.
File(String parent, String child) It creates a new File instance from a parent pathname
string and a child pathname string.
File(URI uri) It creates a new File instance by converting the given
file: URI into an abstract pathname.
File class Constructors
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
public class FileConstructor {
public static void main(String[] args) {
File file = new File("A:ihrdjava
c5programfile.txt");//First
File parent = new File("A:ihrdjava
c5program"); //Second
File file2 = new File(parent, "data2/file2.txt");
File file3 = new File("D:/pankaj/",
"data3/file3.txt"); //Third
System.out.println("First : "+file.getAbsolutePath());
System.out.println("Second : "+file2.getAbsolutePath());
System.out.println("Third : "+file3.getAbsolutePath());
//Forth
URI uri;
try {
uri = new URI("file:A:ihrdjava
c5programdata3file3.txt");
File file4 = new File(uri);
System.out.println("Forth :
"+file4.getAbsolutePath());
} catch (URISyntaxException
e) {
e.printStackTrace();
}
}
}
First : A:ihrdjava c5programdatafile.txt
Second : A:ihrdjava c5programdata2file2.txt
Third : A:ihrdjava c5programdata3file3.txt
Forth : A:ihrdjava c5programdata4file4.txt
File class Methods
Modifier and
Type
Method Description
static File createTempFile(String
prefix, String suffix)
It creates an empty file in the default temporary-file directory,
using the given prefix and suffix to generate its name.
boolean createNewFile() It atomically creates a new, empty file named by this abstract
pathname if and only if a file with this name does not yet exist.
boolean canWrite() It tests whether the application can modify the file denoted by this
abstract pathname.String[]
boolean canExecute() It tests whether the application can execute the file denoted by this
abstract pathname.
boolean canRead() It tests whether the application can read the file denoted by this
abstract pathname.
boolean isAbsolute() It tests whether this abstract pathname is absolute.
Modifier and
Type
Method Description
boolean isDirectory()
It tests whether the file denoted by this abstract pathname is a directory.
boolean isFile()
It tests whether the file denoted by this abstract pathname is a normal file.
String getName()
It returns the name of the file or directory denoted by this abstract pathname.
String getParent()
It returns the pathname string of this abstract pathname's parent, or null if
this pathname does not name a parent directory.
Path toPath() It returns a java.nio.file.Path object constructed from the this abstract path.
URI toURI() It constructs a file: URI that represents this abstract pathname.
File class Methods
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
try {
File file = new File("A:javaFile123.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
File class Example
import java.io.*;
class A
{
public static void main(String[] args)
{
File file= new File("A:TextBook1.txt");
try
{ //calling createNewFile() method creates a new
File
System.out.println("Is the file created ? "+
file.createNewFile());
}
catch(IOException e)
{
System.out.println(e);
}
File class Example
System.out.println("Does this file exists? "+file.exists());
System.out.println("The name of file is "+file.getName());
System.out.println("Parent Directory of this file "+file.getParent());
System.out.println("Path to this file "+file.getPath());
System.out.println("The full path to this file "+file.getAbsolutePath());
System.out.println("Is this a Directory? "+file.isDirectory());
System.out.println("Is this a File? "+file.isFile());
System.out.println("Is this a hidden file "+file.isHidden());
System.out.println("Is this File readable ? "+file.canRead());
System.out.println("Is this File writable ? "+file.canWrite());
} //main method ends
} //class definition ends
Output
Is the file created ? true
Does this file exists? true
The name of file is TextBook1.txt
Parent Directory of this file A:
Path to this file A:TextBook1.txt
Is this a Directory? false
Is this a File? true
Is this a hidden file false
Is this File readable ? true
Is this File writable ? true
File size ? 0
Standard Streams
Streams
❏ Java Uses the concept of Streams to
represent the ordered sequence of
data, a common characteristic shared
by all I/O devices.
❏ Streams presents a uniform, easy to
use, object oriented interface
between the program and I/O
devices.
❏ A stream in Java is a path along
which data flows (like a river or pipe
along which water flows).
Streams
❏ The concepts of sending data from one stream to another (like a pipe
feeding into another pipe) has made streams powerful tool for file
processing.
❏ Connecting streams can also act as filters.
❏ Streams are classified into two basic types:
❏ Input Steam
❏ Output Stream
Input Stream
Output Stream
Standard Streams
❏ There are three standard streams, all of which are managed by the
java.lang.System class:
1) System.out: standard output stream
Used for program output, typically displays information to the user
2) System.in: standard input stream
Used for program input, typically reads input entered by the user.
3) System.err: standard error stream
Used to display error messages to the user.
Stream classes
❏ Input/Output related classes are defined in java.io package.
❏ Input/Output in Java is defined in terms of streams.
❏ A stream is a sequence of data, of no particular length.
❏ There are 2 kinds of streams
❏ byte streams
❏ character streams
Readers/ Writers
Input streams/Output
streams
Operates on 16-bit (2
byte) unicode characters.
Operated on 8 bit (1 byte)
data.
Character streams
Byte Streams
Keyboard Input
Keyboard Input
❏ You've already seen that output can be displayed to the user using the
subroutine System.out.print. This subroutine is part of a pre-defined
object called System.out. The purpose of this object is precisely to display
output to the use
❏ There is also a corresponding object called System.in that exists to read
data input by the user, but it provides only very primitive input facilities,
and it requires some advanced Java programming skills to use it
effectively.
❏ here are many ways to read data from the keyboard in java:
❏ Using Command Line Arguments
❏ Console Class
❏ Scanner Class
❏ InputStreamReader Class
Using Command Line Arguments
❏ In java, Command Line Arguments is a one of the way to passed arguments at the
time of running the java program.
❏ The arguments can be passed from the console can be received in the java program
and it can be used as input.
❏ We have pass N numbers of arguments from the command prompt.
❏ For example, We have taken input from the console at the time of running the java
program and sum of these integer input.
public class InputUsingCMD{
public static void main(String[] args){
int sum=0;
for(int i=0;i<args.length;i++){
sum+=Integer.parseInt(args[i]);}
System.out.println("The sum of the arguments is
"+sum);}}
Console Class
String text=System.console().readLine();
System.out.println("Text is: "+text);
❏ Console class is be used to get input from console.
❏ It provides methods to read texts and passwords.
❏ If you read password using Console class, it will not be displayed to the user.
❏ The java.io.Console class is attached with system console internally.
❏ The Console class is introduced since 1.5.
Console Class
Method Description
Reader reader()
It is used to retrieve the reader object associated with the console
String readLine()
It is used to read a single line of text from the console.
String readLine(String fmt, Object... args) It provides a formatted prompt then reads the single line of text from the
console.
char[] readPassword()
It is used to read password that is not being displayed on the console.
char[] readPassword(String fmt, Object... args) It provides a formatted prompt then reads the password that is not being
displayed on the console.
Console format(String fmt, Object... args)
It is used to write a formatted string to the console output stream.
Console printf(String format, Object... args)
It is used to write a string to the console output stream.
PrintWriter writer()
It is used to retrieve the PrintWriter object associated with the console.
void flush()
It is used to flushes the console.
Console Class:
public class Sample
{
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();
System.out.println(name);
} }
Scanner Class
❏ The java.util.Scanner class breaks the input into tokens using delimiter (i.e.
Whitespace (By Default)). Its provide various methods to read and parse the various
primitive values.
❏ Scanner class is used to parse text for string and primitive types using regular
expressions.
❏ For example, we have taken a string. Java Scanner class which reads the int, string
value as an input from that string
Scanner Creation
Syntax
Scanner keyboard = new Scanner(System.in);
Eg:-
Scanner s = new Scanner(System.in);
String mj = s.nextLine();
❏ Scanner is a class which must be instantiated before it can be used. In other words,
you must make a new Scanner if you want to use Scanner.
❏ A reference must be used to store the location in memory of the Scanner object
created.
❏ System.in is the parameter passed to the Scanner constructor so that Java will know
to connect the new Scanner to the keyboard.
❏ keyboard is a reference that will store the location of newly created Scanner object
Object instantiation
Reference variable
Scanner Imports
❏ In order to use Scanner, you must import java.util.Scanner.
import java.util.Scanner;
Scanner Methods
Reading in Integers
❏ The nextInt() method is used to tell a Scanner object to retrieve the next integer
value entered.
❏ In the example, the next integer typed in on the keyboard would be read in and
placed in the integer variable num.
❏ nextInt() will read up to the first whitespace value entered.
Scanner keyboard = new Scanner(System.in);
System.out.print(“ Enter the number”);
int num = keyboard.nextInt();
❏ The nextInt() method will read in the next integer. If a non-integer value is
encountered such as a decimal value, the result will be run-time exception.
❏ keyboard is a reference that refers to a Scanner object
Strings
❏ The nextLine() method will read in the next text value entered. A numeric or non-
numeric text value will be accepted.
❏ In the example, the next text entered on the keyboard would be read in and placed
in variable word.
❏ The nextLine() method would read up to the first whitespace encountered.
Whitespace would be any space, any tab, or any enter key.
Java Stream Classes
Byte Stream Classes
❏ Byte Stream Classes are used to read bytes from an input stream and write bytes to
an output stream.
❏ Byte streams create binary files.
❏ A binary file essentially contains the memory image of the data. That is, it stores
bits as they are in memory.
❏ Binary files are faster to read and write because no translation need take place.
❏ Binary files, however, cannot be read with a text editor.
❏ Byte Stream Classes are in divided in two groups -
❏ InputStream Classes - These classes are subclasses of an abstract class,
InputStream and they are used to read bytes from a source(file, memory or
console).
❏ OutputStream Classes - These classes are subclasses of an abstract class,
OutputStream and they are used to write bytes to a destination(file, memory
or console).
Byte Stream Classes
InputStream
❏ InputStream class is a base class of all the classes that are used to read bytes
from a file, memory or console.
❏ InputStream is an abstract class and hence we can't create its object but we
can use its subclasses for reading bytes from the input stream.
❏ All of the methods in this class will throw an IOException on error conditions
❏ It is also an implementation of an interface named closable
❏ In this interface we have a special method called close()
Hierarchy of InputStream classes
Object
InputStream Classes
Stream class Description
BufferedInputStream Used for Buffered Input Stream.
DataInputStream Contains method for reading java standard datatype
FileInputStream Input stream that reads from a file
ObjectInputStream Input stream for objects
SequenceInputStream Input stream that is a combination of two or more input streams that will be
read sequentially,ie. one after another
StringBufferInputStream This class allows an application to create an input stream in which the bytes read
are supplied by the contents of a string. Only the low eight bits of each character
in the string are used by this class.
ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the
stream. An internal counter keeps track of the next byte to be supplied by the
read method.
PipedInputStream Input pipe
FilterInputStream Implements InputStream
InputStream Abstract class that describe stream input.
InputStream Class methods
FileInputStream
❏ FileInputStream class is a subclass of InputStream abstract class.
❏ FileInputStream is used to create an input stream,
❏ which is used to read byte/bytes from a file.
Constructors of FileInputStream :
FileInputStream(File file)
This constructor creates a FileInputStream object to read a file specified by the File
object, which is passed to this constructor as a parameter.
Example -
File file= new File("D:Textbook.txt");
FileInputStream fis= new FileInputStream(file);
FileInputStream(String path)
This constructor creates a FileInputStream to read a file which is accessed by the path
mentioned in the parameters of this constructor.
Example -
FileInputStream fis= new FileInputStream("D:TextBook.txt");
Both the examples of constructors have created a FileInputStream object to create an input
stream to read a file called TextBook.txt which is located in the D: drive
Example :
import java.io.*;
class Demo
{
public static void main(String[] args) throws IOException
{
File f = new File("A:IHRDjava c5program2One.txt"); //given the path for file f.
InputStream is = new FileInputStream(f); // created an FileInputStream object and passed file f as parameter
if(f.exists()) //checking whether file f exists or not.
{
System.out.println("File exists.");
int i = 0; // created a variable i to store the byte data from file f.
// read method always returns an integer of range 0 to 255
while((i = is.read()) != -1) // assigning the i value to the byte value obtained from file f through InputStream.
{
System.out.print((char) i); // casting int to char in order to print characters.
} }
else
System.out.println("File not found.");
is.close(); // closing the InputStream
} }
DataInputStream
❏ DataInputStream is a FilterInputStream that read primitive
❏ data from an underlying input stream in a machine-independent way. It
implements the DataInput
❏ interface and provides convenience methods such as readInt(), readChar
etc. It also inherits the methods from its immediate parent
FilterInputStream.
Methods of DataInputStream :
Method Description
int read(byte[] b) It is used to read the number of bytes from the input stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
boolean readBoolean() It is used to read one input byte and return true if byte is non zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input stream.
String readUTF() It is used to read a string that has been encoded using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and store them into the buffer array.
void readFully(byte[] b, int off, int
len)
It is used to read len bytes from the input stream.
Example Input from keyboard:
import java.io.*;
public class B{
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter text (enter & to end):");
char ch;
while ((ch = (char) dis.read()) != '&')
System.out.print(ch);
}
}
Example input from file:
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}
OutputStream
❏ Java application uses an output stream to write data to a destination;
❏ it may be a file, an array, peripheral device or socket.
❏ OutputStream class is an abstract class.
❏ It is the superclass of all classes representing an output stream of bytes.
❏ An output stream accepts output bytes and sends them to some sink.
Hierarchy of OutputStream classes
Object
OutputStream Classes
Stream class Description
BufferedOutputStream Used for Buffered Output Stream.
DataOutputStream An output stream that contain method for writing java standard data type
FileOutputStream Output stream that write to a file.
PipedOutputStream Itcan be connected to a piped input stream to create a communications pipe.
The piped output stream is the sending end of the pipe. Typically, data is
written to a PipedOutputStream object by one thread and data is read from the
connected PipedInputStream by some other thread.
ByteArrayOutputStream It implements an output stream in which the data is written into a byte array.
The buffer automatically grows as data is written to it. The data can be
retrieved using toByteArray() and toString().
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method
OutputStream Class methods
❏ Methods of OutputStream class provide support for writing bytes to the
output stream. As this is an abstract class.
❏ Hence, some undefined abstract methods are defined in the subclasses of
OutputStream
Methods Description
flush() This method flushes the output steam by forcing out buffered
bytes to be written out.
write() This method writes a byte to the output stream.
write(byte b[]) This method writes a whole byte array(b) to the output.
write(byte b[],int n,int m) This method writes m bytes from array b starting from nth byte
to the output.
close() This method closes this output stream and also frees any
resources connected with this output stream.
FileOutputStream
❏ FileOutputStream is an output stream used for writing data to a file.
❏ If you have to write primitive values into a file, use FileOutputStream class.
❏ You can write byte-oriented as well as character-oriented data through
FileOutputStream class.
❏ But, for character-oriented data, it is preferred to use FileWriter than
FileOutputStream.
Constructors of FileOutputStream :
FileInputStream(File file)
This constructor creates a FileOutputStream object to write a file specified by the File object, which is
passed to this constructor as a parameter.
Example -
FileOutputStream(File file) — creates a file output stream to write to a File object.
FileOutputStream(File file, boolean append) — creates a file output stream to write to a File object; allows
appending mode.
FileOutputStream(FileDescriptor fdObj) — creates a file output stream to write to the specified file descriptor.
FileOutputStream(String name) — creates a file output stream to write to the file with the specified name.
FileOutputStream(String name, boolean append) — creates a file output stream to write to the file with the
specified name; allows appending mode
Example :
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
File f = new File("A:IHRDjava c5program2One.txt"); //given the path for file f
OutputStream os = new FileOutputStream(f); // created an FileOutputStream object and passed file f as
parameter
if(f.exists()) // checking whether file f exists or not
{
System.out.println("File exists.");
byte b[] = {'i',' ','a','m',' ','f','i','l','e',' ','o','n','e','.'}; // created a byte array.
os.write(b);// Writing into file One
}else
System.out.println("File not found.");
os.close(); // closing the OutputStream.
InputStream is = new FileInputStream(f); // Reading from file One
int i = 0;
while((i = is.read()) != -1)
{
System.out.print((char) i); }
is.close(); // closing the InputStream
} }
Output
File exists.
i am fileone
DataOutputStream
❏ Java DataOutputStream class allows an application to write primitive
Java data types to the output stream in a machine-independent way.
❏ Java application generally uses the data output stream to write data that
can later be read by a data input stream.
Constructor and Description :
❏ DataOutputStream (OutputStream out) : Creates a new data output
stream to write data to the specified underlying output stream.
Constructors of DataInputStream :
FileInputStream(File file)
This constructor creates a FileInputStream object to read a file specified by the File
object, which is passed to this constructor as a parameter.
Example -
File file= new File("D:Textbook.txt");
FileInputStream fis= new FileInputStream(file);
FileInputStream(String path)
This constructor creates a FileInputStream to read a file which is accessed by the path
mentioned in the parameters of this constructor.
Example -
FileInputStream fis= new FileInputStream("D:TextBook.txt");
Both the examples of constructors have created a FileInputStream object to create an input
stream to read a file called TextBook.txt which is located in the D: drive
Method Description
int size() It is used to return the number of bytes written to the data output stream.
void write(int b) It is used to write the specified byte to the underlying output stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeChars(String s) It is used to write string to the output stream as a sequence of characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.
void writeBytes(String s) It is used to write string to the output stream as a sequence of bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8 encoding in portable manner.
void flush() It is used to flushes the data output stream.
Example :
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
57
Byte Input Stream - example
Count total number of bytes in the file
import java.io.*;
class CountBytes {
public static void main(String[] args) throws FileNotFoundException,
IOException
{
FileInputStream in;
in = new FileInputStream("InFile.txt");
int total = 0;
while (in.read() != -1)
total++;
System.out.println(total + " bytes");
}
}
58
What happens if the file did not exist
■ JVM throws exception and terminates the program since there is no exception handler
defined.
Exception in thread "main" java.io.FileNotFoundException: InFile.txt (The system cannot
find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at CountBytes.main(CountBytes.java:7)
Character streams
❏ The superclass of character-oriented input stream I/O is java.io.Reader.The corresponding
output steam is java.io.Writer. Most byte stream classes have a corresponding character stream
class.
For an example, FileReader is the character-oriented counterpart to FileInputStream and
FileWriter is the couterpart to FileOutputStream.
❏ they were added to work specifically with character data (characters, character arrays, strings).
❏ The character stream classes differ from the byte streams classes in that they operate on
buffered input and output and properly convert each character from the encoding scheme of
the native operating system to the Unicode character set used by the Java platform.
❏ On the other hand, InputStream and OutputStream, and their subclasses operate on bytes and
arrays of bytes. The byte-oriented streams can read characters, but they only correctly handle
7-bit ASCII characters (same as the first 128 Unicode characters).
❏ the character stream classes were not added to completely replace the byte stream classes.
The InputStream and OutputStream classes remain in the I/O library and they still provide
valuable functionality (mainly for reading binary data like primitive types
Character streams
❏ Character Stream Classes are used to read characters from the source and write
characters to destination.
❏ There are two kinds of Character Stream classes - Reader classes and Writer classes.
❏ Reader Classes - These classes are subclasses of an abstract class, Reader and they are
used to read characters from a source(file, memory or console).
❏ Writer Classes - These classes are subclasses of an abstract class, Writer and they used to
write characters to a destination(file, memory or console).
Character stream classes
Reader
❏ Reader class and its subclasses are used to read characters from source.
❏ Reader class is a base class of all the classes that are used to read characters from a
file, memory or console.
❏ Reader is an abstract class and hence we can't instantiate it but we can use its
subclasses for reading characters from the input stream.
Hierarchy of Reader classes
Object
Reader classes
Stream class Description
BufferedReader Handles buffered input stream.
FileReader Input stream that reads from file.
PipedReader Piped character-input streams.
InputStreamReader Input stream that translate byte to character
CharArrayReader This class implements a character buffer that can be used as a character-
input stream.
StringReader A character stream whose source is a string
Reader Abstract class that define character stream input
Reader class methods
❏ These methods are of Reader class
Methods Description
int read() This method reads a characters from the input stream.
int read(char[] ch) This method reads a chunk of characters from the input
stream and store them in its char array, ch.
close() This method closes this output stream and also frees any
system resources connected with it.
Writer
❏ Writer class and its subclasses are used to write characters to a file, memory or
console.
❏ Writer is an abstract class and hence we can't create its object but we can use its
subclasses for writing characters to the output stream
Hierarchy of Writer classes
Object
Writer classes
Stream class Description
BufferedWriter Handles buffered output stream.
FileWriter Output stream that writes to file.
OutputStreamReader Output stream that translate character to byte.
CharArrayWriter This class implements a character buffer that can be used as an Writer.
The buffer automatically grows when data is written to the stream. The
data can be retrieved using toCharArray() and toString().
PipedWriter Piped character-output streams.
PrintWriter Output Stream that contain print() and println() method.
Writer Abstract class that define character stream output
Writer class methods
❏ Writer class provide support for writing characters to the output stream.
❏ As this is an abstract class.
❏ Hence, some undefined abstract methods are defined in the subclasses of
OutputStream.
Methods Description
abstract void flush() This method flushes the output steam by forcing out buffered bytes
to be written out.
void write(int c) This method writes a characters(contained in an int) to the output
stream.
void write(char[] arr) This method writes a whole char array(arr) to the output stream.
abstract void close() This method closes this output stream and also frees any resources
connected with this output stream.
File I/O using character streams
FileReader
❏ Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class.
❏ It is character-oriented class which is used for file handling in java.
Constructors of FileReader :
FileReader(String file) It gets filename in string. It opens the given file in
read mode. If file doesn't exist, it throws FileNotFoundException.
FileReader fr=new FileReader("D:text.txt");
FileReader(File file)It gets filename in file instance. It opens the given file in read
mode. If file doesn't exist, it throws FileNotFoundException.
Methods of FileReader :
Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of
file.
void close() It is used to close the FileReader class.
Example :
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Output
Welcome to myWorld
FileWriter
❏ FileWriter class is used to write character-oriented data to a file. It is
character-oriented class which is used for file handling in java.
❏ Unlike FileOutputStream class, you don't need to convert string into byte
array because it provides method to write string directly.
Constructors of FileWriter :
FileWriter(String file) Creates a new file. It gets file name in string.
FileWriter fw=new FileWriter("D:text.txt");
FileWriter(File file) Creates a new file. It gets file name in File object.
Methods of FileWriter :
Method Description
void write(String text) It is used to write the string into FileWriter.
void write(char c) It is used to write the char into FileWriter.
void write(char[] c) It is used to write char array into FileWriter.
void flush() It is used to flushes the data of FileWriter.
void close() It is used to close the FileWriter.
Example :
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:testout.txt");
fw.write("Welcome to myWorld.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Output
Success...
Buffered Streams
Buffered Streams
❏ Most of the examples we've seen so far use unbuffered I/O. This means each read or write
request is handled directly by the underlying OS.
❏ This can make a program much less efficient, since each such request often triggers disk access,
network activity, or some other operation that is relatively expensive.
❏ To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered
input streams read data from a memory area known as a buffer;
❏ the native input API is called only when the buffer is empty. Similarly, buffered output streams
write data to a buffer, and the native output API is called only when the buffer is full.
❏ A program can convert an unbuffered stream into a buffered stream using the wrapping idiom
we've used several times now, where the unbuffered stream object is passed to the constructor
for a buffered stream class.
❏ Here's modify the constructor invocations to use buffered I/O:
❏ inputStream = new BufferedReader(new FileReader("xyz.txt"));
❏ outputStream = new BufferedWriter(new FileWriter("charoutput.txt"));
❏ There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream
and BufferedOutputStream create buffered byte streams, while BufferedReader and
BufferedWriter create buffered character streams.
Flushing Buffered Streams
❏ It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is
known as flushing the buffer.
❏ Some buffered output classes support autoflush, specified by an optional constructor argument.
When autoflush is enabled, certain key events cause the buffer to be flushed.
❏ For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or
format. See Formatting for more on these methods.
❏ To flush a stream manually, invoke its flush method. The flush method is valid on any output
stream, but has no effect unless the stream is buffered.
BufferedInputStream
❏ A BufferedInputStream adds functionality to another input stream-namely, the ability to
buffer the input and to support the mark and reset methods.
❏ When the BufferedInputStream is created, an internal buffer array is created.
❏ As bytes from the stream are read or skipped, the internal buffer is refilled as necessary
from the contained input stream, many bytes at a time.
❏ The mark operation remembers a point in the input stream and the reset operation causes
all the bytes read since the most recent mark operation to be reread before new bytes are
taken from the contained input stream.
❏ The BufferedInputStream maintains an internal buffer of 8192 bytes.
❏ During the read operation in BufferedInputStream, a chunk of bytes is read from the disk
and stored in the internal buffer. And from the internal buffer bytes are read individually.
❏ Hence, the number of communication to the disk is reduced. This is why reading bytes is
faster using the BufferedInputStream.
BufferedInputStream Constructors and methods
Constructor Description
BufferedInputStream(InputStream in)
Creates a BufferedInputStream and saves its argument, the
input stream in, for later use
BufferedInputStream(InputStream in, int size)
Creates a BufferedInputStream with the specified buffer size,
and saves its argument, the input stream in, for later use.
Method Description
int available() It returns an estimate number of bytes that can be read from the input stream
without blocking by the next invocation method for the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream into a specified byte
array, starting with the given offset.
void close() It closes the input stream and releases any of the system resources associated
with the stream.
void reset() It repositions the stream at a position the mark method was last called on this
input stream.
void mark(int readlimit) It sees the general contract of the mark method for the input stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
boolean markSupported() It tests for the input stream to support the mark and reset methods.
Example : - BufferedInputstream
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[])throws Exception{
try{
FileInputStream fin=new FileInputStream("D:j.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output
Hello all
BufferedOutputStream
❏ Java.io.BufferedOutputStream class implements a buffered output stream.
❏ By setting up such an output stream, an application can write bytes to the underlying
output stream without necessarily causing a call to the underlying system for each byte
written.
❏ It extends the OutputStream abstract class
❏ During the write operation, the bytes are written to the internal buffer instead of the disk.
Once the buffer is filled or the stream is closed, the whole buffer is written to the disk.
❏ Hence, the number of communication to the disk is reduced. This is why writing bytes is
faster using BufferedOutputStream.
Fields
❏ protected byte[] buf: The internal buffer where data is stored.
❏ protected int count: The number of valid bytes in the buffer.
BufferedOutputStream Constructors and methods
Constructor Description
BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for writing
the data to the specified output stream.
BufferedOutputStream(OutputStream os, int size) It creates the new buffered output stream which is used for writing
the data to the specified output stream with a specified buffer size.
Method Description
void write(int b)
It writes the specified byte to the buffered output stream.
void mark(int readlimit) It write the bytes from the specified byte-input stream into a specified byte
array, starting with the given offset
void flush() It flushes the buffered output stream.
Example : - BufferedOutputstream
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:j.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Hello all";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Output
Success
j.txt
Hello all
Here writing the textual information in the BufferedOutputStream object which is connected
to the FileOutputStream object. The flush() flushes the data of one stream and send it into
another. It is required if you have connected the one stream with another.
BufferedReader
❏ BufferedReader is a Java class that reads text from the input stream. It buffers the
characters so that it can get the efficient reading of characters, arrays, etc.
❏ It inherits the reader class and makes the code efficient since we can read the data
line-by-line with the readline() method.
❏ There are a few points we have to keep in mind while working with BufferedReader
class in Java.
❏ We may have to specify the buffer size even though the default is large
enough for any purpose.
❏ With each request made of a reader a corresponding, a read request is also
made of an underlying character.
❏ It is always advised to wrap a BufferedReader class around any reader such as
InputStreamReaders.
❏ For the programs that use DataInputaStreams for textual input, an appropriate
BufferedReader replaces the DataInputStream to localize it
BufferedReader
Constructor Description
BufferedReader(Reader reader) This constructor creates a buffering character-input stream that works
on a default-size input buffer.
BufferedReader(Reader reader, int size) It uses the specified size for the input buffer for buffering the character-
input stream.
Method Description
int read() Reads a single character
String readLine() It reads a line of text
void reset() Repositions the stream to the position where the mark method was last called
int read(char[] cb, int off , int len) Reads the characters in a portion of an array
boolean markSupported() It tests the input stream support for reset and mark method
boolean ready() It checks whether the input stream is ready for reading
long skip(long n) skips the characters
void close() It closes the input stream
void mark(int readAheadLimit) Used to mark the current position in the stream
File input using BufferedReader
❏ BufferedReader is a Java class to reads the text from an Input stream (like a file) by buffering
characters that seamlessly reads characters, arrays or lines. 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 java FileReaders and InputStreamReaders.
❏ A typical usage would involve passing the file path to the BufferedReader as follows:
objReader = new BufferedReader(new FileReader("D:DukesDiary.txt"));//Assuming you have a text file in D:
This basically loads your file in the objReader.Now, you will need to iterate through the contents of the
file and print it
The while loop in the below code will read the file until it has reached the end of file
while ((strCurrentLine = objReader.readLine()) != null) {
System.out.println(strCurrentLine);}
Example: File input using BufferedReader
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:textout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
BufferedWriter
❏ Java BufferedWriter class is used to provide buffering for Writer instances. It makes
the performance fast.
❏ It inherits Writer class. The buffering characters are used for providing the efficient
writing of single arrays, characters, and strings.
BufferedWriter
Constructor Description
BufferedWriter(Writer wrt) It is used to create a buffered character output stream that uses the default size for an output
buffer.
BufferedWriter(Writer wrt, int size) It is used to create a buffered character output stream that uses the specified size for an
output buffer.
Method Description
oid newLine() It is used to add a new line by writing a line separator.
void write(int c) It is used to write a single character.
void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.
void write(String s, int off, int len) It is used to write a portion of a string.
void flush() It is used to flushes the input stream.
void close() It is used to closes the input stream
File I/O using BufferedWriter
❏ BufferedWriter is a sub class of java.io.Writer class.
❏ BufferedWriter writes text to character output stream, buffering characters so as to provide
for the efficient writing of single characters, arrays, and strings.
❏ The buffer size may be specified, or the default size may be used. The default is large enough
for most purposes.
❏ BufferedWriter is used to make lower-level classes like FileWriter more efficient and easier to
use. Compared to FileWriters, BufferedWriters write relatively large chunks of data to a file at
once, minimizing the number of times that slow, file-writing operations are performed.
❏ The BufferedWriter class also provides a newLine() method to create platform-specific line
separators automatically.
❏ In general, a Writer sends its output immediately to the underlying character or byte stream.
Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer
whose write() operations may be costly, such as FileWriters and OutputStreamWriters
BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt")));
Example: File IO using BufferedWriter
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:j.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Hello World");
buffer.close();
System.out.println("Success");
}
}
Output
Success
j.txt
Hello all
Keyboard input using BufferedReader
❏ To use InputStreamReader
❏ InputStreamReader a = new InputStreamReader(System.in);
❏ An InputStreamReader is a bridge from byte streams to character streams: It
reads bytes and decodes them into characters using a specified charset
❏ InputStreamReader has methods for reading one char at a time
❏ We don’t want to read one char at a time from user!
Example
❏ In this example, we are connecting the BufferedReader stream with the
InputStreamReader stream for reading the line by line data from the keyboard.
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output
Enter your name
Mahesh k
Welcome Mahesh k
Example
In this example, we are reading and printing the data until the user types stop.
import java.io.*;
public class BufferedReaderExample{
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();
r.close();
}
}
Output
Enter Data
Mahesh k
Data is Mahesh k
Enter Data
stop
Data is stop
Thread
Process
❏ A process has a self-contained execution environment.
❏ A process generally has a complete, private set of basic run-time
resources; in particular, each process has its own memory space.
❏ Most implementations of the Java virtual machine run as a single process.
Threads
❏ Threads are sometimes called lightweight processes.
❏ Both processes and threads provide an execution environment, but
creating a new thread requires fewer resources than creating a new
process.
❏ Threads exist within a process — every process (application) has at least
one thread.
❏ Threads share the process's resources, including memory and open files.
❏ Each thread is associated with an instance of the class java.lang.Thread.
Threads and Processes
Advantages
❏ easier to program
❏ 1 thread per task
❏ can provide better performance
❏ thread only runs when needed
❏ no polling to decide what to do
❏ multiple threads can share resources
❏ utilize multiple processors if available
Disadvantage
❏ multiple threads can lead to deadlock
❏ much more on this later
❏ overhead of switching between
threads
Difference between Process and Threads
❏ Process can be divided into
multiple threads
❏ Each process has its own
memory space
❏ It is difficult to create a process
❏ Threads cannot be sub divided.
❏ Threads of the same process
share a common memory space
❏ It is easy to create a thread.
Multitasking
❏ Multitasking is a method where multiple tasks are performed during
the same period of time
❏ They are executed concurrently instead of sequentially
❏ The tasks share common processing resources, such as a CPU and
main memory
Difference between multitasking and multithreading
❏ An ability to run several
programs simultaneously
potentially by using several
processors or by time sharing
the resources available.
❏ An ability to run serveral
processes of a single program
simultaneously potentially using
several processors or by time
sharing the resources available.
.
public class HelloX {
String name = null; // Keeps Thread Name
public HelloX(String threadName) {// Constructor
name = threadName;
}
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println(i + " Hello Thread " + name); }
} }
public static void main(String[] args) {
HelloX t1 = new HelloX(“Raina");
HelloX t2 = new HelloX(“Virat");
t1.run();
t2.run();
}
Output
0 Hello Raina
1 Hello Raina
2 Hello Raina
…..
…..
48 Hello Raina
49 Hello Raina
0 Hello Virat
1 Hello Virat
2 Hello Virat
…
…..
48 Hello Virat
49 Hello Virat
.
public class HelloX extends Thread {
private String name = null;
public HelloX(String threadName) {
name = threadName;
}
public void run() {
for (int i = 0;i < 10;i++) {
System.out.println(i + " Hello Thread " + name);
} }
public static void main(String[] args) {
HelloX t1 = new HelloX("Raina");
HelloX t2 = new HelloX("Virat");
t1.start();
t2.start();
for (int i = 0; i < 10; i++) {
System.out.println(i+" Hello Thread Main");
} }
}
Output
0 Hello Thread Raina
1 Hello Thread Raina
2 Hello Thread Raina
0 Hello Thread Virat
1 Hello Thread Virat
1 Hello Thread main
2 Hello Thread main
3 Hello Thread main
3 Hello Thread Raina
4 Hello Thread Raina
2 Hello Thread Virat
3 Hello Thread Virat
4 Hello Thread main
…
…..
48 Hello Thread Raina
49 Hello Thread Raina
48 Hello Thread Virat
Life cycle of Thread
Life cycle of Thread
❏ NEW- A thread that is just instantiated is in new state. When a start() method is
invoked, the thread moves to the ready state from which it is automatically moved
to runnable state by the thread scheduler.
❏ RUNNABLE (ready running)-A thread executing in the JVM is in running state.
❏ BLOCKED - A thread that is blocked waiting for a monitor lock is in this state. This
can also occur when a thread performs an I/O operation and moves to next
(runnable) state.
❏ WAITING - A thread that is waiting indefinitely for another thread to perform a
particular action is in this state.
❏ TIMED_WAITING - A thread that is waiting for another thread to perform an
action for up to a specified waiting time is in this state.
❏ TERMINATED - A thread that has exited is in this state.
Thread Creation
❏ Threads can be created using two ways
❏ By implementing the Runnable class
❏ By extending the Thread class
❏ start() method is used to start the thread
❏ run() method is executed after calling the start()
❏ run() can contain the code you wish to perform using thread.
Thread class
❏ Java provides Thread class to achieve thread programming.
❏ Thread class provides constructors and methods to create and perform
operations on a thread.
❏ Thread class extends Object class and implements Runnable interface.
Constructors of Thread class:
➔ Thread()
➔ Thread(String name)
➔ Thread(Runnable r)
➔ Thread(Runnable r,String name)
Thread class Methods
S.N. Modifier and Type Method Description
1) void start() It is used to start the execution of the thread.
2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread object.
5) void join() It waits for a thread to die.
6) int getPriority() It returns the priority of the thread.
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
12) static void yield() It causes the currently executing thread object to pause and allow
other threads to execute temporarily.
13) void suspend() It is used to suspend the thread.
14) void resume() It is used to resume the suspended thread.
15) void stop() It is used to stop the thread.
S.N. Modifier and
Type
Method Description
16) void destroy() It is used to destroy the thread group and all of its subgroups.
17) boolean isDaemon() It tests if the thread is a daemon thread.
18) void setDaemon() It marks the thread as daemon or user thread.
19) void interrupt() It interrupts the thread.
20) boolean isinterrupted() It tests whether the thread has been interrupted.
21) static boolean interrupted() It tests whether the current thread has been interrupted.
22) static int activeCount() It returns the number of active threads in the current thread's thread group.
23) void checkAccess() It determines if the currently running thread has permission to modify the
thread.
24) static boolean holdLock() It returns true if and only if the current thread holds the monitor lock on the
specified object.
25) static void dumpStack() It is used to print a stack trace of the current thread to the standard error
stream.
26) StackTraceElement[
]
getStackTrace() It returns an array of stack trace elements representing the stack dump of the
thread.
27) static int enumerate() It is used to copy every active thread's thread group and its subgroup into the
specified array.
28) Thread.State getState() It is used to return the state of the thread.
29) ThreadGroup getThreadGroup() It is used to return the thread group to which this thread belongs
30) String toString() It is used to return a string representation of this thread, including the
thread's name, priority, and thread group.
S.N. Modifier and Type Method Description
31) void notify() It is used to give the notification for only
one thread which is waiting for a
particular object.
32) void notifyAll() It is used to give the notification to all
waiting threads of a particular object.
33) void setContextClassLoader() It sets the context ClassLoader for the
Thread.
34) ClassLoader getContextClassLoader() It returns the context ClassLoader for the
thread.
35) static
Thread.UncaughtExceptionHandler
getDefaultUncaughtExceptionHandler() It returns the default handler invoked
when a thread abruptly terminates due to
an uncaught exception.
36) static void setDefaultUncaughtExceptionHandler() It sets the default handler invoked when
a thread abruptly terminates due to an
uncaught exception.
Runnable interface:
❏ The Runnable interface should be implemented by any class whose instances
are intended to be executed by a thread. Runnable interface have only one
method named run().
public void run(): is used to perform action for a thread.
Starting a thread:
❏ start() method of Thread class is used to start a newly created thread. It
performs following tasks:
❏ A new thread starts(with new callstack).
❏ The thread moves from New state to the Runnable state.
❏ When the thread gets a chance to execute, its target run() method will run.
Creating Threads (extending the Thread class)
❏ extending the Thread class
❏ must implement the run() method
❏ thread ends when run() method finishes
❏ call .start() to get the thread ready to run
Creating Threads Example 1
class Output extends Thread {
private String toSay;
public Output(String st) {
toSay = st;
}
public void run() {
try {
for(;;) {
System.out.println(toSay);
sleep(1000);
}
} catch(InterruptedException e) {
System.out.println(e);
}
}
}
contn
class Program {
public static void main(String [] args) {
Output thr1 = new Output(“Hello”);
Output thr2 = new Output(“There”);
thr1.start();
thr2.start();
}
}
❏ main thread is just another thread (happens to start first)
❏ main thread can end before the others do
❏ any thread can spawn more threads
Java Thread Example by extending Thread classable interface:
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output
thread is running...
Creating Threads (implementing Runnable)
❏ implementing Runnable interface
❏ virtually identical to extending Thread class
❏ must still define the run()method
❏ setting up the threads is slightly different
Creating Threads Example
class Output implements Runnable {
private String toSay;
public Output(String st) {
toSay = st;
}
public void run() {
try {
for(;;) {
System.out.println(toSay);
Thread.sleep(1000);
}
} catch(InterruptedException e) {
System.out.println(e);
}
}}
contn.
class Program {
public static void main(String [] args) {
Output out1 = new Output(“Hello”);
Output out2 = new Output(“There”);
Thread thr1 = new Thread(out1);
Thread thr2 = new Thread(out2);
thr1.start();
thr2.start();
}
}
❏ main is a bit more complex
❏ everything else identical for the most part
Advantage of Using Runnable
❏ remember - can only extend one class
❏ implementing runnable allows class to extend something else
Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output
thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread object.So you
need to explicitely create Thread class object.We are passing the object of your class that implements
Runnable so that your class run() method may execute.
Java Thread Example by implementing Runnable interface
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
Output
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Java Thread Example 1
class Job implements Runnable {
private static Thread [] jobs = new Thread[4];
private int threadID;
public Job(int ID) {
threadID = ID;
}
public void run() { do something }
public static void main(String [] args) {
for(int i=0; i<jobs.length; i++) {
jobs[i] = new Thread(new Job(i));
jobs[i].start();
}
try {
for(int i=0; i<jobs.length; i++) {
jobs[i].join();
}
} catch(InterruptedException e) { System.out.println(e); }
}
}
Java Thread Example 2
class Schedule implements Runnable {
private static Thread [] jobs = new Thread[4];
private int threadID;
public Schedule(int ID) {
threadID = ID; }
public void run() { do something }
public static void main(String [] args) {
int nextThread = 0;
setPriority(Thread.MAX_PRIORITY);
for(int i=0; i<jobs.length; i++) {
jobs[i] = new Thread(new Job(i));
jobs[i].setPriority(Thread.MIN_PRIORITY);
jobs[i].start(); }
try {
for(;;) {
jobs[nextThread].setPriority(Thread.NORM_PRIORITY);
Thread.sleep(1000);
jobs[nextThread].setPriority(Thread.MIN_PRIORITY);
nextThread = (nextThread + 1) % jobs.length;
}
} catch(InterruptedException e) { System.out.println(e); }
}}
Extending Thread vs. Implementing Runnable Interface
❏ Choosing between these two is a matter of taste
❏ Implementing the Runnable interface
❏ May take more work since we still
❏ Declare a Thread object
❏ Call the Thread methods on this object
❏ Your class can still extend other class
❏ Extending the Thread class
❏ Easier to implement
❏ Your class can no longer extend any other class
ThreadGroup Class
❏ A thread group represents a set of threads
❏ In addition, a thread group can also include other thread groups
❏ The thread groups form a tree in which every thread group except
the initial thread group has a parent
❏ A thread is allowed to access information about its own thread group,
but not to access information about its thread group's parent thread
group or any other thread groups.
States of Java Threads
❏ 5 states
❏ new: just created but not started
❏ ready:ready
❏ runnable: created, started, and able to run
❏ blocked: created and started but unable to run because it is waiting for some event to occur
❏ Dead or Finished: thread has finished or been stopped
Thread Priority
❏ Each thread is assigned a default priority of Thread.NORM_PRIORITY
(constant of 5). You can reset the priority using setPriority(int
priority).
❏ Some constants for priorities include Thread.MIN_PRIORITY
Thread.MAX_PRIORITY Thread.NORM_PRIORITY
❏ By default, a thread has the priority level of the thread that created it.
Controlling Java Threads
❏_.start(): begins a thread running
❏wait() and notify(): for synchronization
❏more on this later
❏_.stop(): kills a specific thread (deprecated)
❏_.suspend() and resume(): deprecated
❏_.join(): wait for specific thread to finish
❏_.setPriority(): 0 to 10 (MIN_PRIORITY to MAX_PRIORITY); 5 is default
(NORM_PRIORITY)
Java Thread Scheduling
❏An operating system’s thread scheduler determines which thread runs next.
❏ Most operating systems use time slicing for threads of equal priority.
❏ Preemptive scheduling: when a thread of higher priority enters the running
state, it preempts the current thread.
❏ Starvation: Higher-priority threads can postpone (possible forever) the
execution of lower-priority threads.
❏highest priority thread runs
❏if more than one, arbitrary
❏yield(): current thread gives up processor so another of equal priority can
run
❏if none of equal priority, it runs again
❏sleep(msec): stop executing for set time
❏lower priority thread can run
Daemon thread
❏ Daemon thread is a low priority thread (in context of JVM) that runs in background to
perform tasks such as garbage collection.
Properties:
❏ They can not prevent the JVM from exiting when all the user threads finish their execution.
❏ JVM terminates itself when all user threads finish their execution
❏ If JVM finds running daemon thread, it terminates the thread and after that shutdown
itself. JVM does not care whether Daemon thread is running or not.
❏ It is an utmost low priority thread.
Methods
void setDaemon(boolean status): This method is used to mark the current thread as daemon
thread or user thread. For example if I have a user thread tU then tU.setDaemon(true) would
make it Daemon thread. On the other hand if I have a Daemon thread tD then by calling
tD.setDaemon(false) would make it user thread.
boolean isDaemon():
This method is used to check that current is daemon. It returns true if the thread is Daemon else
it returns false.
Daemon thread Example
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work"); }
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
} }
Output
daemon thread work
user thread work
user thread work
Note: If you want to make a user thread as Daemon, it must
not be started otherwise it will throw
IllegalThreadStateException
Naming Thread
❏ The Thread class provides methods to change and get the name of a thread. By default, each thread
has a name
i.e. thread-0, thread-1 and so on.
❏ By we can change the name of the thread by using setName() method. The syntax of setName() and
getName() methods are given below:
public String getName(): is used to return the name of a thread.
public void setName(String name): is used to change the name of a thread.
Eg:- class TestMultiNaming1 extends Thread{
public void run(){
System.out.println("running..."); }
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
t1.setName("javac5");
System.out.println("After changing name of t1:"+t1.getName()); } }
Output
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:javac5
running...
❏ A race condition is a special condition that may occur inside a critical section. A
critical section is a section of code that is executed by multiple threads and
where the sequence of execution for the threads makes a difference in the
result of the concurrent execution of the critical section.
❏ When the result of multiple threads executing a critical section may differ
depending on the sequence in which the threads execute, the critical section is
said to contain a race condition. The term race condition stems from the
metaphor that the threads are racing through the critical section, and that the
result of that race impacts the result of executing the critical section.
❏ This may all sound a bit complicated, so I will elaborate more on race conditions
and critical sections in the following sections.
Race Conditions and Critical Sections
❏ Running more than one thread inside the same application does not by itself cause problems. The problems
arise when multiple threads access the same resources. For instance the same memory (variables, arrays, or
objects), systems (databases, web services etc.) or files.
❏ In fact, problems only arise if one or more of the threads write to these resources. It is safe to let multiple
threads read the same resources, as long as the resources do not change.
❏ Here is a critical section Java code example that may fail if executed by multiple threads simultaneously:
public class Counter {
protected long count = 0;
public void add(long value){
this.count = this.count + value; } }
❏ Imagine if two threads, A and B, are executing the add method on the same instance of the Counter class.
There is no way to know when the operating system switches between the two threads. The code in the add()
method is not executed as a single atomic instruction by the Java virtual machine. Rather it is executed as a set
of smaller instructions, similar to this:
❏ Read this.count from memory into register.
❏ Add value to register.
❏ Write register to memory.
❏ Observe what happens with the following mixed execution of threads A and B:
Race Conditions and Critical Sections
this.count = 0;
A: Reads this.count into a register (0)
B: Reads this.count into a register (0)
B: Adds value 2 to register
B: Writes register value (2) back to memory. this.count now equals 2
A: Adds value 3 to register
A: Writes register value (3) back to memory. this.count now equals 3
❏ The two threads wanted to add the values 2 and 3 to the counter. Thus the value should have been 5 after the
two threads complete execution. However, since the execution of the two threads is interleaved, the result
ends up being different.
❏ In the execution sequence example listed above, both threads read the value 0 from memory. Then they add
their i ndividual values, 2 and 3, to the value, and write the result back to memory. Instead of 5, the value left in
this.count will be the value written by the last thread to write its value. In the above case it is thread A, but it
could as well have been thread B.
Race Conditions and Critical Sections
Race Conditions in Critical Sections
❏ The code in the add() method in the example earlier contains a critical section. When multiple threads execute
this critical section, race conditions occur.
❏ More formally, the situation where two threads compete for the same resource, where the sequence in which
the resource is accessed is significant, is called race conditions. A code section that leads to race conditions is
called a critical section.
Preventing Race Conditions
❏ To prevent race conditions from occurring you must make sure that the critical section is executed as an
atomic instruction. That means that once a single thread is executing it, no other threads can execute it until
the first thread has left the critical section.
❏ Race conditions can be avoided by proper thread synchronization in critical sections. Thread synchronization
can be achieved using a synchronized block of Java code. Thread synchronization can also be achieved using
other synchronization constructs like locks or atomic variables like java.util.concurrent.atomic.AtomicInteger.
Race Conditions and Critical Sections
Synchronization
Why use Synchronization in Java?
1. To prevent thread interference.
2. To prevent consistency problem
If there at least two threads inside a program, there might be a chance when multiple threads
attempt to get to the same resource. It can even create an unexpected outcome because of
concurrency issues.
Syntax:
synchronized(objectidentifier)
{
// Access shared variables and other shared resources;
}
For example, multiple threads attempt to write within an equivalent file. This may corrupt the data
since one of the threads can override the data or when a thread is opening the same file at the same
time, another thread might be closing the same file. There is a need to synchronize the action of
multiple threads. This can be implemented using a concept called Monitors.
❏ Each object in Java is associated with a monitor, which a thread can lock or unlock.
❏ Only one thread at a time may hold a lock on a monitor.
❏ Java programming language provides a very handy way of creating threads and
synchronizing their task by using the Synchronized blocks.
❏ It also keeps the shared resources within this particular block.
Synchronization
Synchronized blocks in Java are marked with the Synchronized keyword. This block in Java is
synchronized on some object. All blocks that are synchronized on the same object can only
have one thread executing inside them at a time. All other threads attempting to enter the
synchronized block are blocked until the thread inside the synchronized block exits the block.
Types of Synchronization
There are basically two types of synchronization available. They are:
❏ Process Synchronization: The simultaneous execution of multiple threads or
processes to reach a state such that they commit to a certain sequence of actions.
❏ Thread Synchronization: At times when more than one thread tries to access a
shared resource, you need to ensure that resource will be used by only one thread
at a time.
Let’s not get into the details of these types and try to understand what are locks in Java.
Locks in Java
As I mentioned earlier, Synchronization is built around an internal entity known as the lock or
monitor. Each and every object has a lock associated with it. So a thread that needs consistent
access to an object’s fields needs to acquire the object’s lock before accessing them, and then
release the lock when the work is done.
From Java 5, the package java.util.concurrent.locks contains many lock implementations.
This is how a lock looks like:
public class Lock
{
private boolean isLocked = false;
public synchronized void lock() throws InterruptedException
{
while(isLocked)
{
wait();
}
isLocked = true;
}
public synchronized void unlock()
{
isLocked = false;
notify();
} }
The lock() method locks the Lock instance so that all
threads calling lock() are blocked until unlock() is executed
Multi-threading without Synchronization
Here is a simple example which prints the counter value in a sequence and every time we run it, it produces
a different result based on CPU availability to a thread. Check this out!
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){
System.out.println(e);
} }
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestThread{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Multi-threading without Synchronization
5
100
10
200
15
300
20
400
25
500
Multi-threading with Synchronization
This is the same example as above but it prints the counter value in the sequence. Every time we run it, it
produces the same result.
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class Test1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Multi-threading with Synchronization
5
10
15
20
25
100
200
300
400
500
Synchronized Keyword
Java synchronized keyword marks a block or a method a critical section. A critical section is
where only one thread is executing at a time, and the thread holds the lock for the
synchronized section. This synchronized keyword helps in writing concurrent parts of any
application. It also protects shared resources within the block.
The synchronized keyword can be used with:
❏ A code block
❏ A method
Let’s discuss the code block.
Synchronized Keyword: A code block
Syntax
The general syntax for writing a synchronized block is:
synchronized ( lockObject)
{
//synchronized statements
}
Synchronized Keyword
❏ When a thread wants to execute the synchronized statements inside the block, it must
acquire the lock on the lockObject‘s monitor. Only one thread can acquire the monitor
of a lock object at a time. So all other threads must wait till the currently executing
thread acquires the lock and finish its execution.
❏ This way, the synchronized keyword guarantees that only one thread will be executing
the synchronized block statements at a time, and thus prevents multiple threads from
corrupting the shared data that is present inside the block.
Note:If a thread is put on sleep (using sleep() method) then it does not release the lock. During this sleep
time, no thread will be executing the synchronized block statements.
Java synchronization will throw NullPointerException if lock object used in ‘synchronized (lock)‘ is null.
Inter-thread communication
❏ Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
❏ Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following methods of Object class:
❏ wait()
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.The
current thread must own this object's monitor, so it must be called from the synchronized method
only otherwise it will throw exception.
❏ notify()
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this
object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of
the implementation. Syntax:
public final void notify()
❏ notifyAll()
Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll()
Understanding the process of inter-thread communication
❏ Threads enter to acquire lock.
❏ Lock is acquired by on thread.
❏ Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the
lock and exits.
❏ If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
❏ Now thread is available to acquire lock.
❏ After completion of the task, thread releases the lock and exits the monitor state of the object.
Difference between wait and sleep
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or notifyAll()
methods
after the specified amount of time, sleep is
completed.
Synchronized Keyword
Synchronized Keyword: A method
Syntax
The general syntax for writing a synchronized method is:
<access modifier> synchronized method ( parameters)
{
//synchronized code
}
Here lockObject is just a reference to an object whose lock is associated with the monitor
which represents the synchronized statements.
Similar to the synchronized block, a thread must acquire the lock on the connected monitor
object with the synchronized method. In the case of synchronized method, the lock object is:
‘.class’ object – if the given method is static.
‘this’ object – if the method is non-static. ‘this’ is the reference to the current object in
which the synchronized method is invoked.
Java synchronized keyword is re-entrant in nature. It means if a synchronized method calls
another synchronized method which requires the same lock, then current thread which is
holding the lock can enter into that method without acquiring the lock.
Difference between synchronized keyword and synchronized block
When you use synchronized keyword with a method, it acquires a lock in the object for the
entire method. This means that no other thread can use any synchronized method until the
current thread that is invoked has finished its execution.
Synchronized block acquires a lock in the object only between parentheses after the
synchronized keyword is specified. This means that no other thread can acquire a lock on the
already locked object until the block exits. But other threads will be able to access the rest of
the code that is present in the method.
This brings us to the end of this article where we have discussed how exactly Synchronization
in Java works.
Deadlock
❏ synchronized keyword is used to make the class or method thread-safe which
means only one thread can have lock of synchronized method and use it, other
threads have to wait till the lock releases and anyone of them acquire that lock.
❏ It is important to use if our program is running in multi-threaded environment
where two or more threads execute simultaneously. But sometimes it also causes a
problem which is called Deadlock. Below is a simple example of Deadlock
condition.
Java program to illustrate Deadlock in multithreading.
class Util { // Util class to sleep a thread
static void sleep(long millis) {
try{
Thread.sleep(millis); }
catch (InterruptedException e) {
e.printStackTrace(); }
} }
// This class is shared by both threads
class Shared {
// first synchronized method
synchronized void test1(Shared s2) {
System.out.println("test1-begin");
Util.sleep(1000);
// taking object lock of s2 enters
// into test2 method
s2.test2();
System.out.println("test1-end"); }
// second synchronized method
synchronized void test2() {
System.out.println("test2-begin");
Util.sleep(1000);
// taking object lock of s1 enters
// into test1 method
System.out.println("test2-end"); } }
public class Deadlock {
public static void main(String[]
args) {
// creating one object
Shared s1 = new Shared();
// creating second object
Shared s2 = new Shared();
// creating first thread and
starting it
Thread1 t1 = new Thread1(s1,
s2);
t1.start();
// creating second thread and
starting it
Thread2 t2 = new Thread2(s1,
s2);
t2.start();
// sleeping main thread
Util.sleep(2000);
}
}
class Thread1 extends Thread {
private Shared s1;
private Shared s2;
// constructor to initialize fields
public Thread1(Shared s1, Shared s2) {
this.s1 = s1;
this.s2 = s2; }
// run method to start a thread
@Override
public void run() { /* taking object lock of s1
enters into test1 method */
s1.test1(s2); } }
class Thread2 extends Thread {
private Shared s1;
private Shared s2;
// constructor to initialize fields
public Thread2(Shared s1, Shared s2){
this.s1 = s1;
this.s2 = s2; }
// run method to start a thread
@Override
public void run() { // taking object lock of s2
// enters into test2 method
s2.test1(s1); } }
Output
test1-begin
test2-begin
Java program to illustrate Deadlock in multithreading.
We can see that it runs for indefinite time, because threads are in deadlock condition and doesn’t let
code to execute. Now let’s see step by step what is happening there.
1. Thread t1 starts and calls test1 method by taking the object lock of s1.
2. Thread t2 starts and calls test2 method by taking the object lock of s2.
3. t1 prints test1-begin and t2 prints test-2 begin and both waits for 1 second, so that both
threads can be started if any of them is not.
4. t1 tries to take object lock of s2 and call method test2 but as it is already acquired by t2 so it
waits till it become free. It will not release lock of s1 until it gets lock of s2.
5. Same happens with t2. It tries to take object lock of s1 and call method test1 but it is already
acquired by t1, so it has to wait till t1 release the lock. t2 will also not release lock of s2 until it
gets lock of s1.
6. Now, both threads are in wait state, waiting for each other to release locks. Now there is a race
around condition that who will release the lock first.
7. As none of them is ready to release lock, so this is the Dead Lock condition.
8. When you will run this program, it will be look like execution is paused.
Detect Dead Lock condition
❏ We can also detect deadlock by running this program on cmd. We have to collect Thread Dump.
Command to collect depends on OS type. If we are using Windows and Java 8, command is jcmd
$PID Thread.print
❏ We can get PID by running jps command.
Avoid Dead Lock condition
❏ We can avoid dead lock condition by knowing its possibilities. It’s a very complex process and not
easy to catch. But still if we try, we can avoid this.
❏ There are some methods by which we can avoid this condition. We can’t completely remove its
possibility but we can reduce.
❏ Avoid Nested Locks : This is the main reason for dead lock. Dead Lock mainly happens when we
give locks to multiple threads. Avoid giving lock to multiple threads if we already have given to one.
Avoid Unnecessary Locks : We should have lock only those members which are required. Having
lock on unnecessarily can lead to dead lock.
Using thread join : Dead lock condition appears when one thread is waiting other to finish. If this
condition occurs we can use Thread.join with maximum time you think the execution will take.
If threads are waiting for each other to finish, then the condition is known as Deadlock.Deadlock condition
is a complex condition which occurs only in case of multiple threads.Deadlock condition can break our
code at run time and can destroy business logic.We should avoid this condition as much as we can.
Exceptions
Motivations
❏ When a program runs into a runtime error, the program
terminates abnormally.
❏ How can you handle the runtime error so that the program can
continue to run or terminate gracefully?
161
Exceptions
❏Unexpected conditions
❏Disrupt normal flow of program
❏With exception handling, we can develop more robust
programs
162
Exceptions
❏ Exceptions are thrown
❏ And can be caught.
163
Where do exceptions come from?
❏JVM
OR
❏Java Programs – can throw an exception
164
Exception Types
165
Exception Hierarchy
System Errors
166
System errors are thrown by JVM and
represented in the Error class. The Error
class describes internal system errors.
Such errors rarely occur. If one does,
there is little you can do beyond
notifying the user and trying to
terminate the program gracefully.
Exceptions
167
Exception describes errors
caused by your program and
external circumstances. These
errors can be caught and
handled by your program.
Runtime Exceptions
168
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-bounds
array, and numeric errors.
Types of Exceptions
❏Errors - serious and fatal problems
❏Exceptions - can be thrown by any program, user can
extend
❏RuntimException - caused by illegal operations, thrown by
JVM (unchecked)
169
Checked Exceptions vs. Unchecked Exceptions
170
❏ RuntimeException, Error and their subclasses are known as
unchecked exceptions.
❏ All other exceptions are known as checked exceptions - the
compiler forces the programmer to check and deal with the
exceptions.
Checked or Unchecked Exceptions
171
Unchecked exception.
Declaring, Throwing, and Catching
Exceptions
Checked Exceptions
❏Checked exceptions that can be thrown in a method
must be
❏caught and handled
OR
❏declared in the throws clause
173
Declaring Exceptions
Every method must state the types of checked
exceptions it might throw. This is known as declaring
exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
174
Throwing Exceptions
When the program detects an error, the program can
create an instance of an appropriate exception type
and throw it. This is known as throwing an exception.
Here is an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
175
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}/
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
Catching Exceptions
Catch or Declare Checked Exceptions
If a method declares a checked exception, you must invoke it in a try-catch
block or declare to throw the exception in the calling method.
In this example, method p1 invokes method p2 and p2 may throw a checked
exception (e.g., IOException)
179
Exceptions in GUI Applications
❏ The methods are executed on the threads. If an exception occurs
on a thread, the thread is terminated if the exception is not
handled. However, the other threads in the application are not
affected.
❏ There are several threads running to support a GUI application.
❏ A thread is launched to execute an event handler (e.g., the
actionPerformed method for the ActionEvent). If an exception
occurs during the execution of a GUI event handler, the thread is
terminated if the exception is not handled.
❏ Interestingly, Java prints the error message on the console, but
does not terminate the application. The program goes back to its
user-interface-processing loop to run continuously.
180
Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}
181
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
182
Cautions When Using Exceptions
• Exception handling separates error-handling code from
normal programming tasks, thus making programs
easier to read and to modify.
• Exception handling usually requires more time and
resources because it requires instantiating a new
exception object, rolling back the call stack, and
propagating the errors to the calling methods.
183
When to Throw Exceptions
❏An exception occurs in a method.
❏If you want the exception to be processed by its caller,
you should create an exception object and throw it.
❏If you can handle the exception in the method where
it occurs, there is no need to throw it.
184
When to Use Exceptions
When should you use the try-catch block in the code? You
should use it to deal with unexpected error conditions.
Do not use it to deal with simple, expected situations. For
example, the following code
185
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
When to Use Exceptions
is better to be replaced by
186
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
187
Exceptions and Inheritance
• Inheritance
– Exception classes can have a common superclass
– catch ( Superclass ref )
• Catches subclasses
• "Is a" relationship
– To catch all exceptions, catch an exception object:
catch( Exception e )
– Polymorphic processing
– Easier to catch superclass than catching every subclass
188
finally Block
❏Resource leaks
❏ Programs obtain and do not return resources
❏ Automatic garbage collection avoids most memory leaks
❏Other leaks can still occur
❏finally block
❏ Placed after last catch block
❏ Can be used to returns resources allocated in try block
❏ Always executed, irregardless whether exceptions thrown or
caught
❏ If exception thrown in finally block, processed by enclosing
try block
Creating user defined Exception Classes
189
❏ Use the exception classes in the API whenever possible.
❏ Create custom exception classes if the predefined
classes are not sufficient.
❏ Declare custom exception classes by extending
Exception or a subclass of Exception.
❏ In java we can create our own exception class and throw
that exception using throw keyword. These exceptions
are known as user-defined or custom exceptions.
Example of User defined exception
class MyException extends Exception{
String str1;
/* Constructor of custom exception class
* here I am copying the message that we are passing while
* throwing the exception to a string and then displaying
* that string along with the message.
*/
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred: "+str1) ;
}
}
Output
Starting of try block
Catch Block
MyException Occurred: This is My error Message
class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of
try block");
// I'm throwing the custom
exception using throw
throw new MyException("This
is My error Message");
}
catch(MyException exp){
System.out.println("Catch
Block") ;
System.out.println(exp) ;
} } } }
You can see that while throwing custom exception I gave a string in parenthesis ( throw new MyException("This is
My error Message");). That’s why we have a parameterized constructor (with a String parameter) in my custom
exception class.
Notes: 1. User-defined exception must extend Exception class.
2. The exception is thrown using throw keyword.
END

Contenu connexe

Similaire à Java 3 Computer Science.pptx

Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
Write a java program that allows the user to input the name of a file.docx
Write a java program that allows the user to input  the name of a file.docxWrite a java program that allows the user to input  the name of a file.docx
Write a java program that allows the user to input the name of a file.docx
noreendchesterton753
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
secunderbadtirumalgi
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
theodorelove43763
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 

Similaire à Java 3 Computer Science.pptx (20)

CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
Basic input-output-v.1.1
Basic input-output-v.1.1Basic input-output-v.1.1
Basic input-output-v.1.1
 
My History
My HistoryMy History
My History
 
Write a java program that allows the user to input the name of a fil.docx
 Write a java program that allows the user to input  the name of a fil.docx Write a java program that allows the user to input  the name of a fil.docx
Write a java program that allows the user to input the name of a fil.docx
 
Write a java program that allows the user to input the name of a file.docx
Write a java program that allows the user to input  the name of a file.docxWrite a java program that allows the user to input  the name of a file.docx
Write a java program that allows the user to input the name of a file.docx
 
History
HistoryHistory
History
 
Java I/O
Java I/OJava I/O
Java I/O
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Hi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfHi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdf
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Systemcall1
Systemcall1Systemcall1
Systemcall1
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 

Plus de MUHAMMED MASHAHIL PUKKUNNUMMAL

Plus de MUHAMMED MASHAHIL PUKKUNNUMMAL (14)

IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
flow of control python.pdf
flow of control python.pdfflow of control python.pdf
flow of control python.pdf
 
Database Management using MS Access.pdf
Database Management using MS Access.pdfDatabase Management using MS Access.pdf
Database Management using MS Access.pdf
 
CA-Web Hosting-Slide.pptx
CA-Web Hosting-Slide.pptxCA-Web Hosting-Slide.pptx
CA-Web Hosting-Slide.pptx
 
loops python.pdf
loops python.pdfloops python.pdf
loops python.pdf
 
flow of control python.pdf
flow of control python.pdfflow of control python.pdf
flow of control python.pdf
 
java 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptxjava 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptx
 
Java 2 computer science.pptx
Java 2 computer science.pptxJava 2 computer science.pptx
Java 2 computer science.pptx
 
java part 1 computer science.pptx
java part 1 computer science.pptxjava part 1 computer science.pptx
java part 1 computer science.pptx
 
2-Arrays.pdf
2-Arrays.pdf2-Arrays.pdf
2-Arrays.pdf
 
Variable scope in php
Variable scope in phpVariable scope in php
Variable scope in php
 
Vardump and printr in php
Vardump and printr in phpVardump and printr in php
Vardump and printr in php
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
Unit1 DBMS Introduction
Unit1 DBMS IntroductionUnit1 DBMS Introduction
Unit1 DBMS Introduction
 

Dernier

result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 

Dernier (20)

Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 

Java 3 Computer Science.pptx

  • 1. UNIT 3 Exceptions, I/O and Threads Input and Output in Java: Muhammed Mashahil
  • 2. Introduction File : A file is collection of related records placed in a particular area on disk. Record : A record is composed of several fields. Fields : A field is group of characters Character : A Character in java is sequence of Unicode characters. file processing: -Storing and manipulating data using files is known as file processing. -Reading/Writing of data in a file can beperformed at the level of bytes, characters, or fields depending on application requirements. -Java also provides capabilities to read and write class objects directly. The process of reading and writing objects is called object serialisation.
  • 3. I/O and Data Movement The flow of data into a program (input) may come from different devices such as keyboard, mouse, memory, disk, network, or another program. The flow of data out of a program (output) may go to the screen, printer, memory, disk, network, another program. Both input and output share a certain common property such as unidirectional movement of data – a sequence of bytes and characters and support to the sequential access to the data.
  • 4. Data representation in java files Marks field Roll no. field Name field
  • 5. ❏ Java.io.File class represents the files and directory pathnames in an abstract manner. ❏ This class is used for creation of files and directories, file searching, file deletion, etc. ❏ The File object represents the actual file/directory on the disk ❏ Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change. ❏ Class File provides information about The class provides ❏ Files and directories ❏ The class provides ❏ A constructor with a String argument ❏ Specifying the name of a file or directory ❏ The name can be either an absolute path or a relative path File class
  • 6. File class fields Modifier Type Field Description static String pathSeparator public static final String pathSeparator The system-dependent path-separator character, represented as a string for convenience. This string contains a single character, namely pathSeparatorChar. static char pathSeparatorChar public static final char pathSeparatorChar The system-dependent path-separator character. This field is initialized to contain the first character of the value of the system property path.separator. This character is used to separate filenames in a sequence of files given as a path list. On UNIX systems, this character is ':'; on Microsoft Windows systems it is ';' static String separator public static final String separator This is the system-dependent default name-separator character, represented as a string for convenience. static char separatorChar public static final char separatorChar The system-dependent default name-separator character. This field is initialized to contain the first character of the value of the system property file.separator. On UNIX systems the value of this field is '/'; on Microsoft Windows systems it is ''.
  • 7. File class Constructors Constructor Description File(File parent, String child) It creates a new File instance from a parent abstract pathname and a child pathname string. File(String pathname) It creates a new File instance by converting the given pathname string into an abstract pathname. File(String parent, String child) It creates a new File instance from a parent pathname string and a child pathname string. File(URI uri) It creates a new File instance by converting the given file: URI into an abstract pathname.
  • 8. File class Constructors import java.io.File; import java.net.URI; import java.net.URISyntaxException; public class FileConstructor { public static void main(String[] args) { File file = new File("A:ihrdjava c5programfile.txt");//First File parent = new File("A:ihrdjava c5program"); //Second File file2 = new File(parent, "data2/file2.txt"); File file3 = new File("D:/pankaj/", "data3/file3.txt"); //Third System.out.println("First : "+file.getAbsolutePath()); System.out.println("Second : "+file2.getAbsolutePath()); System.out.println("Third : "+file3.getAbsolutePath()); //Forth URI uri; try { uri = new URI("file:A:ihrdjava c5programdata3file3.txt"); File file4 = new File(uri); System.out.println("Forth : "+file4.getAbsolutePath()); } catch (URISyntaxException e) { e.printStackTrace(); } } } First : A:ihrdjava c5programdatafile.txt Second : A:ihrdjava c5programdata2file2.txt Third : A:ihrdjava c5programdata3file3.txt Forth : A:ihrdjava c5programdata4file4.txt
  • 9. File class Methods Modifier and Type Method Description static File createTempFile(String prefix, String suffix) It creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. boolean createNewFile() It atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. boolean canWrite() It tests whether the application can modify the file denoted by this abstract pathname.String[] boolean canExecute() It tests whether the application can execute the file denoted by this abstract pathname. boolean canRead() It tests whether the application can read the file denoted by this abstract pathname. boolean isAbsolute() It tests whether this abstract pathname is absolute.
  • 10. Modifier and Type Method Description boolean isDirectory() It tests whether the file denoted by this abstract pathname is a directory. boolean isFile() It tests whether the file denoted by this abstract pathname is a normal file. String getName() It returns the name of the file or directory denoted by this abstract pathname. String getParent() It returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory. Path toPath() It returns a java.nio.file.Path object constructed from the this abstract path. URI toURI() It constructs a file: URI that represents this abstract pathname. File class Methods
  • 11. import java.io.*; public class FileDemo { public static void main(String[] args) { try { File file = new File("A:javaFile123.txt"); if (file.createNewFile()) { System.out.println("New File is created!"); } else { System.out.println("File already exists."); } } catch (IOException e) { e.printStackTrace(); } } } File class Example
  • 12. import java.io.*; class A { public static void main(String[] args) { File file= new File("A:TextBook1.txt"); try { //calling createNewFile() method creates a new File System.out.println("Is the file created ? "+ file.createNewFile()); } catch(IOException e) { System.out.println(e); } File class Example System.out.println("Does this file exists? "+file.exists()); System.out.println("The name of file is "+file.getName()); System.out.println("Parent Directory of this file "+file.getParent()); System.out.println("Path to this file "+file.getPath()); System.out.println("The full path to this file "+file.getAbsolutePath()); System.out.println("Is this a Directory? "+file.isDirectory()); System.out.println("Is this a File? "+file.isFile()); System.out.println("Is this a hidden file "+file.isHidden()); System.out.println("Is this File readable ? "+file.canRead()); System.out.println("Is this File writable ? "+file.canWrite()); } //main method ends } //class definition ends Output Is the file created ? true Does this file exists? true The name of file is TextBook1.txt Parent Directory of this file A: Path to this file A:TextBook1.txt Is this a Directory? false Is this a File? true Is this a hidden file false Is this File readable ? true Is this File writable ? true File size ? 0
  • 14. Streams ❏ Java Uses the concept of Streams to represent the ordered sequence of data, a common characteristic shared by all I/O devices. ❏ Streams presents a uniform, easy to use, object oriented interface between the program and I/O devices. ❏ A stream in Java is a path along which data flows (like a river or pipe along which water flows).
  • 15. Streams ❏ The concepts of sending data from one stream to another (like a pipe feeding into another pipe) has made streams powerful tool for file processing. ❏ Connecting streams can also act as filters. ❏ Streams are classified into two basic types: ❏ Input Steam ❏ Output Stream
  • 18. Standard Streams ❏ There are three standard streams, all of which are managed by the java.lang.System class: 1) System.out: standard output stream Used for program output, typically displays information to the user 2) System.in: standard input stream Used for program input, typically reads input entered by the user. 3) System.err: standard error stream Used to display error messages to the user.
  • 19. Stream classes ❏ Input/Output related classes are defined in java.io package. ❏ Input/Output in Java is defined in terms of streams. ❏ A stream is a sequence of data, of no particular length. ❏ There are 2 kinds of streams ❏ byte streams ❏ character streams
  • 20. Readers/ Writers Input streams/Output streams Operates on 16-bit (2 byte) unicode characters. Operated on 8 bit (1 byte) data. Character streams Byte Streams
  • 22. Keyboard Input ❏ You've already seen that output can be displayed to the user using the subroutine System.out.print. This subroutine is part of a pre-defined object called System.out. The purpose of this object is precisely to display output to the use ❏ There is also a corresponding object called System.in that exists to read data input by the user, but it provides only very primitive input facilities, and it requires some advanced Java programming skills to use it effectively. ❏ here are many ways to read data from the keyboard in java: ❏ Using Command Line Arguments ❏ Console Class ❏ Scanner Class ❏ InputStreamReader Class
  • 23. Using Command Line Arguments ❏ In java, Command Line Arguments is a one of the way to passed arguments at the time of running the java program. ❏ The arguments can be passed from the console can be received in the java program and it can be used as input. ❏ We have pass N numbers of arguments from the command prompt. ❏ For example, We have taken input from the console at the time of running the java program and sum of these integer input. public class InputUsingCMD{ public static void main(String[] args){ int sum=0; for(int i=0;i<args.length;i++){ sum+=Integer.parseInt(args[i]);} System.out.println("The sum of the arguments is "+sum);}}
  • 24. Console Class String text=System.console().readLine(); System.out.println("Text is: "+text); ❏ Console class is be used to get input from console. ❏ It provides methods to read texts and passwords. ❏ If you read password using Console class, it will not be displayed to the user. ❏ The java.io.Console class is attached with system console internally. ❏ The Console class is introduced since 1.5.
  • 25. Console Class Method Description Reader reader() It is used to retrieve the reader object associated with the console String readLine() It is used to read a single line of text from the console. String readLine(String fmt, Object... args) It provides a formatted prompt then reads the single line of text from the console. char[] readPassword() It is used to read password that is not being displayed on the console. char[] readPassword(String fmt, Object... args) It provides a formatted prompt then reads the password that is not being displayed on the console. Console format(String fmt, Object... args) It is used to write a formatted string to the console output stream. Console printf(String format, Object... args) It is used to write a string to the console output stream. PrintWriter writer() It is used to retrieve the PrintWriter object associated with the console. void flush() It is used to flushes the console.
  • 26. Console Class: public class Sample { public static void main(String[] args) { // Using Console to input data from user String name = System.console().readLine(); System.out.println(name); } }
  • 27. Scanner Class ❏ The java.util.Scanner class breaks the input into tokens using delimiter (i.e. Whitespace (By Default)). Its provide various methods to read and parse the various primitive values. ❏ Scanner class is used to parse text for string and primitive types using regular expressions. ❏ For example, we have taken a string. Java Scanner class which reads the int, string value as an input from that string
  • 28. Scanner Creation Syntax Scanner keyboard = new Scanner(System.in); Eg:- Scanner s = new Scanner(System.in); String mj = s.nextLine(); ❏ Scanner is a class which must be instantiated before it can be used. In other words, you must make a new Scanner if you want to use Scanner. ❏ A reference must be used to store the location in memory of the Scanner object created. ❏ System.in is the parameter passed to the Scanner constructor so that Java will know to connect the new Scanner to the keyboard. ❏ keyboard is a reference that will store the location of newly created Scanner object Object instantiation Reference variable
  • 29. Scanner Imports ❏ In order to use Scanner, you must import java.util.Scanner. import java.util.Scanner;
  • 31. Reading in Integers ❏ The nextInt() method is used to tell a Scanner object to retrieve the next integer value entered. ❏ In the example, the next integer typed in on the keyboard would be read in and placed in the integer variable num. ❏ nextInt() will read up to the first whitespace value entered. Scanner keyboard = new Scanner(System.in); System.out.print(“ Enter the number”); int num = keyboard.nextInt(); ❏ The nextInt() method will read in the next integer. If a non-integer value is encountered such as a decimal value, the result will be run-time exception. ❏ keyboard is a reference that refers to a Scanner object
  • 32. Strings ❏ The nextLine() method will read in the next text value entered. A numeric or non- numeric text value will be accepted. ❏ In the example, the next text entered on the keyboard would be read in and placed in variable word. ❏ The nextLine() method would read up to the first whitespace encountered. Whitespace would be any space, any tab, or any enter key.
  • 34. Byte Stream Classes ❏ Byte Stream Classes are used to read bytes from an input stream and write bytes to an output stream. ❏ Byte streams create binary files. ❏ A binary file essentially contains the memory image of the data. That is, it stores bits as they are in memory. ❏ Binary files are faster to read and write because no translation need take place. ❏ Binary files, however, cannot be read with a text editor. ❏ Byte Stream Classes are in divided in two groups - ❏ InputStream Classes - These classes are subclasses of an abstract class, InputStream and they are used to read bytes from a source(file, memory or console). ❏ OutputStream Classes - These classes are subclasses of an abstract class, OutputStream and they are used to write bytes to a destination(file, memory or console).
  • 36. InputStream ❏ InputStream class is a base class of all the classes that are used to read bytes from a file, memory or console. ❏ InputStream is an abstract class and hence we can't create its object but we can use its subclasses for reading bytes from the input stream. ❏ All of the methods in this class will throw an IOException on error conditions ❏ It is also an implementation of an interface named closable ❏ In this interface we have a special method called close()
  • 37. Hierarchy of InputStream classes Object
  • 38. InputStream Classes Stream class Description BufferedInputStream Used for Buffered Input Stream. DataInputStream Contains method for reading java standard datatype FileInputStream Input stream that reads from a file ObjectInputStream Input stream for objects SequenceInputStream Input stream that is a combination of two or more input streams that will be read sequentially,ie. one after another StringBufferInputStream This class allows an application to create an input stream in which the bytes read are supplied by the contents of a string. Only the low eight bits of each character in the string are used by this class. ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method. PipedInputStream Input pipe FilterInputStream Implements InputStream InputStream Abstract class that describe stream input.
  • 40. FileInputStream ❏ FileInputStream class is a subclass of InputStream abstract class. ❏ FileInputStream is used to create an input stream, ❏ which is used to read byte/bytes from a file.
  • 41. Constructors of FileInputStream : FileInputStream(File file) This constructor creates a FileInputStream object to read a file specified by the File object, which is passed to this constructor as a parameter. Example - File file= new File("D:Textbook.txt"); FileInputStream fis= new FileInputStream(file); FileInputStream(String path) This constructor creates a FileInputStream to read a file which is accessed by the path mentioned in the parameters of this constructor. Example - FileInputStream fis= new FileInputStream("D:TextBook.txt"); Both the examples of constructors have created a FileInputStream object to create an input stream to read a file called TextBook.txt which is located in the D: drive
  • 42. Example : import java.io.*; class Demo { public static void main(String[] args) throws IOException { File f = new File("A:IHRDjava c5program2One.txt"); //given the path for file f. InputStream is = new FileInputStream(f); // created an FileInputStream object and passed file f as parameter if(f.exists()) //checking whether file f exists or not. { System.out.println("File exists."); int i = 0; // created a variable i to store the byte data from file f. // read method always returns an integer of range 0 to 255 while((i = is.read()) != -1) // assigning the i value to the byte value obtained from file f through InputStream. { System.out.print((char) i); // casting int to char in order to print characters. } } else System.out.println("File not found."); is.close(); // closing the InputStream } }
  • 43. DataInputStream ❏ DataInputStream is a FilterInputStream that read primitive ❏ data from an underlying input stream in a machine-independent way. It implements the DataInput ❏ interface and provides convenience methods such as readInt(), readChar etc. It also inherits the methods from its immediate parent FilterInputStream.
  • 44. Methods of DataInputStream : Method Description int read(byte[] b) It is used to read the number of bytes from the input stream. int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream. int readInt() It is used to read input bytes and return an int value. byte readByte() It is used to read and return the one input byte. char readChar() It is used to read two input bytes and returns a char value. double readDouble() It is used to read eight input bytes and returns a double value. boolean readBoolean() It is used to read one input byte and return true if byte is non zero, false if byte is zero. int skipBytes(int x) It is used to skip over x bytes of data from the input stream. String readUTF() It is used to read a string that has been encoded using the UTF-8 format. void readFully(byte[] b) It is used to read bytes from the input stream and store them into the buffer array. void readFully(byte[] b, int off, int len) It is used to read len bytes from the input stream.
  • 45. Example Input from keyboard: import java.io.*; public class B{ public static void main(String[] args) throws IOException { DataInputStream dis = new DataInputStream(System.in); System.out.println("Enter text (enter & to end):"); char ch; while ((ch = (char) dis.read()) != '&') System.out.print(ch); } }
  • 46. Example input from file: import java.io.*; public class DataStreamExample { public static void main(String[] args) throws IOException { InputStream input = new FileInputStream("D:testout.txt"); DataInputStream inst = new DataInputStream(input); int count = input.available(); byte[] ary = new byte[count]; inst.read(ary); for (byte bt : ary) { char k = (char) bt; System.out.print(k+"-"); } } }
  • 47. OutputStream ❏ Java application uses an output stream to write data to a destination; ❏ it may be a file, an array, peripheral device or socket. ❏ OutputStream class is an abstract class. ❏ It is the superclass of all classes representing an output stream of bytes. ❏ An output stream accepts output bytes and sends them to some sink.
  • 48. Hierarchy of OutputStream classes Object
  • 49. OutputStream Classes Stream class Description BufferedOutputStream Used for Buffered Output Stream. DataOutputStream An output stream that contain method for writing java standard data type FileOutputStream Output stream that write to a file. PipedOutputStream Itcan be connected to a piped input stream to create a communications pipe. The piped output stream is the sending end of the pipe. Typically, data is written to a PipedOutputStream object by one thread and data is read from the connected PipedInputStream by some other thread. ByteArrayOutputStream It implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString(). OutputStream Abstract class that describe stream output. PrintStream Output Stream that contain print() and println() method
  • 50. OutputStream Class methods ❏ Methods of OutputStream class provide support for writing bytes to the output stream. As this is an abstract class. ❏ Hence, some undefined abstract methods are defined in the subclasses of OutputStream Methods Description flush() This method flushes the output steam by forcing out buffered bytes to be written out. write() This method writes a byte to the output stream. write(byte b[]) This method writes a whole byte array(b) to the output. write(byte b[],int n,int m) This method writes m bytes from array b starting from nth byte to the output. close() This method closes this output stream and also frees any resources connected with this output stream.
  • 51. FileOutputStream ❏ FileOutputStream is an output stream used for writing data to a file. ❏ If you have to write primitive values into a file, use FileOutputStream class. ❏ You can write byte-oriented as well as character-oriented data through FileOutputStream class. ❏ But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.
  • 52. Constructors of FileOutputStream : FileInputStream(File file) This constructor creates a FileOutputStream object to write a file specified by the File object, which is passed to this constructor as a parameter. Example - FileOutputStream(File file) — creates a file output stream to write to a File object. FileOutputStream(File file, boolean append) — creates a file output stream to write to a File object; allows appending mode. FileOutputStream(FileDescriptor fdObj) — creates a file output stream to write to the specified file descriptor. FileOutputStream(String name) — creates a file output stream to write to the file with the specified name. FileOutputStream(String name, boolean append) — creates a file output stream to write to the file with the specified name; allows appending mode
  • 53. Example : import java.io.*; class Test { public static void main(String[] args) throws IOException { File f = new File("A:IHRDjava c5program2One.txt"); //given the path for file f OutputStream os = new FileOutputStream(f); // created an FileOutputStream object and passed file f as parameter if(f.exists()) // checking whether file f exists or not { System.out.println("File exists."); byte b[] = {'i',' ','a','m',' ','f','i','l','e',' ','o','n','e','.'}; // created a byte array. os.write(b);// Writing into file One }else System.out.println("File not found."); os.close(); // closing the OutputStream. InputStream is = new FileInputStream(f); // Reading from file One int i = 0; while((i = is.read()) != -1) { System.out.print((char) i); } is.close(); // closing the InputStream } } Output File exists. i am fileone
  • 54. DataOutputStream ❏ Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way. ❏ Java application generally uses the data output stream to write data that can later be read by a data input stream. Constructor and Description : ❏ DataOutputStream (OutputStream out) : Creates a new data output stream to write data to the specified underlying output stream.
  • 55. Constructors of DataInputStream : FileInputStream(File file) This constructor creates a FileInputStream object to read a file specified by the File object, which is passed to this constructor as a parameter. Example - File file= new File("D:Textbook.txt"); FileInputStream fis= new FileInputStream(file); FileInputStream(String path) This constructor creates a FileInputStream to read a file which is accessed by the path mentioned in the parameters of this constructor. Example - FileInputStream fis= new FileInputStream("D:TextBook.txt"); Both the examples of constructors have created a FileInputStream object to create an input stream to read a file called TextBook.txt which is located in the D: drive Method Description int size() It is used to return the number of bytes written to the data output stream. void write(int b) It is used to write the specified byte to the underlying output stream. void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream. void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte value. void writeChar(int v) It is used to write char to the output stream as a 2-byte value. void writeChars(String s) It is used to write string to the output stream as a sequence of characters. void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value. void writeBytes(String s) It is used to write string to the output stream as a sequence of bytes. void writeInt(int v) It is used to write an int to the output stream void writeShort(int v) It is used to write a short to the output stream. void writeLong(long v) It is used to write a long to the output stream. void writeUTF(String str) It is used to write a string to the output stream using UTF-8 encoding in portable manner. void flush() It is used to flushes the data output stream.
  • 56. Example : import java.io.*; public class OutputExample { public static void main(String[] args) throws IOException { FileOutputStream file = new FileOutputStream(D:testout.txt); DataOutputStream data = new DataOutputStream(file); data.writeInt(65); data.flush(); data.close(); System.out.println("Succcess..."); } }
  • 57. 57 Byte Input Stream - example Count total number of bytes in the file import java.io.*; class CountBytes { public static void main(String[] args) throws FileNotFoundException, IOException { FileInputStream in; in = new FileInputStream("InFile.txt"); int total = 0; while (in.read() != -1) total++; System.out.println(total + " bytes"); } }
  • 58. 58 What happens if the file did not exist ■ JVM throws exception and terminates the program since there is no exception handler defined. Exception in thread "main" java.io.FileNotFoundException: InFile.txt (The system cannot find the file specified) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.io.FileInputStream.<init>(FileInputStream.java:93) at CountBytes.main(CountBytes.java:7)
  • 59. Character streams ❏ The superclass of character-oriented input stream I/O is java.io.Reader.The corresponding output steam is java.io.Writer. Most byte stream classes have a corresponding character stream class. For an example, FileReader is the character-oriented counterpart to FileInputStream and FileWriter is the couterpart to FileOutputStream. ❏ they were added to work specifically with character data (characters, character arrays, strings). ❏ The character stream classes differ from the byte streams classes in that they operate on buffered input and output and properly convert each character from the encoding scheme of the native operating system to the Unicode character set used by the Java platform. ❏ On the other hand, InputStream and OutputStream, and their subclasses operate on bytes and arrays of bytes. The byte-oriented streams can read characters, but they only correctly handle 7-bit ASCII characters (same as the first 128 Unicode characters). ❏ the character stream classes were not added to completely replace the byte stream classes. The InputStream and OutputStream classes remain in the I/O library and they still provide valuable functionality (mainly for reading binary data like primitive types
  • 60. Character streams ❏ Character Stream Classes are used to read characters from the source and write characters to destination. ❏ There are two kinds of Character Stream classes - Reader classes and Writer classes. ❏ Reader Classes - These classes are subclasses of an abstract class, Reader and they are used to read characters from a source(file, memory or console). ❏ Writer Classes - These classes are subclasses of an abstract class, Writer and they used to write characters to a destination(file, memory or console).
  • 62. Reader ❏ Reader class and its subclasses are used to read characters from source. ❏ Reader class is a base class of all the classes that are used to read characters from a file, memory or console. ❏ Reader is an abstract class and hence we can't instantiate it but we can use its subclasses for reading characters from the input stream.
  • 63. Hierarchy of Reader classes Object
  • 64. Reader classes Stream class Description BufferedReader Handles buffered input stream. FileReader Input stream that reads from file. PipedReader Piped character-input streams. InputStreamReader Input stream that translate byte to character CharArrayReader This class implements a character buffer that can be used as a character- input stream. StringReader A character stream whose source is a string Reader Abstract class that define character stream input
  • 65. Reader class methods ❏ These methods are of Reader class Methods Description int read() This method reads a characters from the input stream. int read(char[] ch) This method reads a chunk of characters from the input stream and store them in its char array, ch. close() This method closes this output stream and also frees any system resources connected with it.
  • 66. Writer ❏ Writer class and its subclasses are used to write characters to a file, memory or console. ❏ Writer is an abstract class and hence we can't create its object but we can use its subclasses for writing characters to the output stream
  • 67. Hierarchy of Writer classes Object
  • 68. Writer classes Stream class Description BufferedWriter Handles buffered output stream. FileWriter Output stream that writes to file. OutputStreamReader Output stream that translate character to byte. CharArrayWriter This class implements a character buffer that can be used as an Writer. The buffer automatically grows when data is written to the stream. The data can be retrieved using toCharArray() and toString(). PipedWriter Piped character-output streams. PrintWriter Output Stream that contain print() and println() method. Writer Abstract class that define character stream output
  • 69. Writer class methods ❏ Writer class provide support for writing characters to the output stream. ❏ As this is an abstract class. ❏ Hence, some undefined abstract methods are defined in the subclasses of OutputStream. Methods Description abstract void flush() This method flushes the output steam by forcing out buffered bytes to be written out. void write(int c) This method writes a characters(contained in an int) to the output stream. void write(char[] arr) This method writes a whole char array(arr) to the output stream. abstract void close() This method closes this output stream and also frees any resources connected with this output stream.
  • 70. File I/O using character streams
  • 71. FileReader ❏ Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. ❏ It is character-oriented class which is used for file handling in java.
  • 72. Constructors of FileReader : FileReader(String file) It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. FileReader fr=new FileReader("D:text.txt"); FileReader(File file)It gets filename in file instance. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.
  • 73. Methods of FileReader : Method Description int read() It is used to return a character in ASCII form. It returns -1 at the end of file. void close() It is used to close the FileReader class.
  • 74. Example : import java.io.FileReader; public class FileReaderExample { public static void main(String args[])throws Exception{ FileReader fr=new FileReader("D:testout.txt"); int i; while((i=fr.read())!=-1) System.out.print((char)i); fr.close(); } } Output Welcome to myWorld
  • 75. FileWriter ❏ FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java. ❏ Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly.
  • 76. Constructors of FileWriter : FileWriter(String file) Creates a new file. It gets file name in string. FileWriter fw=new FileWriter("D:text.txt"); FileWriter(File file) Creates a new file. It gets file name in File object.
  • 77. Methods of FileWriter : Method Description void write(String text) It is used to write the string into FileWriter. void write(char c) It is used to write the char into FileWriter. void write(char[] c) It is used to write char array into FileWriter. void flush() It is used to flushes the data of FileWriter. void close() It is used to close the FileWriter.
  • 78. Example : import java.io.FileWriter; public class FileWriterExample { public static void main(String args[]){ try{ FileWriter fw=new FileWriter("D:testout.txt"); fw.write("Welcome to myWorld."); fw.close(); }catch(Exception e){System.out.println(e);} System.out.println("Success..."); } } Output Success...
  • 80. Buffered Streams ❏ Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. ❏ This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. ❏ To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; ❏ the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full. ❏ A program can convert an unbuffered stream into a buffered stream using the wrapping idiom we've used several times now, where the unbuffered stream object is passed to the constructor for a buffered stream class. ❏ Here's modify the constructor invocations to use buffered I/O: ❏ inputStream = new BufferedReader(new FileReader("xyz.txt")); ❏ outputStream = new BufferedWriter(new FileWriter("charoutput.txt")); ❏ There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams.
  • 81. Flushing Buffered Streams ❏ It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer. ❏ Some buffered output classes support autoflush, specified by an optional constructor argument. When autoflush is enabled, certain key events cause the buffer to be flushed. ❏ For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format. See Formatting for more on these methods. ❏ To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered.
  • 82. BufferedInputStream ❏ A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. ❏ When the BufferedInputStream is created, an internal buffer array is created. ❏ As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time. ❏ The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream. ❏ The BufferedInputStream maintains an internal buffer of 8192 bytes. ❏ During the read operation in BufferedInputStream, a chunk of bytes is read from the disk and stored in the internal buffer. And from the internal buffer bytes are read individually. ❏ Hence, the number of communication to the disk is reduced. This is why reading bytes is faster using the BufferedInputStream.
  • 83. BufferedInputStream Constructors and methods Constructor Description BufferedInputStream(InputStream in) Creates a BufferedInputStream and saves its argument, the input stream in, for later use BufferedInputStream(InputStream in, int size) Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in, for later use. Method Description int available() It returns an estimate number of bytes that can be read from the input stream without blocking by the next invocation method for the input stream. int read() It read the next byte of data from the input stream. int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset. void close() It closes the input stream and releases any of the system resources associated with the stream. void reset() It repositions the stream at a position the mark method was last called on this input stream. void mark(int readlimit) It sees the general contract of the mark method for the input stream. long skip(long x) It skips over and discards x bytes of data from the input stream. boolean markSupported() It tests for the input stream to support the mark and reset methods.
  • 84. Example : - BufferedInputstream import java.io.*; public class BufferedInputStreamExample{ public static void main(String args[])throws Exception{ try{ FileInputStream fin=new FileInputStream("D:j.txt"); BufferedInputStream bin=new BufferedInputStream(fin); int i; while((i=bin.read())!=-1){ System.out.print((char)i); } bin.close(); fin.close(); }catch(Exception e){System.out.println(e);} } } Output Hello all
  • 85. BufferedOutputStream ❏ Java.io.BufferedOutputStream class implements a buffered output stream. ❏ By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written. ❏ It extends the OutputStream abstract class ❏ During the write operation, the bytes are written to the internal buffer instead of the disk. Once the buffer is filled or the stream is closed, the whole buffer is written to the disk. ❏ Hence, the number of communication to the disk is reduced. This is why writing bytes is faster using BufferedOutputStream. Fields ❏ protected byte[] buf: The internal buffer where data is stored. ❏ protected int count: The number of valid bytes in the buffer.
  • 86. BufferedOutputStream Constructors and methods Constructor Description BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for writing the data to the specified output stream. BufferedOutputStream(OutputStream os, int size) It creates the new buffered output stream which is used for writing the data to the specified output stream with a specified buffer size. Method Description void write(int b) It writes the specified byte to the buffered output stream. void mark(int readlimit) It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset void flush() It flushes the buffered output stream.
  • 87. Example : - BufferedOutputstream import java.io.*; public class BufferedOutputStreamExample{ public static void main(String args[])throws Exception{ FileOutputStream fout=new FileOutputStream("D:j.txt"); BufferedOutputStream bout=new BufferedOutputStream(fout); String s="Hello all"; byte b[]=s.getBytes(); bout.write(b); bout.flush(); bout.close(); fout.close(); System.out.println("success"); } } Output Success j.txt Hello all Here writing the textual information in the BufferedOutputStream object which is connected to the FileOutputStream object. The flush() flushes the data of one stream and send it into another. It is required if you have connected the one stream with another.
  • 88. BufferedReader ❏ BufferedReader is a Java class that reads text from the input stream. It buffers the characters so that it can get the efficient reading of characters, arrays, etc. ❏ It inherits the reader class and makes the code efficient since we can read the data line-by-line with the readline() method. ❏ There are a few points we have to keep in mind while working with BufferedReader class in Java. ❏ We may have to specify the buffer size even though the default is large enough for any purpose. ❏ With each request made of a reader a corresponding, a read request is also made of an underlying character. ❏ It is always advised to wrap a BufferedReader class around any reader such as InputStreamReaders. ❏ For the programs that use DataInputaStreams for textual input, an appropriate BufferedReader replaces the DataInputStream to localize it
  • 89. BufferedReader Constructor Description BufferedReader(Reader reader) This constructor creates a buffering character-input stream that works on a default-size input buffer. BufferedReader(Reader reader, int size) It uses the specified size for the input buffer for buffering the character- input stream. Method Description int read() Reads a single character String readLine() It reads a line of text void reset() Repositions the stream to the position where the mark method was last called int read(char[] cb, int off , int len) Reads the characters in a portion of an array boolean markSupported() It tests the input stream support for reset and mark method boolean ready() It checks whether the input stream is ready for reading long skip(long n) skips the characters void close() It closes the input stream void mark(int readAheadLimit) Used to mark the current position in the stream
  • 90. File input using BufferedReader ❏ BufferedReader is a Java class to reads the text from an Input stream (like a file) by buffering characters that seamlessly reads characters, arrays or lines. 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 java FileReaders and InputStreamReaders. ❏ A typical usage would involve passing the file path to the BufferedReader as follows: objReader = new BufferedReader(new FileReader("D:DukesDiary.txt"));//Assuming you have a text file in D: This basically loads your file in the objReader.Now, you will need to iterate through the contents of the file and print it The while loop in the below code will read the file until it has reached the end of file while ((strCurrentLine = objReader.readLine()) != null) { System.out.println(strCurrentLine);}
  • 91. Example: File input using BufferedReader import java.io.*; public class BufferedReaderExample { public static void main(String args[])throws Exception{ FileReader fr=new FileReader("D:textout.txt"); BufferedReader br=new BufferedReader(fr); int i; while((i=br.read())!=-1){ System.out.print((char)i); } br.close(); fr.close(); } }
  • 92. BufferedWriter ❏ Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. ❏ It inherits Writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings.
  • 93. BufferedWriter Constructor Description BufferedWriter(Writer wrt) It is used to create a buffered character output stream that uses the default size for an output buffer. BufferedWriter(Writer wrt, int size) It is used to create a buffered character output stream that uses the specified size for an output buffer. Method Description oid newLine() It is used to add a new line by writing a line separator. void write(int c) It is used to write a single character. void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters. void write(String s, int off, int len) It is used to write a portion of a string. void flush() It is used to flushes the input stream. void close() It is used to closes the input stream
  • 94. File I/O using BufferedWriter ❏ BufferedWriter is a sub class of java.io.Writer class. ❏ BufferedWriter writes text to character output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. ❏ The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. ❏ BufferedWriter is used to make lower-level classes like FileWriter more efficient and easier to use. Compared to FileWriters, BufferedWriters write relatively large chunks of data to a file at once, minimizing the number of times that slow, file-writing operations are performed. ❏ The BufferedWriter class also provides a newLine() method to create platform-specific line separators automatically. ❏ In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt")));
  • 95. Example: File IO using BufferedWriter public class BufferedWriterExample { public static void main(String[] args) throws Exception { FileWriter writer = new FileWriter("D:j.txt"); BufferedWriter buffer = new BufferedWriter(writer); buffer.write("Hello World"); buffer.close(); System.out.println("Success"); } } Output Success j.txt Hello all
  • 96. Keyboard input using BufferedReader ❏ To use InputStreamReader ❏ InputStreamReader a = new InputStreamReader(System.in); ❏ An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset ❏ InputStreamReader has methods for reading one char at a time ❏ We don’t want to read one char at a time from user!
  • 97. Example ❏ In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by line data from the keyboard. import java.io.*; public class BufferedReaderExample{ public static void main(String args[])throws Exception{ InputStreamReader r=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(r); System.out.println("Enter your name"); String name=br.readLine(); System.out.println("Welcome "+name); } } Output Enter your name Mahesh k Welcome Mahesh k
  • 98. Example In this example, we are reading and printing the data until the user types stop. import java.io.*; public class BufferedReaderExample{ 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(); r.close(); } } Output Enter Data Mahesh k Data is Mahesh k Enter Data stop Data is stop
  • 100. Process ❏ A process has a self-contained execution environment. ❏ A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. ❏ Most implementations of the Java virtual machine run as a single process.
  • 101. Threads ❏ Threads are sometimes called lightweight processes. ❏ Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. ❏ Threads exist within a process — every process (application) has at least one thread. ❏ Threads share the process's resources, including memory and open files. ❏ Each thread is associated with an instance of the class java.lang.Thread.
  • 103. Advantages ❏ easier to program ❏ 1 thread per task ❏ can provide better performance ❏ thread only runs when needed ❏ no polling to decide what to do ❏ multiple threads can share resources ❏ utilize multiple processors if available Disadvantage ❏ multiple threads can lead to deadlock ❏ much more on this later ❏ overhead of switching between threads
  • 104. Difference between Process and Threads ❏ Process can be divided into multiple threads ❏ Each process has its own memory space ❏ It is difficult to create a process ❏ Threads cannot be sub divided. ❏ Threads of the same process share a common memory space ❏ It is easy to create a thread.
  • 105. Multitasking ❏ Multitasking is a method where multiple tasks are performed during the same period of time ❏ They are executed concurrently instead of sequentially ❏ The tasks share common processing resources, such as a CPU and main memory
  • 106. Difference between multitasking and multithreading ❏ An ability to run several programs simultaneously potentially by using several processors or by time sharing the resources available. ❏ An ability to run serveral processes of a single program simultaneously potentially using several processors or by time sharing the resources available.
  • 107. . public class HelloX { String name = null; // Keeps Thread Name public HelloX(String threadName) {// Constructor name = threadName; } public void run() { for (int i = 0; i < 50; i++) { System.out.println(i + " Hello Thread " + name); } } } public static void main(String[] args) { HelloX t1 = new HelloX(“Raina"); HelloX t2 = new HelloX(“Virat"); t1.run(); t2.run(); } Output 0 Hello Raina 1 Hello Raina 2 Hello Raina ….. ….. 48 Hello Raina 49 Hello Raina 0 Hello Virat 1 Hello Virat 2 Hello Virat … ….. 48 Hello Virat 49 Hello Virat
  • 108. . public class HelloX extends Thread { private String name = null; public HelloX(String threadName) { name = threadName; } public void run() { for (int i = 0;i < 10;i++) { System.out.println(i + " Hello Thread " + name); } } public static void main(String[] args) { HelloX t1 = new HelloX("Raina"); HelloX t2 = new HelloX("Virat"); t1.start(); t2.start(); for (int i = 0; i < 10; i++) { System.out.println(i+" Hello Thread Main"); } } } Output 0 Hello Thread Raina 1 Hello Thread Raina 2 Hello Thread Raina 0 Hello Thread Virat 1 Hello Thread Virat 1 Hello Thread main 2 Hello Thread main 3 Hello Thread main 3 Hello Thread Raina 4 Hello Thread Raina 2 Hello Thread Virat 3 Hello Thread Virat 4 Hello Thread main … ….. 48 Hello Thread Raina 49 Hello Thread Raina 48 Hello Thread Virat
  • 109. Life cycle of Thread
  • 110. Life cycle of Thread ❏ NEW- A thread that is just instantiated is in new state. When a start() method is invoked, the thread moves to the ready state from which it is automatically moved to runnable state by the thread scheduler. ❏ RUNNABLE (ready running)-A thread executing in the JVM is in running state. ❏ BLOCKED - A thread that is blocked waiting for a monitor lock is in this state. This can also occur when a thread performs an I/O operation and moves to next (runnable) state. ❏ WAITING - A thread that is waiting indefinitely for another thread to perform a particular action is in this state. ❏ TIMED_WAITING - A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. ❏ TERMINATED - A thread that has exited is in this state.
  • 111. Thread Creation ❏ Threads can be created using two ways ❏ By implementing the Runnable class ❏ By extending the Thread class ❏ start() method is used to start the thread ❏ run() method is executed after calling the start() ❏ run() can contain the code you wish to perform using thread.
  • 112. Thread class ❏ Java provides Thread class to achieve thread programming. ❏ Thread class provides constructors and methods to create and perform operations on a thread. ❏ Thread class extends Object class and implements Runnable interface. Constructors of Thread class: ➔ Thread() ➔ Thread(String name) ➔ Thread(Runnable r) ➔ Thread(Runnable r,String name)
  • 113. Thread class Methods S.N. Modifier and Type Method Description 1) void start() It is used to start the execution of the thread. 2) void run() It is used to do an action for a thread. 3) static void sleep() It sleeps a thread for the specified amount of time. 4) static Thread currentThread() It returns a reference to the currently executing thread object. 5) void join() It waits for a thread to die. 6) int getPriority() It returns the priority of the thread. 7) void setPriority() It changes the priority of the thread. 8) String getName() It returns the name of the thread. 9) void setName() It changes the name of the thread. 10) long getId() It returns the id of the thread. 11) boolean isAlive() It tests if the thread is alive. 12) static void yield() It causes the currently executing thread object to pause and allow other threads to execute temporarily. 13) void suspend() It is used to suspend the thread. 14) void resume() It is used to resume the suspended thread. 15) void stop() It is used to stop the thread.
  • 114. S.N. Modifier and Type Method Description 16) void destroy() It is used to destroy the thread group and all of its subgroups. 17) boolean isDaemon() It tests if the thread is a daemon thread. 18) void setDaemon() It marks the thread as daemon or user thread. 19) void interrupt() It interrupts the thread. 20) boolean isinterrupted() It tests whether the thread has been interrupted. 21) static boolean interrupted() It tests whether the current thread has been interrupted. 22) static int activeCount() It returns the number of active threads in the current thread's thread group. 23) void checkAccess() It determines if the currently running thread has permission to modify the thread. 24) static boolean holdLock() It returns true if and only if the current thread holds the monitor lock on the specified object. 25) static void dumpStack() It is used to print a stack trace of the current thread to the standard error stream. 26) StackTraceElement[ ] getStackTrace() It returns an array of stack trace elements representing the stack dump of the thread. 27) static int enumerate() It is used to copy every active thread's thread group and its subgroup into the specified array. 28) Thread.State getState() It is used to return the state of the thread. 29) ThreadGroup getThreadGroup() It is used to return the thread group to which this thread belongs 30) String toString() It is used to return a string representation of this thread, including the thread's name, priority, and thread group.
  • 115. S.N. Modifier and Type Method Description 31) void notify() It is used to give the notification for only one thread which is waiting for a particular object. 32) void notifyAll() It is used to give the notification to all waiting threads of a particular object. 33) void setContextClassLoader() It sets the context ClassLoader for the Thread. 34) ClassLoader getContextClassLoader() It returns the context ClassLoader for the thread. 35) static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() It returns the default handler invoked when a thread abruptly terminates due to an uncaught exception. 36) static void setDefaultUncaughtExceptionHandler() It sets the default handler invoked when a thread abruptly terminates due to an uncaught exception.
  • 116. Runnable interface: ❏ The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). public void run(): is used to perform action for a thread. Starting a thread: ❏ start() method of Thread class is used to start a newly created thread. It performs following tasks: ❏ A new thread starts(with new callstack). ❏ The thread moves from New state to the Runnable state. ❏ When the thread gets a chance to execute, its target run() method will run.
  • 117. Creating Threads (extending the Thread class) ❏ extending the Thread class ❏ must implement the run() method ❏ thread ends when run() method finishes ❏ call .start() to get the thread ready to run
  • 118. Creating Threads Example 1 class Output extends Thread { private String toSay; public Output(String st) { toSay = st; } public void run() { try { for(;;) { System.out.println(toSay); sleep(1000); } } catch(InterruptedException e) { System.out.println(e); } } }
  • 119. contn class Program { public static void main(String [] args) { Output thr1 = new Output(“Hello”); Output thr2 = new Output(“There”); thr1.start(); thr2.start(); } } ❏ main thread is just another thread (happens to start first) ❏ main thread can end before the others do ❏ any thread can spawn more threads
  • 120. Java Thread Example by extending Thread classable interface: class Multi extends Thread{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi t1=new Multi(); t1.start(); } } Output thread is running...
  • 121. Creating Threads (implementing Runnable) ❏ implementing Runnable interface ❏ virtually identical to extending Thread class ❏ must still define the run()method ❏ setting up the threads is slightly different
  • 122. Creating Threads Example class Output implements Runnable { private String toSay; public Output(String st) { toSay = st; } public void run() { try { for(;;) { System.out.println(toSay); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println(e); } }}
  • 123. contn. class Program { public static void main(String [] args) { Output out1 = new Output(“Hello”); Output out2 = new Output(“There”); Thread thr1 = new Thread(out1); Thread thr2 = new Thread(out2); thr1.start(); thr2.start(); } } ❏ main is a bit more complex ❏ everything else identical for the most part
  • 124. Advantage of Using Runnable ❏ remember - can only extend one class ❏ implementing runnable allows class to extend something else
  • 125. Java Thread Example by implementing Runnable interface class Multi3 implements Runnable{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi3 m1=new Multi3(); Thread t1 =new Thread(m1); t1.start(); } } Output thread is running... If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitely create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute.
  • 126. Java Thread Example by implementing Runnable interface class Customer{ int amount=10000; synchronized void withdraw(int amount){ System.out.println("going to withdraw..."); if(this.amount<amount){ System.out.println("Less balance; waiting for deposit..."); try{wait();}catch(Exception e){} } this.amount-=amount; System.out.println("withdraw completed..."); } synchronized void deposit(int amount){ System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... "); notify(); } } Output going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed class Test{ public static void main(String args[]){ final Customer c=new Customer(); new Thread(){ public void run(){c.withdraw(15000);} }.start(); new Thread(){ public void run(){c.deposit(10000);} }.start(); }}
  • 127. Java Thread Example 1 class Job implements Runnable { private static Thread [] jobs = new Thread[4]; private int threadID; public Job(int ID) { threadID = ID; } public void run() { do something } public static void main(String [] args) { for(int i=0; i<jobs.length; i++) { jobs[i] = new Thread(new Job(i)); jobs[i].start(); } try { for(int i=0; i<jobs.length; i++) { jobs[i].join(); } } catch(InterruptedException e) { System.out.println(e); } } }
  • 128. Java Thread Example 2 class Schedule implements Runnable { private static Thread [] jobs = new Thread[4]; private int threadID; public Schedule(int ID) { threadID = ID; } public void run() { do something } public static void main(String [] args) { int nextThread = 0; setPriority(Thread.MAX_PRIORITY); for(int i=0; i<jobs.length; i++) { jobs[i] = new Thread(new Job(i)); jobs[i].setPriority(Thread.MIN_PRIORITY); jobs[i].start(); } try { for(;;) { jobs[nextThread].setPriority(Thread.NORM_PRIORITY); Thread.sleep(1000); jobs[nextThread].setPriority(Thread.MIN_PRIORITY); nextThread = (nextThread + 1) % jobs.length; } } catch(InterruptedException e) { System.out.println(e); } }}
  • 129. Extending Thread vs. Implementing Runnable Interface ❏ Choosing between these two is a matter of taste ❏ Implementing the Runnable interface ❏ May take more work since we still ❏ Declare a Thread object ❏ Call the Thread methods on this object ❏ Your class can still extend other class ❏ Extending the Thread class ❏ Easier to implement ❏ Your class can no longer extend any other class
  • 130. ThreadGroup Class ❏ A thread group represents a set of threads ❏ In addition, a thread group can also include other thread groups ❏ The thread groups form a tree in which every thread group except the initial thread group has a parent ❏ A thread is allowed to access information about its own thread group, but not to access information about its thread group's parent thread group or any other thread groups.
  • 131. States of Java Threads ❏ 5 states ❏ new: just created but not started ❏ ready:ready ❏ runnable: created, started, and able to run ❏ blocked: created and started but unable to run because it is waiting for some event to occur ❏ Dead or Finished: thread has finished or been stopped
  • 132. Thread Priority ❏ Each thread is assigned a default priority of Thread.NORM_PRIORITY (constant of 5). You can reset the priority using setPriority(int priority). ❏ Some constants for priorities include Thread.MIN_PRIORITY Thread.MAX_PRIORITY Thread.NORM_PRIORITY ❏ By default, a thread has the priority level of the thread that created it.
  • 133. Controlling Java Threads ❏_.start(): begins a thread running ❏wait() and notify(): for synchronization ❏more on this later ❏_.stop(): kills a specific thread (deprecated) ❏_.suspend() and resume(): deprecated ❏_.join(): wait for specific thread to finish ❏_.setPriority(): 0 to 10 (MIN_PRIORITY to MAX_PRIORITY); 5 is default (NORM_PRIORITY)
  • 134. Java Thread Scheduling ❏An operating system’s thread scheduler determines which thread runs next. ❏ Most operating systems use time slicing for threads of equal priority. ❏ Preemptive scheduling: when a thread of higher priority enters the running state, it preempts the current thread. ❏ Starvation: Higher-priority threads can postpone (possible forever) the execution of lower-priority threads. ❏highest priority thread runs ❏if more than one, arbitrary ❏yield(): current thread gives up processor so another of equal priority can run ❏if none of equal priority, it runs again ❏sleep(msec): stop executing for set time ❏lower priority thread can run
  • 135. Daemon thread ❏ Daemon thread is a low priority thread (in context of JVM) that runs in background to perform tasks such as garbage collection. Properties: ❏ They can not prevent the JVM from exiting when all the user threads finish their execution. ❏ JVM terminates itself when all user threads finish their execution ❏ If JVM finds running daemon thread, it terminates the thread and after that shutdown itself. JVM does not care whether Daemon thread is running or not. ❏ It is an utmost low priority thread. Methods void setDaemon(boolean status): This method is used to mark the current thread as daemon thread or user thread. For example if I have a user thread tU then tU.setDaemon(true) would make it Daemon thread. On the other hand if I have a Daemon thread tD then by calling tD.setDaemon(false) would make it user thread. boolean isDaemon(): This method is used to check that current is daemon. It returns true if the thread is Daemon else it returns false.
  • 136. Daemon thread Example public class TestDaemonThread1 extends Thread{ public void run(){ if(Thread.currentThread().isDaemon()){//checking for daemon thread System.out.println("daemon thread work"); } else{ System.out.println("user thread work"); } } public static void main(String[] args){ TestDaemonThread1 t1=new TestDaemonThread1();//creating thread TestDaemonThread1 t2=new TestDaemonThread1(); TestDaemonThread1 t3=new TestDaemonThread1(); t1.setDaemon(true);//now t1 is daemon thread t1.start();//starting threads t2.start(); t3.start(); } } Output daemon thread work user thread work user thread work Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException
  • 137. Naming Thread ❏ The Thread class provides methods to change and get the name of a thread. By default, each thread has a name i.e. thread-0, thread-1 and so on. ❏ By we can change the name of the thread by using setName() method. The syntax of setName() and getName() methods are given below: public String getName(): is used to return the name of a thread. public void setName(String name): is used to change the name of a thread. Eg:- class TestMultiNaming1 extends Thread{ public void run(){ System.out.println("running..."); } public static void main(String args[]){ TestMultiNaming1 t1=new TestMultiNaming1(); TestMultiNaming1 t2=new TestMultiNaming1(); System.out.println("Name of t1:"+t1.getName()); System.out.println("Name of t2:"+t2.getName()); t1.start(); t2.start(); t1.setName("javac5"); System.out.println("After changing name of t1:"+t1.getName()); } } Output Name of t1:Thread-0 Name of t2:Thread-1 id of t1:8 running... After changeling name of t1:javac5 running...
  • 138. ❏ A race condition is a special condition that may occur inside a critical section. A critical section is a section of code that is executed by multiple threads and where the sequence of execution for the threads makes a difference in the result of the concurrent execution of the critical section. ❏ When the result of multiple threads executing a critical section may differ depending on the sequence in which the threads execute, the critical section is said to contain a race condition. The term race condition stems from the metaphor that the threads are racing through the critical section, and that the result of that race impacts the result of executing the critical section. ❏ This may all sound a bit complicated, so I will elaborate more on race conditions and critical sections in the following sections. Race Conditions and Critical Sections
  • 139. ❏ Running more than one thread inside the same application does not by itself cause problems. The problems arise when multiple threads access the same resources. For instance the same memory (variables, arrays, or objects), systems (databases, web services etc.) or files. ❏ In fact, problems only arise if one or more of the threads write to these resources. It is safe to let multiple threads read the same resources, as long as the resources do not change. ❏ Here is a critical section Java code example that may fail if executed by multiple threads simultaneously: public class Counter { protected long count = 0; public void add(long value){ this.count = this.count + value; } } ❏ Imagine if two threads, A and B, are executing the add method on the same instance of the Counter class. There is no way to know when the operating system switches between the two threads. The code in the add() method is not executed as a single atomic instruction by the Java virtual machine. Rather it is executed as a set of smaller instructions, similar to this: ❏ Read this.count from memory into register. ❏ Add value to register. ❏ Write register to memory. ❏ Observe what happens with the following mixed execution of threads A and B: Race Conditions and Critical Sections
  • 140. this.count = 0; A: Reads this.count into a register (0) B: Reads this.count into a register (0) B: Adds value 2 to register B: Writes register value (2) back to memory. this.count now equals 2 A: Adds value 3 to register A: Writes register value (3) back to memory. this.count now equals 3 ❏ The two threads wanted to add the values 2 and 3 to the counter. Thus the value should have been 5 after the two threads complete execution. However, since the execution of the two threads is interleaved, the result ends up being different. ❏ In the execution sequence example listed above, both threads read the value 0 from memory. Then they add their i ndividual values, 2 and 3, to the value, and write the result back to memory. Instead of 5, the value left in this.count will be the value written by the last thread to write its value. In the above case it is thread A, but it could as well have been thread B. Race Conditions and Critical Sections
  • 141. Race Conditions in Critical Sections ❏ The code in the add() method in the example earlier contains a critical section. When multiple threads execute this critical section, race conditions occur. ❏ More formally, the situation where two threads compete for the same resource, where the sequence in which the resource is accessed is significant, is called race conditions. A code section that leads to race conditions is called a critical section. Preventing Race Conditions ❏ To prevent race conditions from occurring you must make sure that the critical section is executed as an atomic instruction. That means that once a single thread is executing it, no other threads can execute it until the first thread has left the critical section. ❏ Race conditions can be avoided by proper thread synchronization in critical sections. Thread synchronization can be achieved using a synchronized block of Java code. Thread synchronization can also be achieved using other synchronization constructs like locks or atomic variables like java.util.concurrent.atomic.AtomicInteger. Race Conditions and Critical Sections
  • 142. Synchronization Why use Synchronization in Java? 1. To prevent thread interference. 2. To prevent consistency problem If there at least two threads inside a program, there might be a chance when multiple threads attempt to get to the same resource. It can even create an unexpected outcome because of concurrency issues. Syntax: synchronized(objectidentifier) { // Access shared variables and other shared resources; } For example, multiple threads attempt to write within an equivalent file. This may corrupt the data since one of the threads can override the data or when a thread is opening the same file at the same time, another thread might be closing the same file. There is a need to synchronize the action of multiple threads. This can be implemented using a concept called Monitors. ❏ Each object in Java is associated with a monitor, which a thread can lock or unlock. ❏ Only one thread at a time may hold a lock on a monitor. ❏ Java programming language provides a very handy way of creating threads and synchronizing their task by using the Synchronized blocks. ❏ It also keeps the shared resources within this particular block.
  • 143. Synchronization Synchronized blocks in Java are marked with the Synchronized keyword. This block in Java is synchronized on some object. All blocks that are synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block. Types of Synchronization There are basically two types of synchronization available. They are: ❏ Process Synchronization: The simultaneous execution of multiple threads or processes to reach a state such that they commit to a certain sequence of actions. ❏ Thread Synchronization: At times when more than one thread tries to access a shared resource, you need to ensure that resource will be used by only one thread at a time. Let’s not get into the details of these types and try to understand what are locks in Java.
  • 144. Locks in Java As I mentioned earlier, Synchronization is built around an internal entity known as the lock or monitor. Each and every object has a lock associated with it. So a thread that needs consistent access to an object’s fields needs to acquire the object’s lock before accessing them, and then release the lock when the work is done. From Java 5, the package java.util.concurrent.locks contains many lock implementations. This is how a lock looks like: public class Lock { private boolean isLocked = false; public synchronized void lock() throws InterruptedException { while(isLocked) { wait(); } isLocked = true; } public synchronized void unlock() { isLocked = false; notify(); } } The lock() method locks the Lock instance so that all threads calling lock() are blocked until unlock() is executed
  • 145. Multi-threading without Synchronization Here is a simple example which prints the counter value in a sequence and every time we run it, it produces a different result based on CPU availability to a thread. Check this out! class Table{ void printTable(int n){//method not synchronized for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){ System.out.println(e); } } } } class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } } class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100); } } public class TestThread{ public static void main(String args[]){ Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } }
  • 147. Multi-threading with Synchronization This is the same example as above but it prints the counter value in the sequence. Every time we run it, it produces the same result. class Table{ synchronized void printTable(int n){//synchronized method for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } } class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100); } } public class Test1{ public static void main(String args[]){ Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } }
  • 149. Synchronized Keyword Java synchronized keyword marks a block or a method a critical section. A critical section is where only one thread is executing at a time, and the thread holds the lock for the synchronized section. This synchronized keyword helps in writing concurrent parts of any application. It also protects shared resources within the block. The synchronized keyword can be used with: ❏ A code block ❏ A method Let’s discuss the code block. Synchronized Keyword: A code block Syntax The general syntax for writing a synchronized block is: synchronized ( lockObject) { //synchronized statements }
  • 150. Synchronized Keyword ❏ When a thread wants to execute the synchronized statements inside the block, it must acquire the lock on the lockObject‘s monitor. Only one thread can acquire the monitor of a lock object at a time. So all other threads must wait till the currently executing thread acquires the lock and finish its execution. ❏ This way, the synchronized keyword guarantees that only one thread will be executing the synchronized block statements at a time, and thus prevents multiple threads from corrupting the shared data that is present inside the block. Note:If a thread is put on sleep (using sleep() method) then it does not release the lock. During this sleep time, no thread will be executing the synchronized block statements. Java synchronization will throw NullPointerException if lock object used in ‘synchronized (lock)‘ is null.
  • 151. Inter-thread communication ❏ Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. ❏ Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class: ❏ wait() Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception. ❏ notify() Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax: public final void notify() ❏ notifyAll() Wakes up all threads that are waiting on this object's monitor. Syntax: public final void notifyAll()
  • 152. Understanding the process of inter-thread communication ❏ Threads enter to acquire lock. ❏ Lock is acquired by on thread. ❏ Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. ❏ If you call notify() or notifyAll() method, thread moves to the notified state (runnable state). ❏ Now thread is available to acquire lock. ❏ After completion of the task, thread releases the lock and exits the monitor state of the object.
  • 153. Difference between wait and sleep wait() sleep() wait() method releases the lock sleep() method doesn't release the lock. is the method of Object class is the method of Thread class is the non-static method is the static method is the non-static method is the static method should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is completed.
  • 154. Synchronized Keyword Synchronized Keyword: A method Syntax The general syntax for writing a synchronized method is: <access modifier> synchronized method ( parameters) { //synchronized code } Here lockObject is just a reference to an object whose lock is associated with the monitor which represents the synchronized statements. Similar to the synchronized block, a thread must acquire the lock on the connected monitor object with the synchronized method. In the case of synchronized method, the lock object is: ‘.class’ object – if the given method is static. ‘this’ object – if the method is non-static. ‘this’ is the reference to the current object in which the synchronized method is invoked. Java synchronized keyword is re-entrant in nature. It means if a synchronized method calls another synchronized method which requires the same lock, then current thread which is holding the lock can enter into that method without acquiring the lock.
  • 155. Difference between synchronized keyword and synchronized block When you use synchronized keyword with a method, it acquires a lock in the object for the entire method. This means that no other thread can use any synchronized method until the current thread that is invoked has finished its execution. Synchronized block acquires a lock in the object only between parentheses after the synchronized keyword is specified. This means that no other thread can acquire a lock on the already locked object until the block exits. But other threads will be able to access the rest of the code that is present in the method. This brings us to the end of this article where we have discussed how exactly Synchronization in Java works.
  • 156. Deadlock ❏ synchronized keyword is used to make the class or method thread-safe which means only one thread can have lock of synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock. ❏ It is important to use if our program is running in multi-threaded environment where two or more threads execute simultaneously. But sometimes it also causes a problem which is called Deadlock. Below is a simple example of Deadlock condition.
  • 157. Java program to illustrate Deadlock in multithreading. class Util { // Util class to sleep a thread static void sleep(long millis) { try{ Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } } // This class is shared by both threads class Shared { // first synchronized method synchronized void test1(Shared s2) { System.out.println("test1-begin"); Util.sleep(1000); // taking object lock of s2 enters // into test2 method s2.test2(); System.out.println("test1-end"); } // second synchronized method synchronized void test2() { System.out.println("test2-begin"); Util.sleep(1000); // taking object lock of s1 enters // into test1 method System.out.println("test2-end"); } } public class Deadlock { public static void main(String[] args) { // creating one object Shared s1 = new Shared(); // creating second object Shared s2 = new Shared(); // creating first thread and starting it Thread1 t1 = new Thread1(s1, s2); t1.start(); // creating second thread and starting it Thread2 t2 = new Thread2(s1, s2); t2.start(); // sleeping main thread Util.sleep(2000); } } class Thread1 extends Thread { private Shared s1; private Shared s2; // constructor to initialize fields public Thread1(Shared s1, Shared s2) { this.s1 = s1; this.s2 = s2; } // run method to start a thread @Override public void run() { /* taking object lock of s1 enters into test1 method */ s1.test1(s2); } } class Thread2 extends Thread { private Shared s1; private Shared s2; // constructor to initialize fields public Thread2(Shared s1, Shared s2){ this.s1 = s1; this.s2 = s2; } // run method to start a thread @Override public void run() { // taking object lock of s2 // enters into test2 method s2.test1(s1); } } Output test1-begin test2-begin
  • 158. Java program to illustrate Deadlock in multithreading. We can see that it runs for indefinite time, because threads are in deadlock condition and doesn’t let code to execute. Now let’s see step by step what is happening there. 1. Thread t1 starts and calls test1 method by taking the object lock of s1. 2. Thread t2 starts and calls test2 method by taking the object lock of s2. 3. t1 prints test1-begin and t2 prints test-2 begin and both waits for 1 second, so that both threads can be started if any of them is not. 4. t1 tries to take object lock of s2 and call method test2 but as it is already acquired by t2 so it waits till it become free. It will not release lock of s1 until it gets lock of s2. 5. Same happens with t2. It tries to take object lock of s1 and call method test1 but it is already acquired by t1, so it has to wait till t1 release the lock. t2 will also not release lock of s2 until it gets lock of s1. 6. Now, both threads are in wait state, waiting for each other to release locks. Now there is a race around condition that who will release the lock first. 7. As none of them is ready to release lock, so this is the Dead Lock condition. 8. When you will run this program, it will be look like execution is paused.
  • 159. Detect Dead Lock condition ❏ We can also detect deadlock by running this program on cmd. We have to collect Thread Dump. Command to collect depends on OS type. If we are using Windows and Java 8, command is jcmd $PID Thread.print ❏ We can get PID by running jps command. Avoid Dead Lock condition ❏ We can avoid dead lock condition by knowing its possibilities. It’s a very complex process and not easy to catch. But still if we try, we can avoid this. ❏ There are some methods by which we can avoid this condition. We can’t completely remove its possibility but we can reduce. ❏ Avoid Nested Locks : This is the main reason for dead lock. Dead Lock mainly happens when we give locks to multiple threads. Avoid giving lock to multiple threads if we already have given to one. Avoid Unnecessary Locks : We should have lock only those members which are required. Having lock on unnecessarily can lead to dead lock. Using thread join : Dead lock condition appears when one thread is waiting other to finish. If this condition occurs we can use Thread.join with maximum time you think the execution will take. If threads are waiting for each other to finish, then the condition is known as Deadlock.Deadlock condition is a complex condition which occurs only in case of multiple threads.Deadlock condition can break our code at run time and can destroy business logic.We should avoid this condition as much as we can.
  • 161. Motivations ❏ When a program runs into a runtime error, the program terminates abnormally. ❏ How can you handle the runtime error so that the program can continue to run or terminate gracefully? 161
  • 162. Exceptions ❏Unexpected conditions ❏Disrupt normal flow of program ❏With exception handling, we can develop more robust programs 162
  • 163. Exceptions ❏ Exceptions are thrown ❏ And can be caught. 163
  • 164. Where do exceptions come from? ❏JVM OR ❏Java Programs – can throw an exception 164
  • 166. System Errors 166 System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
  • 167. Exceptions 167 Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
  • 168. Runtime Exceptions 168 RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
  • 169. Types of Exceptions ❏Errors - serious and fatal problems ❏Exceptions - can be thrown by any program, user can extend ❏RuntimException - caused by illegal operations, thrown by JVM (unchecked) 169
  • 170. Checked Exceptions vs. Unchecked Exceptions 170 ❏ RuntimeException, Error and their subclasses are known as unchecked exceptions. ❏ All other exceptions are known as checked exceptions - the compiler forces the programmer to check and deal with the exceptions.
  • 171. Checked or Unchecked Exceptions 171 Unchecked exception.
  • 172. Declaring, Throwing, and Catching Exceptions
  • 173. Checked Exceptions ❏Checked exceptions that can be thrown in a method must be ❏caught and handled OR ❏declared in the throws clause 173
  • 174. Declaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException 174
  • 175. Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, throw new TheException(); TheException ex = new TheException(); throw ex; 175
  • 176. Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }/
  • 177. Catching Exceptions try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } ... catch (ExceptionN exVar3) { handler for exceptionN; }
  • 179. Catch or Declare Checked Exceptions If a method declares a checked exception, you must invoke it in a try-catch block or declare to throw the exception in the calling method. In this example, method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException) 179
  • 180. Exceptions in GUI Applications ❏ The methods are executed on the threads. If an exception occurs on a thread, the thread is terminated if the exception is not handled. However, the other threads in the application are not affected. ❏ There are several threads running to support a GUI application. ❏ A thread is launched to execute an event handler (e.g., the actionPerformed method for the ActionEvent). If an exception occurs during the execution of a GUI event handler, the thread is terminated if the exception is not handled. ❏ Interestingly, Java prints the error message on the console, but does not terminate the application. The program goes back to its user-interface-processing loop to run continuously. 180
  • 181. Rethrowing Exceptions try { statements; } catch(TheException ex) { perform operations before exits; throw ex; } 181
  • 182. The finally Clause try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } 182
  • 183. Cautions When Using Exceptions • Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. • Exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods. 183
  • 184. When to Throw Exceptions ❏An exception occurs in a method. ❏If you want the exception to be processed by its caller, you should create an exception object and throw it. ❏If you can handle the exception in the method where it occurs, there is no need to throw it. 184
  • 185. When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code 185 try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); }
  • 186. When to Use Exceptions is better to be replaced by 186 if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null");
  • 187. 187 Exceptions and Inheritance • Inheritance – Exception classes can have a common superclass – catch ( Superclass ref ) • Catches subclasses • "Is a" relationship – To catch all exceptions, catch an exception object: catch( Exception e ) – Polymorphic processing – Easier to catch superclass than catching every subclass
  • 188. 188 finally Block ❏Resource leaks ❏ Programs obtain and do not return resources ❏ Automatic garbage collection avoids most memory leaks ❏Other leaks can still occur ❏finally block ❏ Placed after last catch block ❏ Can be used to returns resources allocated in try block ❏ Always executed, irregardless whether exceptions thrown or caught ❏ If exception thrown in finally block, processed by enclosing try block
  • 189. Creating user defined Exception Classes 189 ❏ Use the exception classes in the API whenever possible. ❏ Create custom exception classes if the predefined classes are not sufficient. ❏ Declare custom exception classes by extending Exception or a subclass of Exception. ❏ In java we can create our own exception class and throw that exception using throw keyword. These exceptions are known as user-defined or custom exceptions.
  • 190. Example of User defined exception class MyException extends Exception{ String str1; /* Constructor of custom exception class * here I am copying the message that we are passing while * throwing the exception to a string and then displaying * that string along with the message. */ MyException(String str2) { str1=str2; } public String toString(){ return ("MyException Occurred: "+str1) ; } } Output Starting of try block Catch Block MyException Occurred: This is My error Message class Example1{ public static void main(String args[]){ try{ System.out.println("Starting of try block"); // I'm throwing the custom exception using throw throw new MyException("This is My error Message"); } catch(MyException exp){ System.out.println("Catch Block") ; System.out.println(exp) ; } } } } You can see that while throwing custom exception I gave a string in parenthesis ( throw new MyException("This is My error Message");). That’s why we have a parameterized constructor (with a String parameter) in my custom exception class. Notes: 1. User-defined exception must extend Exception class. 2. The exception is thrown using throw keyword.
  • 191. END