SlideShare a Scribd company logo
1 of 282
Lecture By,
Prabu.U
Assistant Professor,
Department of Computer Science and Engineering.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING,
V R Siddhartha Engineering College.
20ES3102 – JAVA PROGRAMMING
UNIT 3
UNIT III:
Exception handling: Exception handling fundamentals, exception types,
uncaught exceptions, using try and catch, multiple catch clauses, throw,
throws, finally, creating your own exception subclasses.
Stream Classes: Byte Streams- InputStream, OutputStream,
FileInputStream, FileOutputStream, Character Streams- Reader, Writer,
FileReader, FileWriter.
Multithread Programming: The Java Thread Model, creating a thread:
Implementing Runnable, Extending Thread, creating multiple threads,
Thread Priorities, Synchronization: Using Synchronized methods, The
synchronized Statement.
20ES3102 – JAVA PROGRAMMING
1. Exception-Handling Fundamentals
2. Exception Types
3. Uncaught Exceptions
4. Using try and catch
5. Multiple catch Clauses
6. throw, throws, finally
7. Creating Your Own Exception Subclasses
EXCEPTION HANDLING
1. Byte Streams
 InputStream
 OutputStream
 FileInputStream
 FileOutputStream
2. Character Streams
 Reader
 Writer
 FileReader
 FileWriter
STREAM CLASSES
1. The Java Thread Model
2. Creating a Thread
 Implementing Runnable
 Extending Thread
3. Creating Multiple Threads
4. Thread Priorities
5. Synchronization
 Using Synchronized methods
 The synchronized Statement
MULTITHREADED PROGRAMMING
1. Exception-Handling Fundamentals
 A Java exception is an object that describes an exceptional (that is,
error) condition that has occurred in a piece of code.
 When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the
error.
 That method may choose to handle the exception itself or pass it
on. Either way, at some point, the exception is caught and
processed.
 Exceptions can be generated by the Java run-time system, or they
can be manually generated by your code
 Exceptions thrown by Java relate to fundamental errors that violate
the rules of the Java language or the constraints of the Java
execution environment.
 Manually generated exceptions are typically used to report some
error condition to the caller of a method.
 Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally.
 Program statements that you want to monitor for exceptions are
contained within a try block.
 If an exception occurs within the try block, it is thrown.
 Your code can catch this exception (using catch) and handle it in
some rational manner.
 System-generated exceptions are automatically thrown by the Java
runtime system.
 To manually throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be specified as such
by a throws clause.
 Any code that absolutely must be executed after a try block
completes is put in a finally block.
This is the general form of an exception-handling block:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally
{
// block of code to be executed after try block ends
}
2. Exception Types
 All exception types are subclasses of the built-in class Throwable.
Thus, Throwable is at the top of the exception class hierarchy.
 Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches. One branch is headed by
Exception.
 This class is used for exceptional conditions that user programs
should catch.
 This is also the class that you will subclass to create your own
custom exception types.
 There is an important subclass of Exception, called
RuntimeException.
 Exceptions of this type are automatically defined for the programs
that you write and include things such as division by zero and
invalid array indexing.
 The other branch is topped by Error, which defines exceptions that
are not expected to be caught under normal circumstances by your
program.
 Exceptions of type Error are used by the Java run-time system to
indicate errors having to do with the run-time environment, itself.
Stack overflow is an example of such an error.
3. Uncaught Exceptions
 This small program includes an expression that intentionally
causes a divide-by-zero error:
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
 When the Java run-time system detects the attempt to divide by zero, it
constructs a new exception object and then throws this exception.
 This causes the execution of Exc0 to stop, because once an exception has
been thrown, it must be caught by an exception handler and dealt with
immediately.
 In this example, we haven’t supplied any exception handlers of our own,
so the exception is caught by the default handler provided by the Java run-
time system.
 Any exception that is not caught by your program will ultimately be
processed by the default handler.
 The default handler displays a string describing the exception, prints a
stack trace from the point at which the exception occurred, and terminates
the program.
 Here is the exception generated when this example is executed:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
4. Using try and catch
 Although the default exception handler provided by the Java run-
time system is useful for debugging, you will usually want to
handle an exception yourself.
 Doing so provides two benefits. First, it allows you to fix the error.
Second, it prevents the program from automatically terminating.
 To handle a run-time error, simply enclose the code that you want
to monitor inside a try block.
 Immediately following the try block, include a catch clause that
specifies the exception type that you wish to catch.
class Exc2
{
public static void main(String args[])
{
int d, a;
// monitor a block of code
try
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
// catch divide-by-zero error
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Division by zero.
After catch statement.
 Once an exception is thrown, program control transfers out of the try
block into the catch block.
 A try and its catch statement form a unit.
 The scope of the catch clause is restricted to those statements
specified by the immediately preceding try statement.
 A catch statement cannot catch an exception thrown by another try
statement (except in the case of nested try statements, described
shortly).
 The statements that are protected by try must be surrounded by
curly braces (That is, they must be within a block.)
Java Random Class Methods
nextBoolean() - This method returns next pseudorandom which is a
boolean value from random number generator sequence.
nextDouble() - his method returns next pseudorandom which is double
value between 0.0 and 1.0.
nextFloat() - This method returns next pseudorandom which is float value
between 0.0 and 1.0.
nextInt() - This method returns next int value from random number
generator sequence.
nextInt(int n) - This method return a pseudorandom which is int value
between 0 and specified value from random number generator sequence.
import java.util.Random;
public class RandomNumberExample
{
public static void main(String[] args)
{
//initialize random number generator
Random random = new Random();
//generates boolean value
System.out.println(random.nextBoolean());
//generates double value
System.out.println(random.nextDouble());
//generates float value
System.out.println(random.nextFloat());
//generates int value
System.out.println(random.nextInt());
//generates int value within specific limit
System.out.println(random.nextInt(20));
}
}
false
0.21218821288158107
0.96327835
930869598
6
import java.util.Random;
class HandleError
{
public static void main(String args[])
{
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<10; i++)
{
try
{
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
a: -12345
Division by zero.
a: 0
Division by zero.
a: 0
Division by zero.
a: 0
Division by zero.
a: 0
Division by zero.
a: 0
a: -2469
a: -12345
Division by zero.
a: 0
a: 4115
 In the next program each iteration of the for loop obtains two
random integers.
 Those two integers are divided by each other, and the result is used
to divide the value 12345.
 The final result is put into a. If either division operation causes a
divide-by-zero error, it is caught, the value of a is set to zero, and
the program continues.
Displaying a Description of an Exception
 Throwable overrides the toString( ) method (defined by Object) so
that it returns a string containing a description of the exception.
 You can display this description in a println( ) statement by simply
passing the exception as an argument.
import java.util.Random;
class HandleErrorDescription
{
public static void main(String args[])
{
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<10; i++)
{
try
{
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
}
catch (ArithmeticException e)
{
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Output:
Exception: java.lang.ArithmeticException: / by zero
a: 0
Exception: java.lang.ArithmeticException: / by zero
a: 0
Exception: java.lang.ArithmeticException: / by zero
a: 0
a: -6172
a: 12345
a: 12345
Exception: java.lang.ArithmeticException: / by zero
a: 0
a: 6172
a: 12345
a: 12345
5. Multiple catch Clauses
 In some cases, more than one exception could be raised by a single
piece of code.
 To handle this type of situation, you can specify two or more catch
clauses, each catching a different type of exception.
 When an exception is thrown, each catch statement is inspected in
order, and the first one whose type matches that of the exception is
executed.
 After one catch statement executes, the others are bypassed, and
execution continues after the try / catch block.
class MultipleCatches
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
6. throw, throws, finally
throw
 So far, you have only been catching exceptions that are thrown by
the Java run-time system.
 However, it is possible for your program to throw an exception
explicitly, using the throw statement. The general form of throw is
shown here:
throw ThrowableInstance;
 Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throwable.
 Primitive types, such as int or char, as well as non-Throwable
classes, such as String and Object, cannot be used as exceptions.
 There are two ways you can obtain a Throwable object: using a
parameter in a catch clause or creating one with the new operator.
 The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed.
 The nearest enclosing try block is inspected to see if it has a catch
statement that matches the type of exception.
 If it does find a match, control is transferred to that statement.
 If not, then the next enclosing try statement is inspected, and so on.
 If no matching catch is found, then the default exception handler
halts the program and prints the stack trace.
public class TestThrow
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
Exception in thread "main" java.lang.ArithmeticException: not valid
at TestThrow.validate(TestThrow.java:6)
at TestThrow.main(TestThrow.java:12)
throws
 The throws keyword is used in the method declaration to declare
the type of exceptions that might occur within it.
 Its syntax is:
accessModifier returnType methodName() throws
ExceptionType1, ExceptionType2 …
{
// code
}
import java.io.*;
class TestThrows
{
public static void findFile() throws IOException
{
// code that may produce IOException
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}
public static void main(String[] args)
{
try
{
findFile();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
java.io.FileNotFoundException: test.txt (The system cannot find the file
specified)
Differences between throw and throws
finally
 finally creates a block of code that will be executed after a try /catch
block has completed and before the code following the try/catch
block.
 The finally block will execute whether or not an exception is thrown.
 If an exception is thrown, the finally block will execute even if no
catch statement matches the exception.
 Any time a method is about to return to the caller from inside a
try/catch block, via an uncaught exception or an explicit return
statement, the finally clause is also executed just before the method
returns.
 This can be useful for closing file handles and freeing up any other
resources that might have been allocated at the beginning of a
method with the intent of disposing of them before returning.
 The finally clause is optional. However, each try statement requires
at least one catch or a finally clause.
public class TestFinally
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...
7. Creating Your Own Exception Subclasses
 Although Java’s built-in exceptions handle most common errors,
you will probably want to create your own exception types to
handle situations specific to your applications.
 This is quite easy to do: just define a subclass of Exception (which
is, of course, a subclass of Throwable).
 Your subclasses don’t need to actually implement anything—it is
their existence in the type system that allows you to use them as
exceptions.
 The Exception class does not define any methods of its own. It
does, of course, inherit those methods provided by Throwable.
 Thus, all exceptions, including those that you create, have the
methods defined by Throwable available to them.
 You may also wish to override one or more of these methods in
exception classes that you create.
 Exception defines four public constructors. Two support chained
exceptions, described in the next section. The other two are shown
here:
 Exception( )
 Exception(String msg)
 The first form creates an exception that has no description. The
second form lets you specify a description of the exception.
 Although specifying a description when an exception is created is
often useful, sometimes it is better to override toString( ). Here’s
why: The version of toString( ) defined by Throwable (and
inherited by Exception) first displays the name of the exception
followed by a colon, which is then followed by your description.
 By overriding toString( ), you can prevent the exception name and
colon from being displayed.
 This makes for a cleaner output, which is desirable in some cases.
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
class ExceptionDemo
{
static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[])
{
try
{
compute(1);
compute(20);
}
catch (MyException e)
{
System.out.println("Caught " + e);
}
}
}
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
Chained Exceptions
 To allow chained exceptions, two constructors and two methods were
added to Throwable. The constructors are shown here:
 Throwable(Throwable causeExc)
 Throwable(String msg, Throwable causeExc)
 In the first form, causeExc is the exception that causes the current
exception. That is, causeExc is the underlying reason that an exception
occurred.
 The second form allows you to specify a description at the same time
that you specify a cause exception.
 These two constructors have also been added to the Error, Exception,
and RuntimeException classes.
 The chained exception methods supported by Throwable are
getCause( ) and initCause( ).
 Throwable getCause( )
 Throwable initCause(Throwable causeExc)
 The getCause( ) method returns the exception that underlies the
current exception.
 If there is no underlying exception, null is returned. The
initCause( ) method associates causeExc with the invoking
exception and returns a reference to the exception.
 Thus, you can associate a cause with an exception after the
exception has been created.
 However, the cause exception can be set only once.
 Thus, you can call initCause( ) only once for each exception object.
 Furthermore, if the cause exception was set by a constructor, then
you can’t set it again using initCause( ).
 In general, initCause( ) is used to set a cause for legacy exception
classes that don’t support the two additional constructors described
earlier.
class ChainExcDemo
{
static void demoproc()
{
// create an exception
NullPointerException e = new NullPointerException("top layer");
// add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
// display top level exception
System.out.println("Caught: " + e);
// display cause exception
System.out.println("Original cause: " +e.getCause());
}
}
}
Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException: cause
Multi-catch Features
 The multi-catch feature allows two or more exceptions to be caught
by the same catch clause.
 It is not uncommon for two or more exception handlers to use the
same code sequence even though they respond to different
exceptions.
 Instead of having to catch each exception type individually, you can
use a single catch clause to handle all of the exceptions without
code duplication.
 To use a multi-catch, separate each exception type in the catch
clause with the OR operator.
 Each multi-catch parameter is implicitly final. (You can explicitly
specify final, if desired, but it is not necessary.)
 Because each multi-catch parameter is implicitly final, it can’t be
assigned a new value.
class MultiCatch
{
public static void main(String args[])
{
int a=10, b=0;
int vals[] = { 1, 2, 3 };
try
{
// generates an ArithmeticException
int result = a / b;
// generates an ArrayIndexOutOfBoundsException
vals[10] = 19;
// This catch clause catches both exceptions.
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception caught: " + e);
}
System.out.println("After multi-catch.");
}
}
Exception caught: java.lang.ArithmeticException: / by zero
After multi-catch.
1. Byte Streams
 InputStream
 OutputStream
 FileInputStream
 FileOutputStream
2. Character Streams
 Reader
 Writer
 FileReader
 FileWriter
STREAM CLASSES
Overview of I/O Streams
 An I/O Stream represents an input source or an output destination.
 A stream can represent many different kinds of sources and
destinations, including disk files, devices, other programs, and
memory arrays.
 Streams support many different kinds of data, including simple
bytes, primitive data types, localized characters, and objects.
 Some streams simply pass on data; others manipulate and
transform the data in useful ways.
 No matter how they work internally, all streams present the same
simple model to programs that use them: A stream is a sequence of
data.
 A program uses an input stream to read data from a source, one
item at a time:
 A program uses an output stream to write data to a destination, one
item at time:
What is a Stream?
 Abstraction that consumes or produces information
 Linked to source and destination
 Implemented within class hierarchies defined in java.io.package
 An input stream acts as a source of data
 An output stream acts as a destination of data
Different Types of I/O Streams
Byte Streams:
 They provide a convenient means for handling input and output of
bytes.
 Programs use byte streams to perform input and output of 8-bit
bytes.
 All byte stream classes descend from InputStream and
OutputStream class.
Character Streams:
 They provide a convenient means for handling input and output of
characters.
 They use Unicode and therefore, can be internationalized.
Buffered 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.
Data Streams:
 Data streams support binary I/O of primitive data type values (Boolean,
char, byte, short, int, long, float, and double) as well as String values.
Object Streams:
 Just as data streams support I/O of primitive data types, object streams
support I/O of objects.
Scanning and Formatting:
 It allows a program to read and write formatted text.
The Predefined Streams
 The java.lang.System class encapsulates several aspects of the run-
time environment.
 Contains three predefined stream variables: in,out, and err.
 These fields are declared as public and static within System.
 System.out: refers to the standard output stream
 System.err: refers to standard error stream
 System.in: refers to standard input
 out and err are objects of type PrintStream class and in is an object
of the InputStream class.
Streams Classes
 Java’s stream-based I/O is built upon four abstract classes:
InputStream, OutputStream, Reader, and Writer.
 InputStream and OutputStream are designed for byte streams.
Reader and Writer are designed for character streams.
 The byte stream classes and the character stream classes form
separate hierarchies.
 In general, you should use the character stream classes when
working with characters or strings and use the byte stream classes
when working with bytes or other binary objects.
1. Byte Streams
 The byte stream classes provide a rich environment for handling
byte-oriented I/O.
 A byte stream can be used with any type of object, including binary
data.
 This versatility makes byte streams important to many types of
programs.
InputStream
 InputStream is an abstract class that defines Java’s model of
streaming byte input.
 It implements the AutoCloseable and Closeable interfaces.
 Most of the methods in this class will throw an IOException when
an I/O error occurs. (The exceptions are mark( ) and
markSupported( ).)
 The methods in InputStream is shown in the table
OutputStream
 OutputStream is an abstract class that defines streaming byte
output.
 It implements the AutoCloseable, Closeable, and Flushable
interfaces.
 Most of the methods defined by this class return void and throw an
IOException in the case of I/O errors.
 The methods in OutputStream is shown in the table.
FileInputStream
 The FileInputStream class creates an InputStream that you can use
to read bytes from a file.
 Two commonly used constructors are shown here:
 FileInputStream(String filePath)
 FileInputStream(File fileObj)
 Either can throw a FileNotFoundException. Here, filePath is the full
path name of a file, and fileObj is a File object that describes the file.
 The FileInputStream class of the java.io package can be used to read
data (in bytes) from files.
 It extends the InputStream abstract class.
Create a FileInputStream
 In order to create a file input stream, we must import the
java.io.FileInputStream package first.
 Once we import the package, here is how we can create a file input
stream in Java.
1. Using the path to file
FileInputStream input = new FileInputStream(stringPath);
Here, we have created an input stream that will be linked to the file
specified by the path.
2. Using an object of the file
FileInputStream input = new FileInputStream(File fileObject);
Here, we have created an input stream that will be linked to the file
specified by fileObject.
Methods of FileInputStream
 read() - reads a single byte from the file
 read(byte[] array) - reads the bytes from the file and stores in the
specified array
 read(byte[] array, int start, int length) - reads the number of bytes
equal to length from the file and stores in the specified array
starting from the position start
import java.io.*;
public class FIS
{
public static void main(String args[])
{
try
{
FileInputStream input = new FileInputStream("Sample.txt");
System.out.println("Data in the file: ");
// Reads the first byte
int i = input.read();
while(i != -1)
{
System.out.print((char)i);
// Reads next byte from the file
i = input.read();
}
input.close();
}
catch(IOException e)
{
System.out.println("Error:" +e);
}
}
}
Data in the file:
Hello World
available() Method
 To get the number of available bytes, we can use the available() method.
import java.io.*;
public class AvailableExample
{
public static void main(String args[])
{
try
{
FileInputStream input = new FileInputStream("Sample.txt");
// Returns the number of available bytes
System.out.println("Available bytes at the beginning: " +
input.available());
// Reads 2 bytes from the file
input.read();
input.read();
// Returns the number of available bytes
System.out.println("Available bytes at the end: " + input.available());
input.close();
}
catch (Exception e)
{
System.out.println("Error:" +e);
}
}
}
Available bytes at the beginning: 11
Available bytes at the end: 9
skip() Method
 To discard and skip the specified number of bytes, we can use the skip()
method.
import java.io.*;
public class SkipExample
{
public static void main(String args[])
{
try
{
FileInputStream input = new FileInputStream("Sample.txt");
// Skips the 2 bytes
input.skip(2);
System.out.println("Input stream after skipping 2 bytes:");
// Reads the first byte
int i = input.read();
while (i != -1)
{
System.out.print((char) i);
// Reads next byte from the file
i = input.read();
}
input.close();
}
catch (Exception e)
{
System.out.println("Error:" +e);
}
}
}
Input stream after skipping 2 bytes:
llo World
FileOutputStream
 FileOutputStream creates an OutputStream that you can use to
write bytes to a file.
 It implements the AutoCloseable, Closeable, and Flushable
interfaces.
 Four of its constructors are shown here:
 FileOutputStream(String filePath)
 FileOutputStream(File fileObj)
 FileOutputStream(String filePath, boolean append)
 FileOutputStream(File fileObj, boolean append)
 They can throw a FileNotFoundException.
 Here, filePath is the full path name of a file, and fileObj is a File
object that describes the file.
 If append is true, the file is opened in append mode.
 Creation of a FileOutputStream is not dependent on the file already
existing.
 FileOutputStream will create the file before opening it for output
when you create the object.
 In the case where you attempt to open a read-only file, an exception
will be thrown.
 The FileOutputStream class of the java.io package can be used to
write data (in bytes) to the files.
 It extends the OutputStream abstract class.
Create a FileOutputStream
 In order to create a file output stream, we must import the
java.io.FileOutputStream package first.
 Once we import the package, here is how we can create a file
output stream in Java.
1. Using the path to file
// Including the boolean parameter
FileOutputStream output = new FileOutputStream(String path,
boolean value);
// Not including the boolean parameter
FileOutputStream output = new FileOutputStream(String path);
 Here, we have created an output stream that will be linked to the
file specified by the path.
 Also, value is an optional boolean parameter.
 If it is set to true, the new data will be appended to the end of the
existing data in the file.
 Otherwise, the new data overwrites the existing data in the file.
2. Using an object of the file
FileOutputStream output = new FileOutputStream(File fileObject);
Here, we have created an output stream that will be linked to the file
specified by fileObject.
Methods of FileOutputStream
write() - writes the single byte to the file output stream
write(byte[] array) - writes the bytes from the specified array to the
output stream
write(byte[] array, int start, int length) - writes the number of bytes
equal to length to the output stream from an array starting from the
position start
import java.io.*;
public class FOS
{
public static void main(String[] args)
{
String data = "Output File";
try
{
FileOutputStream output = new FileOutputStream("outfile.txt");
byte[] b = data.getBytes();
// Writes byte to the file
output.write(b);
output.close();
}
catch(Exception e)
{
System.out.println("Error:" +e);
}
}
}
outfile.txt
Output File
flush() Method
 To clear the output stream, we can use the flush() method. This method forces
the output stream to write all data to the destination.
import java.io.*;
public class FlushExample
{
public static void main(String[] args) throws IOException
{
FileOutputStream out = null;
String data = "Printed by flush method";
try
{
out = new FileOutputStream("flush.txt");
// Using write() method
out.write(data.getBytes());
// Using the flush() method
out.flush();
out.close();
}
catch(Exception e)
{
System.out.println("Error:" +e);
}
}
}
flush.txt
Printed by flush method
ByteArrayInputStream
 The ByteArrayInputStream class of the java.io package can be used
to read an array of input data (in bytes).
 It extends the InputStream abstract class.
Create a ByteArrayInputStream
 In order to create a byte array input stream, we must import the
java.io.ByteArrayInputStream package first.
// Creates a ByteArrayInputStream that reads entire array
ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr);
// Creates a ByteArrayInputStream that reads a portion of array
ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr,
int start, int length);
import java.io.ByteArrayInputStream;
public class ByteArrayInputExample
{
public static void main(String[] args)
{
// Creates an array of byte
byte[] array = {1, 2, 3, 4};
//byte[] array ={'A','B','C'};
try
{
ByteArrayInputStream input = new ByteArrayInputStream(array);
System.out.print("The bytes read from the input stream: ");
for(int i= 0; i < array.length; i++)
{
// Reads the bytes
int data = input.read();
System.out.print(data + ", ");
//System.out.print((char)data + ", ");
}
input.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
The bytes read from the input stream: 1, 2, 3, 4,
ByteArrayOutputStream
 The ByteArrayOutputStream class of the java.io package can be
used to write an array of output data (in bytes).
 It extends the OutputStream abstract class.
 ByteArrayOutputStream maintains an internal array of bytes to
store the data.
Create a ByteArrayOutputStream
 In order to create a byte array output stream, we must import the
java.io.ByteArrayOutputStream package first.
// Creates a ByteArrayOutputStream with default size
ByteArrayOutputStream out = new ByteArrayOutputStream();
 Here, we have created an output stream that will write data to an
array of bytes with default size 32 bytes. However, we can change
the default size of the array.
// Creating a ByteArrayOutputStream with specified size
ByteArrayOutputStream out = new ByteArrayOutputStream(int size);
 The size specifies the length of the array.
Access Data from ByteArrayOutputStream
toByteArray() - returns the array present inside the output stream
toString() - returns the entire data of the output stream in string form
import java.io.ByteArrayOutputStream;
class ByteArrayOutputExample
{
public static void main(String[] args)
{
String data = "This is data.";
try
{
// Creates an output stream
ByteArrayOutputStream output = new ByteArrayOutputStream();
// Writes data to the output stream
output.write(data.getBytes());
// Returns an array of bytes
byte[] byteData = output.toByteArray();
System.out.print("Data using toByteArray(): ");
for(int i=0; i<byteData.length; i++)
{
System.out.print((char)byteData[i]);
}
// Returns a string
String stringData = output.toString();
System.out.println("nData using toString(): " + stringData);
output.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
Data using toByteArray(): This is data.
Data using toString(): This is data.
ObjectInputStream
 The ObjectInputStream class of the java.io package can be used to
read objects that were previously written by ObjectOutputStream.
 It extends the InputStream abstract class.
Working of ObjectInputStream
 The ObjectInputStream is mainly used to read data written by the
ObjectOutputStream.
 Basically, the ObjectOutputStream converts Java objects into
corresponding streams. This is known as serialization. Those
converted streams can be stored in files or transferred through
networks.
 Now, if we need to read those objects, we will use the
ObjectInputStream that will convert the streams back to
corresponding objects. This is known as deserialization.
Create an ObjectInputStream
 In order to create an object input stream, we must import the
java.io.ObjectInputStream package first.
// Creates a file input stream linked with the specified file
FileInputStream fileStream = new FileInputStream(String file);
// Creates an object input stream using the file input stream
ObjectInputStream objStream = new ObjectInputStream(fileStream);
 An object input stream named objStream is created that is linked
with the file input stream named fileStream.
 Now, the objStream can be used to read objects from the file.
Methods of ObjectInputStream
 The ObjectInputStream class provides implementations of different
methods present in the InputStream class.
read() Method
read() - reads a byte of data from the input stream
readBoolean() - reads data in boolean form
readChar() - reads data in character form
readInt() - reads data in integer form
readObject() - reads the object from the input stream
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
class ObjectInputExample
{
public static void main(String[] args)
{
int data1 = 200;
String data2 = "Two Hundred";
try
{
FileOutputStream file = new FileOutputStream("Objectinfile.txt");
ObjectOutputStream output = new ObjectOutputStream(file);
// Writing to the file using ObjectOutputStream
output.writeInt(data1);
output.writeObject(data2);
FileInputStream fileStream = new FileInputStream("Objectinfile.txt");
// Creating an object input stream
ObjectInputStream objStream = new ObjectInputStream(fileStream);
//Using the readInt() method
System.out.println("Integer data :" + objStream.readInt());
// Using the readObject() method
System.out.println("String data: " + objStream.readObject());
output.close();
objStream.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
Integer data :200
String data: Two Hundred
ObjectOutputStream
 The ObjectOutputStream class of the java.io package can be used to
write objects that can be read by ObjectInputStream.
 It extends the OutputStream abstract class.
Working of ObjectOutputStream
 Basically, the ObjectOutputStream encodes Java objects using the
class name and object values. And, hence generates corresponding
streams. This process is known as serialization.
 Those converted streams can be stored in files and can be
transferred among networks.
 The ObjectOutputStream class only writes those objects that
implement the Serializable interface. This is because objects need to
be serialized while writing to the stream.
Create an ObjectOutputStream
 In order to create an object output stream, we must import the
java.io.ObjectOutputStream package first.
// Creates a FileOutputStream where objects from
ObjectOutputStream are written
FileOutputStream fileStream = new FileOutputStream(String file);
// Creates the ObjectOutputStream
ObjectOutputStream objStream = new ObjectOutputStream(fileStream);
 An object output stream named objStream is created which is linked
with the file output stream named fileStream.
Methods of ObjectOutputStream
 The ObjectOutputStream class provides implementations for
different methods present in the OutputStream class.
write() Method
write() - writes a byte of data to the output stream
writeBoolean() - writes data in boolean form
writeChar() - writes data in character form
writeInt() - writes data in integer form
writeObject() - writes object to the output stream
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
class ObjectOutputExample
{
public static void main(String[] args)
{
int data1 = 300;
String data2 = "Three Hundred";
try
{
FileOutputStream file = new FileOutputStream("ObjectOutfile.txt");
// Creates an ObjectOutputStream
ObjectOutputStream output = new ObjectOutputStream(file);
// writes objects to output stream
output.writeInt(data1);
output.writeObject(data2);
// Reads data using the ObjectInputStream
FileInputStream fileStream = new FileInputStream("ObjectOutfile.txt");
ObjectInputStream objStream = new ObjectInputStream(fileStream);
System.out.println("Integer data :" + objStream.readInt());
System.out.println("String data: " + objStream.readObject());
output.close();
objStream.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
Integer data :300
String data: Three Hundred
BufferedInputStream
 The BufferedInputStream class of the java.io package is used with
other input streams to read the data (in bytes) more efficiently.
 It extends the InputStream abstract class
Working of BufferedInputStream
 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.
Create a BufferedInputStream
 In order to create a BufferedInputStream, we must import the
java.io.BufferedInputStream package first.
// Creates a FileInputStream
FileInputStream file = new FileInputStream(String path);
// Creates a BufferedInputStream
BufferedInputStream buffer = new BufferInputStream(file);
 A BufferdInputStream named buffer with the FileInputStream
named file.
 Here, the internal buffer has the default size of 8192 bytes. However,
we can specify the size of the internal buffer as well.
// Creates a BufferedInputStream with specified size internal buffer
BufferedInputStream buffer = new BufferInputStream(file, int size);
 The buffer will help to read bytes from the files more quickly.
Methods of BufferedInputStream
 The BufferedInputStream class provides implementations for
different methods present in the InputStream class.
read() Method
read() - reads a single byte from the input stream
read(byte[] arr) - reads bytes from the stream and stores in the
specified array
read(byte[] arr, int start, int length) - reads the number of bytes equal
to the length from the stream and stores in the specified array starting
from the position start
import java.io.BufferedInputStream;
import java.io.FileInputStream;
class BufferedInputExample
{
public static void main(String[] args)
{
try
{
// Creates a FileInputStream
FileInputStream file = new FileInputStream("BufIn.txt");
// Creates a BufferedInputStream
BufferedInputStream input = new BufferedInputStream(file);
// Reads first byte from file
int i = input .read();
while (i != -1)
{
System.out.print((char) i);
// Reads next byte from the file
i = input.read();
}
input.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
This line is printed from BufIn File
PrintStream
 The PrintStream class of the java.io package can be used to write
output data in commonly readable form (text) instead of bytes.
 It extends the abstract class OutputStream.
Create a PrintStream
 In order to create a PrintStream, we must import the
java.io.PrintStream package first.
1. Using other output streams
// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream(String file);
// Creates a PrintStream
PrintStream output = new PrintStream(file, autoFlush);
 Here, we have created a print stream that will write formatted data
to the file represented by FileOutputStream
 the autoFlush is an optional boolean parameter that specifies
whether to perform auto flushing or not.
2. Using filename
// Creates a PrintStream
PrintStream output = new PrintStream(String file, boolean autoFlush);
 We have created a print stream that will write formatted data to the
specified file.
 autoFlush is an optional boolean parameter that specifies whether to
perform autoflush or not.
Methods of PrintStream
The PrintStream class provides various methods that allow us to print
data to the output.
print() Method
print() - prints the specified data to the output stream
println() - prints the data to the output stream along with a new line
character at the end
Example: print() method with System class
class Main
{
public static void main(String[] args)
{
String data = "Hello World.";
System.out.print(data);
}
}
Hello World.
Example: print() method with System class
class Main
{
public static void main(String[] args)
{
String data = "Hello World.";
System.out.print(data);
}
}
Hello World.
Example: print() method with PrintStream class
import java.io.PrintStream;
class Main
{
public static void main(String[] args)
{
String data = "This is a text written to Print file.";
try
{
PrintStream output = new PrintStream("Print.txt");
output.print(data);
output.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
This is a text written to Print file.
2. Character Streams
 Reader
 Writer
 FileReader
 FileWriter
STREAM CLASSES
Reader
 The Reader class of the java.io package is an abstract superclass that
represents a stream of characters.
 Since Reader is an abstract class, it is not useful by itself. However,
its subclasses can be used to read data.
Subclasses of Reader
In order to use the functionality of Reader, we can use its subclasses.
Some of them are:
 BufferedReader
 InputStreamReader
 FileReader
 StringReader
Create a Reader
 In order to create a Reader, we must import the java.io.Reader package
first.
// Creates a Reader
Reader input = new FileReader();
Methods of Reader
ready() - checks if the reader is ready to be read
read(char[] array) - reads the characters from the stream and stores in the
specified array
read(char[] array, int start, int length) - reads the number of characters equal
to length from the stream and stores in the specified array starting from the
start
mark() - marks the position in the stream up to which data has been read
reset() - returns the control to the point in the stream where the mark is set
skip() - discards the specified number of characters from the stream
import java.io.Reader;
import java.io.FileReader;
class ReaderExample
{
public static void main(String[] args)
{
// Creates an array of character
char[] array = new char[100];
try
{
// Creates a reader using the FileReader
Reader input = new FileReader("ReaderInput.txt");
// Checks if reader is ready
System.out.println("Is there data in the stream? " + input.ready());
// Reads characters
input.read(array);
System.out.println("Data in the stream:");
System.out.println(array);
// Closes the reader
input.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
This line is printed from the ReaderInput File.
Writer
 The Writer class of the java.io package is an abstract superclass that
represents a stream of characters.
Subclasses of Writer
 In order to use the functionality of the Writer, we can use its
subclasses. Some of them are:
 BufferedWriter
 OutputStreamWriter
 FileWriter
 StringWriter
Create a Writer
 In order to create a Writer, we must import the java.io.Writer
package first.
// Creates a Writer
Writer output = new FileWriter();
 Here, we have created a writer named output using the FileWriter
class. It is because the Writer is an abstract class. Hence we cannot
create an object of Writer.
The Writer class provides different methods that are implemented by
its subclasses. Here are some of the methods:
write(char[] array) - writes the characters from the specified array to
the output stream
write(String data) - writes the specified string to the writer
append(char c) - inserts the specified character to the current writer
flush() - forces to write all the data present in the writer to the
corresponding destination
close() - closes the writer
import java.io.FileWriter;
import java.io.Writer;
public class WriterExample
{
public static void main(String args[])
{
String data = "This line is printed from FileWriterOut File";
try
{
// Creates a Writer using FileWriter
Writer output = new FileWriter("FileWriterOut.txt");
// Writes string to the file
output.write(data);
// Closes the writer
output.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
InputStreamReader
 The InputStreamReader class of the java.io package can be used to
convert data in bytes into data in characters.
 It extends the abstract class Reader.
 The InputStreamReader class works with other input streams. It is
also known as a bridge between byte streams and character streams.
 This is because the InputStreamReader reads bytes from the input
stream as characters.
 For example, some characters required 2 bytes to be stored in the
storage.
 To read such data we can use the input stream reader that reads the
2 bytes together and converts into the corresponding character.
Create an InputStreamReader
 In order to create an InputStreamReader, we must import the
java.io.InputStreamReader package first.
// Creates an InputStream
FileInputStream file = new FileInputStream(String path);
// Creates an InputStreamReader
InputStreamReader input = new InputStreamReader(file);
Methods of InputStreamReader
 The InputStreamReader class provides implementations for different
methods present in the Reader class.
read() Method
read() - reads a single character from the reader
read(char[] array) - reads the characters from the reader and stores in
the specified array
read(char[] array, int start, int length) - reads the number of characters
equal to length from the reader and stores in the specified array
starting from the start
import java.io.InputStreamReader;
import java.io.FileInputStream;
class IPStreamReaderEx
{
public static void main(String[] args)
{
// Creates an array of character
char[] array = new char[100];
try
{
// Creates a FileInputStream
FileInputStream file = new FileInputStream("IPStreamReaderFile.txt");
// Creates an InputStreamReader
InputStreamReader input = new InputStreamReader(file);
// Reads characters from the file
input.read(array);
System.out.println("Data in the stream:");
System.out.println(array);
// Closes the reader
input.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
Data in the stream:
This line is printed from IPStreamReaderFile
OutputStreamWriter
 The OutputStreamWriter class of the java.io package can be used to
convert data in character form into data in bytes form.
 It extends the abstract class Writer.
 The OutputStreamWriter class works with other output streams. It is
also known as a bridge between byte streams and character streams.
 This is because the OutputStreamWriter converts its characters into
bytes.
 For example, some characters require 2 bytes to be stored in the
storage.
 To write such data we can use the output stream writer that converts
the character into corresponding bytes and stores the bytes together.
Create an OutputStreamWriter
 In order to create an OutputStreamWriter, we must import the
java.io.OutputStreamWriter package first.
// Creates an OutputStream
FileOutputStream file = new FileOutputStream(String path);
// Creates an OutputStreamWriter
OutputStreamWriter output = new OutputStreamWriter(file);
write() Method
write() - writes a single character to the writer
write(char[] array) - writes the characters from the specified array to
the writer
write(String data) - writes the specified string to the writer
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
public class OPStreamWriterEx
{
public static void main(String args[])
{
String data = "This line is written to OPStreamWriterFile";
try
{
// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream("OPStreamWriterFile.txt");
// Creates an OutputStreamWriter
OutputStreamWriter output = new OutputStreamWriter(file);
// Writes string to the file
output.write(data);
// Closes the writer
output.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
Session 27
FileReader
 The FileReader class of the java.io package can be used to read data (in
characters) from files.
 It extends the InputSreamReader class.
Create a FileReader
 In order to create a file reader, we must import the java.io.FileReader
package first.
1. Using the name of the file
FileReader input = new FileReader(String name);
2. Using an object of the file
FileReader input = new FileReader(File fileObj);
read() Method
read() - reads a single character from the reader
read(char[] array) - reads the characters from the reader and stores in the
specified array
read(char[] array, int start, int length) - reads the number of characters
equal to length from the reader and stores in the specified array starting
from the position start
import java.io.FileReader;
class FileReaderEx
{
public static void main(String[] args)
{
// Creates an array of character
char[] array = new char[100];
try
{
// Creates a reader using the FileReader
FileReader input = new FileReader("FreaderFile.txt");
// Reads characters
input.read(array);
System.out.println("Data in the file: ");
System.out.println(array);
// Closes the reader
input.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
Data in the file:
This line is written in File Reader
FileWriter
 The FileWriter class of the java.io package can be used to write data
(in characters) to files.
 It extends the OutputStreamWriter class.
Create a FileWriter
 In order to create a file writer, we must import the Java.io.FileWriter
package first.
1. Using the name of the file
FileWriter output = new FileWriter(String name);
2. Using an object of the file
FileWriter input = new FileWriter(File fileObj);
Methods of FileWriter
The FileWriter class provides implementations for different methods
present in the Writer class.
write() Method
write() - writes a single character to the writer
write(char[] array) - writes the characters from the specified array to the
writer
write(String data) - writes the specified string to the writer
import java.io.FileWriter;
public class FileWriterEx
{
public static void main(String args[])
{
String data = "This line is written to FWriter File";
try
{
// Creates a FileWriter
FileWriter output = new FileWriter("FWriterFile.txt");
// Writes the string to the file
output.write(data);
// Closes the writer
output.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
BufferedReader
 The BufferedReader class of the java.io package can be used with
other readers to read data (in characters) more efficiently.
 It extends the abstract class Reader.
Working of BufferedReader
 The BufferedReader maintains an internal buffer of 8192 characters.
 During the read operation in BufferedReader, a chunk of characters is
read from the disk and stored in the internal buffer. And from the
internal buffer characters are read individually.
 Hence, the number of communication to the disk is reduced. This is
why reading characters is faster using BufferedReader.
Create a BufferedReader
 In order to create a BufferedReader, we must import the
java.io.BuferedReader package first.
// Creates a FileReader
FileReader file = new FileReader(String file);
// Creates a BufferedReader
BufferedReader buffer = new BufferedReader(file);
// Creates a BufferdReader with specified size internal buffer
BufferedReader buffer = new BufferedReader(file, int size);
Methods of BufferedReader
 The BufferedReader class provides implementations for different
methods present in Reader.
read() Method
read() - reads a single character from the internal buffer of the reader
read(char[] array) - reads the characters from the reader and stores in the
specified array
read(char[] array, int start, int length) - reads the number of characters
equal to length from the reader and stores in the specified array starting
from the position start
import java.io.FileReader;
import java.io.BufferedReader;
class BufferReaderEx
{
public static void main(String[] args)
{
// Creates an array of character
char[] array = new char[100];
try
{
// Creates a FileReader
FileReader file = new FileReader("BufferReaderFile.txt");
// Creates a BufferedReader
BufferedReader input = new BufferedReader(file);
// Reads characters
input.read(array);
System.out.println("Data in the file: ");
System.out.println(array);
// Closes the reader
input.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
Data in the file:
This line is printed from BufferReaderFile
BufferedWriter
 The BufferedWriter class of the java.io package can be used with other
writers to write data (in characters) more efficiently.
 It extends the abstract class Writer.
Working of BufferedWriter
 The BufferedWriter maintains an internal buffer of 8192 characters.
 During the write operation, the characters are written to the internal
buffer instead of the disk. Once the buffer is filled or the writer is
closed, the whole characters in the buffer are written to the disk.
 Hence, the number of communication to the disk is reduced. This is
why writing characters is faster using BufferedWriter.
Create a BufferedWriter
 In order to create a BufferedWriter, we must import the
java.io.BufferedWriter package first.
// Creates a FileWriter
FileWriter file = new FileWriter(String name);
// Creates a BufferedWriter
BufferedWriter buffer = new BufferedWriter(file);
// Creates a BufferedWriter with specified size internal buffer
BufferedWriter buffer = new BufferedWriter(file, int size);
Methods of BufferedWriter
 The BufferedWriter class provides implementations for different
methods present in Writer.
write() Method
write() - writes a single character to the internal buffer of the writer
write(char[] array) - writes the characters from the specified array to the
writer
write(String data) - writes the specified string to the writer
import java.io.FileWriter;
import java.io.BufferedWriter;
public class BufferedWriterEx
{
public static void main(String args[])
{
String data = "This line is written to BufferedWriterFile";
try
{
// Creates a FileWriter
FileWriter file = new FileWriter("BufferedWriterFile.txt");
// Creates a BufferedWriter
BufferedWriter output = new BufferedWriter(file);
// Writes the string to the file
output.write(data);
// Closes the writer
output.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
This line is written to BufferedWriterFile
StringReader
 The StringReader class of the java.io package can be used to read data
(in characters) from strings.
 It extends the abstract class Reader.
 In StringReader, the specified string acts as a source from where
characters are read individually.
Create a StringReader
 In order to create a StringReader, we must import the
java.io.StringReader package first.
// Creates a StringReader
StringReader input = new StringReader(String data);
Methods of StringReader
 The StringReader class provides implementations for different
methods present in the Reader class.
Methods of StringReader
 The StringReader class provides implementations for different
methods present in the Reader class.
read() Method
read() - reads a single character from the string reader
read(char[] array) - reads the characters from the reader and stores in the
specified array
read(char[] array, int start, int length) - reads the number of characters
equal to length from the reader and stores in the specified array starting
from the position start
import java.io.StringReader;
public class StringReaderEX
{
public static void main(String[] args)
{
String data = "This is the text read from StringReader.";
// Create a character array
char[] array = new char[100];
try
{
// Create a StringReader
StringReader input = new StringReader(data);
//Use the read method
input.read(array);
System.out.println("Data read from the string:");
System.out.println(array);
input.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
Data read from the string:
This is the text read from StringReader.
StringWriter
 The StringWriter class of the java.io package can be used to write data (in
characters) to the string buffer.
 It extends the abstract class Writer.
Create a StringWriter
 In order to create a StringWriter, we must import the java.io.StringWriter
package first.
// Creates a StringWriter
StringWriter output = new StringWriter();
// Creates a StringWriter with specified string buffer capacity
StringWriter output = new StringWriter(int size);
Methods of StringWriter
write() Method
write() - writes a single character to the string writer
write(char[] array) - writes the characters from the specified array to the writer
write(String data) - writes the specified string to the writer
import java.io.StringWriter;
public class StringWriterEx
{
public static void main(String[] args)
{
String data = "This is the text in the string.";
try
{
// Create a StringWriter with default string buffer capacity
StringWriter output = new StringWriter();
// Writes data to the string buffer
output.write(data);
// Prints the string writer
System.out.println("Data in the StringWriter: " + output);
output.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
Data in the StringWriter: This is the text in the string.
Access Data from StringBuffer
getBuffer() - returns the data present in the string buffer
toString() - returns the data present in the string buffer as a string
import java.io.StringWriter;
public class StringWriterBufferEx
{
public static void main(String[] args)
{
String data = "This is the original data";
try
{
// Create a StringWriter with default string buffer capacity
StringWriter output = new StringWriter();
// Writes data to the string buffer
output.write(data);
// Returns the string buffer
StringBuffer stringBuffer = output.getBuffer();
System.out.println("StringBuffer: " + stringBuffer);
// Returns the string buffer in string form
String string = output.toString();
System.out.println("String: " + string);
output.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
StringBuffer: This is the original data
String: This is the original data
PrintWriter
 The PrintWriter class of the java.io package can be used to write output
data in a commonly readable form (text).
 It extends the abstract class Writer.
Working of PrintWriter
 Unlike other writers, PrintWriter converts the primitive data (int, float,
char, etc.) into the text format. It then writes that formatted data to the
writer.
 Also, the PrintWriter class does not throw any input/output exception.
Instead, we need to use the checkError() method to find any error in it.
 The PrintWriter class also has a feature of auto flushing. This means it
forces the writer to write all data to the destination if one of the println() or
printf() methods is called.
Create a PrintWriter
 In order to create a print writer, we must import the java.io.PrintWriter
package first.
1. Using other writers
// Creates a FileWriter
FileWriter file = new FileWriter("output.txt");
// Creates a PrintWriter
PrintWriter output = new PrintWriter(file, autoFlush);
Here,
 we have created a print writer that will write data to the file represented by
the FileWriter
 autoFlush is an optional parameter that specifies whether to perform auto
flushing or not
2. Using other output streams
// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream("output.txt");
// Creates a PrintWriter
PrintWriter output = new PrintWriter(file, autoFlush);
Here,
 We have created a print writer that will write data to the file represented by
the FileOutputStream
 The autoFlush is an optional parameter that specifies whether to perform
auto flushing or not
3. Using filename
// Creates a PrintWriter
PrintWriter output = new PrintWriter(String file, boolean autoFlush);
Here,
 We have created a print writer that will write data to the specified file
 The autoFlush is an optional boolean parameter that specifies whether to
perform auto flushing or nor
 In all the above cases, the PrintWriter writes data to the file using some
default character encoding. However, we can specify the character
encoding (UTF8 or UTF16) as well.
Methods of PrintWriter
 The PrintWriter class provides various methods that allow us to print data
to the output.
print() Method
print() - prints the specified data to the writer
println() - prints the data to the writer along with a new line character at the
end
import java.io.PrintWriter;
class PrintWriterEx
{
public static void main(String[] args)
{
String data = "This is a text inside the file.";
try
{
PrintWriter output = new PrintWriter("output.txt");
output.print(data);
output.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
1. The Java Thread Model
2. Creating a Thread
 Implementing Runnable
 Extending Thread
3. Creating Multiple Threads
4. Thread Priorities
5. Synchronization
 Using Synchronized methods
 The synchronized Statement
MULTITHREADED PROGRAMMING
Multithreaded Programming
 Java provides built-in support for multithreaded programming. A
multithreaded program contains two or more parts that can run
concurrently.
 Each part of such a program is called a thread, and each thread
defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking.
 You are almost certainly acquainted with multitasking because it is
supported by virtually all modern operating systems. However,
there are two distinct types of multitasking: process-based and
thread-based.
 It is important to understand the difference between the two. For
many readers, process-based multitasking is the more familiar
form.
 A process is, in essence, a program that is executing. Thus, process-
based multitasking is the feature that allows your computer to run
two or more programs concurrently.
 For example, process-based multitasking enables you to run the
Java compiler while you are using a text editor or visiting a web
site.
 In process-based multitasking, a program is the smallest unit of
code that can be dispatched by the scheduler.
 In a thread-based multitasking environment, the thread is the
smallest unit of dispatchable code.
 This means that a single program can perform two or more tasks
simultaneously. For instance, a text editor can format text at the
same time that it is printing, as long as these two actions are being
performed by two separate threads.
 Thus, process-based multitasking deals with the “big picture,” and
thread-based multitasking handles the details.
 Multitasking threads require less overhead than multitasking
processes. Processes are heavyweight tasks that require their own
separate address spaces.
 Interprocess communication is expensive and limited. Context
switching from one process to another is also costly.
 Threads, on the other hand, are lighter weight. They share the same
address space and cooperatively share the same heavyweight
process.
 Interthread communication is inexpensive, and context switching
from one thread to the next is lower in cost.
 While Java programs make use of process-based multitasking
environments, process-based multitasking is not under Java’s
control. However, multithreaded multitasking is.
 Multithreading enables you to write efficient programs that make
maximum use of the processing power available in the system.
 One important way multithreading achieves this is by keeping idle
time to a minimum. This is especially important for the interactive,
networked environment in which Java operates because idle time is
common.
 For example, the transmission rate of data over a network is much
slower than the rate at which the computer can process it.
 Even local file system resources are read and written at a much
slower pace than they can be processed by the CPU. And, of course,
user input is much slower than the computer.
 In a single-threaded environment, your program has to wait for
each of these tasks to finish before it can proceed to the next one—
even though most of the time the program is idle, waiting for input.
 Multithreading helps you reduce this idle time because another
thread can run when one is waiting.
1. The Java Thread Model
 The Java run-time system depends on threads for many things, and
all the class libraries are designed with multithreading in mind.
 The value of a multithreaded environment is best understood in
contrast to its counterpart.
 Single-threaded systems use an approach called an event loop with
polling. In this model, a single thread of control runs in an infinite
loop, polling a single event queue to decide what to do next.
 Once this polling mechanism returns with, say, a signal that a
network file is ready to be read, then the event loop dispatches
control to the appropriate event handler.
 Until this event handler returns, nothing else can happen in the
program. This wastes CPU time.
 It can also result in one part of a program dominating the system
and preventing any other events from being processed.
 In general, in a single-threaded environment, when a thread blocks
(that is, suspends execution) because it is waiting for some
resource, the entire program stops running.
 The benefit of Java’s multithreading is that the main loop/polling
mechanism is eliminated.
 One thread can pause without stopping other parts of your
program. For example, the idle time created when a thread reads
data from a network or waits for user input can be utilized
elsewhere.
 Multithreading allows animation loops to sleep for a second
between each frame without causing the whole system to pause.
 When a thread blocks in a Java program, only the single thread that
is blocked pauses. All other threads continue to run.
 Threads exist in several states. Here is a general description. A
thread can be running.
 It can be ready to run as soon as it gets CPU time. A running thread
can be suspended, which temporarily halts its activity.
 A suspended thread can then be resumed, allowing it to pick up
where it left off. A thread can be blocked when waiting for a
resource.
 At any time, a thread can be terminated, which halts its execution
immediately. Once terminated, a thread cannot be resumed.
The Main Thread
 When a Java program starts up, one thread begins running
immediately.
 This is usually called the main thread of your program, because it is
the one that is executed when your program begins. The main thread
is important for two reasons:
 It is the thread from which other “child” threads will be spawned.
 Often, it must be the last thread to finish execution because it
performs various shutdown actions.
 Although the main thread is created automatically when your
program is started, it can be controlled through a Thread object.
 To do so, you must obtain a reference to it by calling the method
currentThread( ), which is a public static member of Thread. Its
general form is shown here:
static Thread currentThread( )
 This method returns a reference to the thread in which it is called.
Once you have a reference to the main thread, you can control it just
like any other thread.
class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try
{
for(int n = 6; n > 0; n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
}
}
Output:
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
6
5
4
3
2
1
 In this program, a reference to the current thread (the main thread, in
this case) is obtained by calling currentThread( ), and this reference is
stored in the local variable t.
 Next, the program displays information about the thread. The
program then calls setName( ) to change the internal name of the
thread.
 Information about the thread is then redisplayed. Next, a loop counts
down from five, pausing one second between each line.
 The pause is accomplished by the sleep( ) method. The argument to
sleep( ) specifies the delay period in milliseconds. Notice the try/catch
block around this loop.
 The sleep( ) method in Thread might throw an InterruptedException. This
would happen if some other thread wanted to interrupt this sleeping one.
 Notice the output produced when t is used as an argument to println( ).
This displays, in order: the name of the thread, its priority, and the name
of its group.
 By default, the name of the main thread is main. Its priority is 5, which is
the default value, and main is also the name of the group of threads to
which this thread belongs.
 A thread group is a data structure that controls the state of a collection of
threads as a whole.
 After the name of the thread is changed, t is again output. This time, the
new name of the thread is displayed.
 The sleep( ) method causes the thread from which it is called to
suspend execution for the specified period of milliseconds. Its general
form is shown here:
static void sleep(long milliseconds) throws InterruptedException
 The number of milliseconds to suspend is specified in milliseconds.
This method may throw an InterruptedException.
 The sleep( ) method has a second form, shown next, which allows
you to specify the period in terms of milliseconds and nanoseconds:
static void sleep(long milliseconds, int nanoseconds) throws InterruptedException
 This second form is useful only in environments that allow timing
periods as short as nanoseconds.
 The name of a thread can be set by using setName( ).
 The name of a thread can be obtained by calling getName( ) (but note
that this is not shown in the program).
 These methods are members of the Thread class and are declared like
this:
final void setName(String threadName)
final String getName( )
 Here, threadName specifies the name of the thread.
2. Creating a Thread
 A thread can be created by instantiating an object of type Thread.
 Java defines two ways in which this can be accomplished:
 Implement the Runnable interface.
 Extend the Thread class, itself.
Implementing Runnable
 The easiest way to create a thread is to create a class that implements
the Runnable interface.
 Runnable abstracts a unit of executable code. A thread can be
constructed on any object that implements Runnable.
 To implement Runnable, a class need only implement a single
method called run( ), which is declared like this:
public void run( )
 Inside run( ), the code is defined that constitutes the new thread.
 It is important to understand that run( ) can call other methods, use
other classes, and declare variables, just like the main thread can.
 The only difference is that run( ) establishes the entry point for
another, concurrent thread of execution within your program.
 This thread will end when run( ) returns.
 After you create a class that implements Runnable, you will
instantiate an object of type Thread from within that class.
 Thread defines several constructors. The one that we will use is
shown here:
Thread(Runnable threadOb, String threadName)
 In this constructor, threadOb is an instance of a class that implements
the Runnable interface.
 This defines where execution of the thread will begin. The name of
the new thread is specified by threadName.
 After the new thread is created, it will not start running until you call
its start( ) method, which is declared within Thread. In essence, start(
) executes a call to run( ).
 The start( ) method is shown here:
void start( )
class NewThread implements Runnable
{
Thread t;
NewThread()
{
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
// Start the thread
t.start();
}
// This is the entry point for the second thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class RunnableExample
{
public static void main(String args[ ] )
{
// create a new thread
new NewThread();
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Output:
Child thread: Thread[Demo Thread,5,main]
Child Thread: 5
Main Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
 Passing this as the first argument indicates that you want the new
thread to call the run( ) method on this object.
 Next, start( ) is called, which starts the thread of execution beginning
at the run( ) method.
 This causes the child thread’s for loop to begin.
 After calling start( ), NewThread’s constructor returns to main( ).
 When the main thread resumes, it enters its for loop. Both threads
continue running, sharing the CPU in singlecore systems, until their
loops finish.
Extending Thread
 The second way to create a thread is to create a new class that
extends Thread, and then to create an instance of that class.
 The extending class must override the run( ) method, which is the
entry point for the new thread.
 It must also call start( ) to begin execution of the new thread.
class NewThread extends Thread
{
NewThread()
{
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
// Start the thread
start();
}
// This is the entry point for the second thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread
{
public static void main(String args[])
{
// create a new thread
new NewThread();
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Output:
Child thread: Thread[Demo Thread,5,main]
Child Thread: 5
Main Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
 The child thread is created by instantiating an object of NewThread,
which is derived from Thread.
 Notice the call to super( ) inside NewThread. This invokes the
following form of the Thread constructor:
public Thread(String threadName)
 Here, threadName specifies the name of the thread
3. Creating Multiple Threads
 So far, only two threads : the main thread and one child thread
have been used.
 However, the program can spawn as many threads as it needs.
class NewThread implements Runnable
{
// name of thread
String name;
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
// Start the thread
t.start();
}
// This is the entry point for thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
// start threads
new NewThread("One");
new NewThread("Two");
new NewThread("Three");
try
{
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Three: 5
Two: 5
One: 4
Three: 4
Two: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Three exiting.
Two exiting.
Main thread exiting.
 Once started, all three child threads share the CPU.
 Notice the call to sleep(10000) in main( ).
 This causes the main thread to sleep for ten seconds and ensures that
it will finish last.
Using isAlive( ) and join( )
 Two ways exist to determine whether a thread has finished. First, you
can call isAlive( ) on the thread.
 This method is defined by Thread, and its general form is shown
here:
final boolean isAlive( )
 The isAlive( ) method returns true if the thread upon which it is
called is still running. It returns false otherwise.
 While isAlive( ) is occasionally useful, the method that you will more
commonly use to wait for a thread to finish is called join( ), shown
here:
final void join( ) throws InterruptedException
class NewThread implements Runnable
{
// name of thread
String name;
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
// Start the thread
t.start();
}
// This is the entry point for thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
// wait for threads to finish
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}
Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Two: 5
One: 5
Thread Two is alive: true
Three: 5
Thread Three is alive: true
Waiting for threads to finish.
Three: 4
Two: 4
One: 4
Three: 3
One: 3
Two: 3
Three: 2
One: 2
Two: 2
Three: 1
Two: 1
One: 1
Three exiting.
Two exiting.
One exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
4. Threads Priorities
 Thread priorities are used by the thread scheduler to decide when each
thread should be allowed to run.
 In theory, over a given period of time, higher-priority threads get more
CPU time than lower-priority threads.
 In practice, the amount of CPU time that a thread gets often depends on
several factors besides its priority. (For example, how an operating
system implements multitasking can affect the relative availability of
CPU time.)
 In theory, threads of equal priority should get equal access to the CPU.
But you need to be careful.
 To set a thread’s priority, use the setPriority( ) method, which is a
member of Thread. This is its general form:
final void setPriority(int level)
 Here, level specifies the new priority setting for the calling thread.
The value of level must be within the range MIN_PRIORITY and
MAX_PRIORITY. Currently, these values are 1 and 10, respectively.
To return a thread to default priority, specify NORM_PRIORITY,
which is currently 5.
 These priorities are defined as static final variables within Thread.
 You can obtain the current priority setting by calling the getPriority(
) method of Thread, shown here:
final int getPriority( )
public class ThreadPriorityEx extends Thread
{
public void run()
{
System.out.println("Thread Running... "+Thread.currentThread().getName());
}
public static void main(String args[])
{
ThreadPriorityEx t1=new ThreadPriorityEx();
ThreadPriorityEx t2=new ThreadPriorityEx();
ThreadPriorityEx t3=new ThreadPriorityEx();
ThreadPriorityEx t4=new ThreadPriorityEx();
ThreadPriorityEx t5=new ThreadPriorityEx();
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t4.setPriority(9);
System.out.println("Priority of thread t1 is: " + t1.getPriority()); //1
System.out.println("Priority of thread t2 is: " + t2.getPriority()); //5
System.out.println("Priority of thread t3 is: " + t3.getPriority()); //10
System.out.println("Priority of thread t4 is: " + t4.getPriority()); //9
try
{
t5.setPriority(11);
System.out.println("Priority of thread t5 is: " + t5.getPriority()); //11
}
catch (Exception e)
{
System.out.println("Illegal Arguement");
}
}
}
Output:
Thread Running... Thread-2
Thread Running... Thread-1
Thread Running... Thread-4
Thread Running... Thread-3
Thread Running... Thread-0
Priority of thread t1 is: 1
Priority of thread t2 is: 5
Priority of thread t3 is: 10
Priority of thread t4 is: 9
Illegal Arguement
5. Synchronization
 When two or more threads need access to a shared resource, they
need some way to ensure that the resource will be used by only one
thread at a time. The process by which this is achieved is called
synchronization.
 Key to synchronization is the concept of the monitor. A monitor is
an object that is used as a mutually exclusive lock. Only one thread
can own a monitor at a given time.
 When a thread acquires a lock, it is said to have entered the
monitor.
 All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor.
 These other threads are said to be waiting for the monitor. A thread
that owns a monitor can reenter the same monitor if it so desires.
Using Synchronized Methods
 Synchronization is easy in Java, because all objects have their own
implicit monitor associated with them.
 To enter an object’s monitor, just call a method that has been
modified with the synchronized keyword.
 While a thread is inside a synchronized method, all other threads
that try to call it (or any other synchronized method) on the same
instance have to wait.
 To exit the monitor and relinquish control of the object to the next
waiting thread, the owner of the monitor simply returns from the
synchronized method.
class Callme
{
void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run()
{
synchronized(target)
{
// synchronized block
target.call(msg);
}
}
}
class Synch1
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
Output:
[Hello]
[World]
[Synchronized]
The Synchronized Statement
The general form of the synchronized statement:
synchronized(objRef)
{
// statements to be synchronized
}
 Here, objRef is a reference to the object being synchronized.
 A synchronized block ensures that a call to a synchronized
method that is a member of objRef’s class occurs only after the
current thread has successfully entered objRef’s monitor.
References
1. Herbert Schildt, “Java The Complete Reference”, 9th Edition,
McGraw-Hill Education, New Delhi, 2017.
Thank You

More Related Content

What's hot

Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Asim Rais Siddiqui
 
Concept of c data types
Concept of c data typesConcept of c data types
Concept of c data typesManisha Keim
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.pptVarshini62
 
Top 20 c# interview Question and answers
Top 20 c# interview Question and answersTop 20 c# interview Question and answers
Top 20 c# interview Question and answersw3asp dotnet
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanKavita Ganesan
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with PythonMicroPyramid .
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptxSameerAhmed593310
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsGanesh Samarthyam
 

What's hot (20)

Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Concept of c data types
Concept of c data typesConcept of c data types
Concept of c data types
 
Java tokens
Java tokensJava tokens
Java tokens
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
 
Java interface
Java interfaceJava interface
Java interface
 
Top 20 c# interview Question and answers
Top 20 c# interview Question and answersTop 20 c# interview Question and answers
Top 20 c# interview Question and answers
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java operators
Java operatorsJava operators
Java operators
 

Similar to Exception handling, Stream Classes, Multithread Programming

Similar to Exception handling, Stream Classes, Multithread Programming (20)

MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java unit3
Java unit3Java unit3
Java unit3
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Chap12
Chap12Chap12
Chap12
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 

More from Prabu U

Computation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit LearnComputation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit LearnPrabu U
 
Concurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network ProgrammingConcurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network ProgrammingPrabu U
 
File Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with PandasFile Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with PandasPrabu U
 
Arrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsArrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsPrabu U
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and ObjectsPrabu U
 
Building XML Based Applications
Building XML Based ApplicationsBuilding XML Based Applications
Building XML Based ApplicationsPrabu U
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XMLPrabu U
 
WEB SERVICES
WEB SERVICESWEB SERVICES
WEB SERVICESPrabu U
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGPrabu U
 
Internet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side ProgrammingInternet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side ProgrammingPrabu U
 
Operation Management
Operation ManagementOperation Management
Operation ManagementPrabu U
 
Nature and Importance of Management
Nature and Importance of ManagementNature and Importance of Management
Nature and Importance of ManagementPrabu U
 
Replacement and Maintenance Analysis
Replacement and Maintenance AnalysisReplacement and Maintenance Analysis
Replacement and Maintenance AnalysisPrabu U
 
Elementary Economic Analysis
Elementary Economic AnalysisElementary Economic Analysis
Elementary Economic AnalysisPrabu U
 
Introduction to Engineering Economics
Introduction to Engineering EconomicsIntroduction to Engineering Economics
Introduction to Engineering EconomicsPrabu U
 
Files in C
Files in CFiles in C
Files in CPrabu U
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and PointersPrabu U
 
Decision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsDecision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsPrabu U
 
Problem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to CProblem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to CPrabu U
 

More from Prabu U (20)

Computation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit LearnComputation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit Learn
 
Concurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network ProgrammingConcurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network Programming
 
File Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with PandasFile Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with Pandas
 
Arrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsArrays with Numpy, Computer Graphics
Arrays with Numpy, Computer Graphics
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
Building XML Based Applications
Building XML Based ApplicationsBuilding XML Based Applications
Building XML Based Applications
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
WEB SERVICES
WEB SERVICESWEB SERVICES
WEB SERVICES
 
XML
XMLXML
XML
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 
Internet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side ProgrammingInternet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side Programming
 
Operation Management
Operation ManagementOperation Management
Operation Management
 
Nature and Importance of Management
Nature and Importance of ManagementNature and Importance of Management
Nature and Importance of Management
 
Replacement and Maintenance Analysis
Replacement and Maintenance AnalysisReplacement and Maintenance Analysis
Replacement and Maintenance Analysis
 
Elementary Economic Analysis
Elementary Economic AnalysisElementary Economic Analysis
Elementary Economic Analysis
 
Introduction to Engineering Economics
Introduction to Engineering EconomicsIntroduction to Engineering Economics
Introduction to Engineering Economics
 
Files in C
Files in CFiles in C
Files in C
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
Decision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsDecision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, Strings
 
Problem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to CProblem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to C
 

Recently uploaded

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 EscortsCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
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.pptxpranjaldaimarysona
 
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.pptxupamatechverse
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 

Recently uploaded (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
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
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
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 

Exception handling, Stream Classes, Multithread Programming

  • 1. Lecture By, Prabu.U Assistant Professor, Department of Computer Science and Engineering. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, V R Siddhartha Engineering College. 20ES3102 – JAVA PROGRAMMING UNIT 3
  • 2. UNIT III: Exception handling: Exception handling fundamentals, exception types, uncaught exceptions, using try and catch, multiple catch clauses, throw, throws, finally, creating your own exception subclasses. Stream Classes: Byte Streams- InputStream, OutputStream, FileInputStream, FileOutputStream, Character Streams- Reader, Writer, FileReader, FileWriter. Multithread Programming: The Java Thread Model, creating a thread: Implementing Runnable, Extending Thread, creating multiple threads, Thread Priorities, Synchronization: Using Synchronized methods, The synchronized Statement. 20ES3102 – JAVA PROGRAMMING
  • 3. 1. Exception-Handling Fundamentals 2. Exception Types 3. Uncaught Exceptions 4. Using try and catch 5. Multiple catch Clauses 6. throw, throws, finally 7. Creating Your Own Exception Subclasses EXCEPTION HANDLING
  • 4. 1. Byte Streams  InputStream  OutputStream  FileInputStream  FileOutputStream 2. Character Streams  Reader  Writer  FileReader  FileWriter STREAM CLASSES
  • 5. 1. The Java Thread Model 2. Creating a Thread  Implementing Runnable  Extending Thread 3. Creating Multiple Threads 4. Thread Priorities 5. Synchronization  Using Synchronized methods  The synchronized Statement MULTITHREADED PROGRAMMING
  • 6. 1. Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.  When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.  That method may choose to handle the exception itself or pass it on. Either way, at some point, the exception is caught and processed.  Exceptions can be generated by the Java run-time system, or they can be manually generated by your code
  • 7.  Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment.  Manually generated exceptions are typically used to report some error condition to the caller of a method.  Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.  Program statements that you want to monitor for exceptions are contained within a try block.
  • 8.  If an exception occurs within the try block, it is thrown.  Your code can catch this exception (using catch) and handle it in some rational manner.  System-generated exceptions are automatically thrown by the Java runtime system.  To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause.  Any code that absolutely must be executed after a try block completes is put in a finally block.
  • 9. This is the general form of an exception-handling block: try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed after try block ends }
  • 10. 2. Exception Types  All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy.  Immediately below Throwable are two subclasses that partition exceptions into two distinct branches. One branch is headed by Exception.  This class is used for exceptional conditions that user programs should catch.  This is also the class that you will subclass to create your own custom exception types.
  • 11.  There is an important subclass of Exception, called RuntimeException.  Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing.  The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by your program.  Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error.
  • 12.
  • 13. 3. Uncaught Exceptions  This small program includes an expression that intentionally causes a divide-by-zero error: class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } }
  • 14.  When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception.  This causes the execution of Exc0 to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately.  In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run- time system.  Any exception that is not caught by your program will ultimately be processed by the default handler.  The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.
  • 15.  Here is the exception generated when this example is executed: java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
  • 16. 4. Using try and catch  Although the default exception handler provided by the Java run- time system is useful for debugging, you will usually want to handle an exception yourself.  Doing so provides two benefits. First, it allows you to fix the error. Second, it prevents the program from automatically terminating.  To handle a run-time error, simply enclose the code that you want to monitor inside a try block.  Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch.
  • 17. class Exc2 { public static void main(String args[]) { int d, a; // monitor a block of code try { d = 0; a = 42 / d; System.out.println("This will not be printed."); }
  • 18. // catch divide-by-zero error catch (ArithmeticException e) { System.out.println("Division by zero."); } System.out.println("After catch statement."); } } Division by zero. After catch statement.  Once an exception is thrown, program control transfers out of the try block into the catch block.
  • 19.  A try and its catch statement form a unit.  The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement.  A catch statement cannot catch an exception thrown by another try statement (except in the case of nested try statements, described shortly).  The statements that are protected by try must be surrounded by curly braces (That is, they must be within a block.)
  • 20. Java Random Class Methods nextBoolean() - This method returns next pseudorandom which is a boolean value from random number generator sequence. nextDouble() - his method returns next pseudorandom which is double value between 0.0 and 1.0. nextFloat() - This method returns next pseudorandom which is float value between 0.0 and 1.0. nextInt() - This method returns next int value from random number generator sequence. nextInt(int n) - This method return a pseudorandom which is int value between 0 and specified value from random number generator sequence.
  • 21. import java.util.Random; public class RandomNumberExample { public static void main(String[] args) { //initialize random number generator Random random = new Random(); //generates boolean value System.out.println(random.nextBoolean()); //generates double value System.out.println(random.nextDouble());
  • 22. //generates float value System.out.println(random.nextFloat()); //generates int value System.out.println(random.nextInt()); //generates int value within specific limit System.out.println(random.nextInt(20)); } }
  • 24. import java.util.Random; class HandleError { public static void main(String args[]) { int a=0, b=0, c=0; Random r = new Random(); for(int i=0; i<10; i++) { try { b = r.nextInt(); c = r.nextInt(); a = 12345 / (b/c); }
  • 25. catch (ArithmeticException e) { System.out.println("Division by zero."); a = 0; // set a to zero and continue } System.out.println("a: " + a); } } }
  • 26. a: -12345 Division by zero. a: 0 Division by zero. a: 0 Division by zero. a: 0 Division by zero. a: 0 Division by zero. a: 0 a: -2469 a: -12345 Division by zero. a: 0 a: 4115
  • 27.  In the next program each iteration of the for loop obtains two random integers.  Those two integers are divided by each other, and the result is used to divide the value 12345.  The final result is put into a. If either division operation causes a divide-by-zero error, it is caught, the value of a is set to zero, and the program continues.
  • 28. Displaying a Description of an Exception  Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a description of the exception.  You can display this description in a println( ) statement by simply passing the exception as an argument.
  • 29. import java.util.Random; class HandleErrorDescription { public static void main(String args[]) { int a=0, b=0, c=0; Random r = new Random(); for(int i=0; i<10; i++) { try { b = r.nextInt(); c = r.nextInt(); a = 12345 / (b/c); }
  • 30. catch (ArithmeticException e) { System.out.println("Exception: " + e); a = 0; // set a to zero and continue } System.out.println("a: " + a); } } }
  • 31. Output: Exception: java.lang.ArithmeticException: / by zero a: 0 Exception: java.lang.ArithmeticException: / by zero a: 0 Exception: java.lang.ArithmeticException: / by zero a: 0 a: -6172 a: 12345 a: 12345 Exception: java.lang.ArithmeticException: / by zero a: 0 a: 6172 a: 12345 a: 12345
  • 32. 5. Multiple catch Clauses  In some cases, more than one exception could be raised by a single piece of code.  To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception.  When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed.  After one catch statement executes, the others are bypassed, and execution continues after the try / catch block.
  • 33. class MultipleCatches { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; }
  • 34. catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); } }
  • 35. a = 0 Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks.
  • 36. 6. throw, throws, finally throw  So far, you have only been catching exceptions that are thrown by the Java run-time system.  However, it is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here: throw ThrowableInstance;
  • 37.  Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.  Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions.  There are two ways you can obtain a Throwable object: using a parameter in a catch clause or creating one with the new operator.  The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.
  • 38.  The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception.  If it does find a match, control is transferred to that statement.  If not, then the next enclosing try statement is inspected, and so on.  If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
  • 39. public class TestThrow { static void validate(int age) { if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]) { validate(13); System.out.println("rest of the code..."); } }
  • 40. Exception in thread "main" java.lang.ArithmeticException: not valid at TestThrow.validate(TestThrow.java:6) at TestThrow.main(TestThrow.java:12)
  • 41. throws  The throws keyword is used in the method declaration to declare the type of exceptions that might occur within it.  Its syntax is: accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 … { // code }
  • 42. import java.io.*; class TestThrows { public static void findFile() throws IOException { // code that may produce IOException File newFile=new File("test.txt"); FileInputStream stream=new FileInputStream(newFile); }
  • 43. public static void main(String[] args) { try { findFile(); } catch(IOException e) { System.out.println(e); } } } java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
  • 45. finally  finally creates a block of code that will be executed after a try /catch block has completed and before the code following the try/catch block.  The finally block will execute whether or not an exception is thrown.  If an exception is thrown, the finally block will execute even if no catch statement matches the exception.  Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns.
  • 46.  This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning.  The finally clause is optional. However, each try statement requires at least one catch or a finally clause.
  • 47. public class TestFinally { public static void main(String args[]) { try { int data=25/0; System.out.println(data); } catch(ArithmeticException e) { System.out.println(e); }
  • 48. finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } java.lang.ArithmeticException: / by zero finally block is always executed rest of the code...
  • 49. 7. Creating Your Own Exception Subclasses  Although Java’s built-in exceptions handle most common errors, you will probably want to create your own exception types to handle situations specific to your applications.  This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable).  Your subclasses don’t need to actually implement anything—it is their existence in the type system that allows you to use them as exceptions.
  • 50.  The Exception class does not define any methods of its own. It does, of course, inherit those methods provided by Throwable.  Thus, all exceptions, including those that you create, have the methods defined by Throwable available to them.  You may also wish to override one or more of these methods in exception classes that you create.  Exception defines four public constructors. Two support chained exceptions, described in the next section. The other two are shown here:  Exception( )  Exception(String msg)
  • 51.  The first form creates an exception that has no description. The second form lets you specify a description of the exception.  Although specifying a description when an exception is created is often useful, sometimes it is better to override toString( ). Here’s why: The version of toString( ) defined by Throwable (and inherited by Exception) first displays the name of the exception followed by a colon, which is then followed by your description.  By overriding toString( ), you can prevent the exception name and colon from being displayed.  This makes for a cleaner output, which is desirable in some cases.
  • 52.
  • 53.
  • 54. class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } }
  • 55. class ExceptionDemo { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")"); if(a > 10) throw new MyException(a); System.out.println("Normal exit"); }
  • 56. public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } }
  • 57. Called compute(1) Normal exit Called compute(20) Caught MyException[20]
  • 58. Chained Exceptions  To allow chained exceptions, two constructors and two methods were added to Throwable. The constructors are shown here:  Throwable(Throwable causeExc)  Throwable(String msg, Throwable causeExc)  In the first form, causeExc is the exception that causes the current exception. That is, causeExc is the underlying reason that an exception occurred.  The second form allows you to specify a description at the same time that you specify a cause exception.  These two constructors have also been added to the Error, Exception, and RuntimeException classes.
  • 59.  The chained exception methods supported by Throwable are getCause( ) and initCause( ).  Throwable getCause( )  Throwable initCause(Throwable causeExc)  The getCause( ) method returns the exception that underlies the current exception.  If there is no underlying exception, null is returned. The initCause( ) method associates causeExc with the invoking exception and returns a reference to the exception.  Thus, you can associate a cause with an exception after the exception has been created.
  • 60.  However, the cause exception can be set only once.  Thus, you can call initCause( ) only once for each exception object.  Furthermore, if the cause exception was set by a constructor, then you can’t set it again using initCause( ).  In general, initCause( ) is used to set a cause for legacy exception classes that don’t support the two additional constructors described earlier.
  • 61. class ChainExcDemo { static void demoproc() { // create an exception NullPointerException e = new NullPointerException("top layer"); // add a cause e.initCause(new ArithmeticException("cause")); throw e; }
  • 62. public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { // display top level exception System.out.println("Caught: " + e); // display cause exception System.out.println("Original cause: " +e.getCause()); } } }
  • 63. Caught: java.lang.NullPointerException: top layer Original cause: java.lang.ArithmeticException: cause
  • 64. Multi-catch Features  The multi-catch feature allows two or more exceptions to be caught by the same catch clause.  It is not uncommon for two or more exception handlers to use the same code sequence even though they respond to different exceptions.  Instead of having to catch each exception type individually, you can use a single catch clause to handle all of the exceptions without code duplication.
  • 65.  To use a multi-catch, separate each exception type in the catch clause with the OR operator.  Each multi-catch parameter is implicitly final. (You can explicitly specify final, if desired, but it is not necessary.)  Because each multi-catch parameter is implicitly final, it can’t be assigned a new value.
  • 66. class MultiCatch { public static void main(String args[]) { int a=10, b=0; int vals[] = { 1, 2, 3 }; try { // generates an ArithmeticException int result = a / b; // generates an ArrayIndexOutOfBoundsException vals[10] = 19; // This catch clause catches both exceptions. }
  • 67. catch(ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println("Exception caught: " + e); } System.out.println("After multi-catch."); } } Exception caught: java.lang.ArithmeticException: / by zero After multi-catch.
  • 68. 1. Byte Streams  InputStream  OutputStream  FileInputStream  FileOutputStream 2. Character Streams  Reader  Writer  FileReader  FileWriter STREAM CLASSES
  • 69. Overview of I/O Streams  An I/O Stream represents an input source or an output destination.  A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.  Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects.  Some streams simply pass on data; others manipulate and transform the data in useful ways.
  • 70.  No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data.  A program uses an input stream to read data from a source, one item at a time:
  • 71.  A program uses an output stream to write data to a destination, one item at time:
  • 72. What is a Stream?  Abstraction that consumes or produces information  Linked to source and destination  Implemented within class hierarchies defined in java.io.package  An input stream acts as a source of data  An output stream acts as a destination of data
  • 73. Different Types of I/O Streams Byte Streams:  They provide a convenient means for handling input and output of bytes.  Programs use byte streams to perform input and output of 8-bit bytes.  All byte stream classes descend from InputStream and OutputStream class. Character Streams:  They provide a convenient means for handling input and output of characters.  They use Unicode and therefore, can be internationalized.
  • 74. Buffered 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. Data Streams:  Data streams support binary I/O of primitive data type values (Boolean, char, byte, short, int, long, float, and double) as well as String values. Object Streams:  Just as data streams support I/O of primitive data types, object streams support I/O of objects. Scanning and Formatting:  It allows a program to read and write formatted text.
  • 75.
  • 76.
  • 77. The Predefined Streams  The java.lang.System class encapsulates several aspects of the run- time environment.  Contains three predefined stream variables: in,out, and err.  These fields are declared as public and static within System.  System.out: refers to the standard output stream  System.err: refers to standard error stream  System.in: refers to standard input  out and err are objects of type PrintStream class and in is an object of the InputStream class.
  • 78. Streams Classes  Java’s stream-based I/O is built upon four abstract classes: InputStream, OutputStream, Reader, and Writer.  InputStream and OutputStream are designed for byte streams. Reader and Writer are designed for character streams.  The byte stream classes and the character stream classes form separate hierarchies.  In general, you should use the character stream classes when working with characters or strings and use the byte stream classes when working with bytes or other binary objects.
  • 79. 1. Byte Streams  The byte stream classes provide a rich environment for handling byte-oriented I/O.  A byte stream can be used with any type of object, including binary data.  This versatility makes byte streams important to many types of programs.
  • 80. InputStream  InputStream is an abstract class that defines Java’s model of streaming byte input.  It implements the AutoCloseable and Closeable interfaces.  Most of the methods in this class will throw an IOException when an I/O error occurs. (The exceptions are mark( ) and markSupported( ).)  The methods in InputStream is shown in the table
  • 81.
  • 82.
  • 83. OutputStream  OutputStream is an abstract class that defines streaming byte output.  It implements the AutoCloseable, Closeable, and Flushable interfaces.  Most of the methods defined by this class return void and throw an IOException in the case of I/O errors.  The methods in OutputStream is shown in the table.
  • 84.
  • 85.
  • 86. FileInputStream  The FileInputStream class creates an InputStream that you can use to read bytes from a file.  Two commonly used constructors are shown here:  FileInputStream(String filePath)  FileInputStream(File fileObj)  Either can throw a FileNotFoundException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file.
  • 87.  The FileInputStream class of the java.io package can be used to read data (in bytes) from files.  It extends the InputStream abstract class.
  • 88. Create a FileInputStream  In order to create a file input stream, we must import the java.io.FileInputStream package first.  Once we import the package, here is how we can create a file input stream in Java. 1. Using the path to file FileInputStream input = new FileInputStream(stringPath); Here, we have created an input stream that will be linked to the file specified by the path.
  • 89. 2. Using an object of the file FileInputStream input = new FileInputStream(File fileObject); Here, we have created an input stream that will be linked to the file specified by fileObject. Methods of FileInputStream  read() - reads a single byte from the file  read(byte[] array) - reads the bytes from the file and stores in the specified array  read(byte[] array, int start, int length) - reads the number of bytes equal to length from the file and stores in the specified array starting from the position start
  • 90. import java.io.*; public class FIS { public static void main(String args[]) { try { FileInputStream input = new FileInputStream("Sample.txt"); System.out.println("Data in the file: "); // Reads the first byte int i = input.read(); while(i != -1) { System.out.print((char)i); // Reads next byte from the file i = input.read(); }
  • 92. available() Method  To get the number of available bytes, we can use the available() method. import java.io.*; public class AvailableExample { public static void main(String args[]) { try { FileInputStream input = new FileInputStream("Sample.txt"); // Returns the number of available bytes System.out.println("Available bytes at the beginning: " + input.available());
  • 93. // Reads 2 bytes from the file input.read(); input.read(); // Returns the number of available bytes System.out.println("Available bytes at the end: " + input.available()); input.close(); } catch (Exception e) { System.out.println("Error:" +e); } } } Available bytes at the beginning: 11 Available bytes at the end: 9
  • 94. skip() Method  To discard and skip the specified number of bytes, we can use the skip() method. import java.io.*; public class SkipExample { public static void main(String args[]) { try { FileInputStream input = new FileInputStream("Sample.txt"); // Skips the 2 bytes input.skip(2); System.out.println("Input stream after skipping 2 bytes:");
  • 95. // Reads the first byte int i = input.read(); while (i != -1) { System.out.print((char) i); // Reads next byte from the file i = input.read(); } input.close(); } catch (Exception e) { System.out.println("Error:" +e); } } }
  • 96. Input stream after skipping 2 bytes: llo World
  • 97. FileOutputStream  FileOutputStream creates an OutputStream that you can use to write bytes to a file.  It implements the AutoCloseable, Closeable, and Flushable interfaces.  Four of its constructors are shown here:  FileOutputStream(String filePath)  FileOutputStream(File fileObj)  FileOutputStream(String filePath, boolean append)  FileOutputStream(File fileObj, boolean append)
  • 98.  They can throw a FileNotFoundException.  Here, filePath is the full path name of a file, and fileObj is a File object that describes the file.  If append is true, the file is opened in append mode.  Creation of a FileOutputStream is not dependent on the file already existing.  FileOutputStream will create the file before opening it for output when you create the object.  In the case where you attempt to open a read-only file, an exception will be thrown.
  • 99.  The FileOutputStream class of the java.io package can be used to write data (in bytes) to the files.  It extends the OutputStream abstract class.
  • 100. Create a FileOutputStream  In order to create a file output stream, we must import the java.io.FileOutputStream package first.  Once we import the package, here is how we can create a file output stream in Java. 1. Using the path to file // Including the boolean parameter FileOutputStream output = new FileOutputStream(String path, boolean value); // Not including the boolean parameter FileOutputStream output = new FileOutputStream(String path);
  • 101.  Here, we have created an output stream that will be linked to the file specified by the path.  Also, value is an optional boolean parameter.  If it is set to true, the new data will be appended to the end of the existing data in the file.  Otherwise, the new data overwrites the existing data in the file.
  • 102. 2. Using an object of the file FileOutputStream output = new FileOutputStream(File fileObject); Here, we have created an output stream that will be linked to the file specified by fileObject. Methods of FileOutputStream write() - writes the single byte to the file output stream write(byte[] array) - writes the bytes from the specified array to the output stream write(byte[] array, int start, int length) - writes the number of bytes equal to length to the output stream from an array starting from the position start
  • 103. import java.io.*; public class FOS { public static void main(String[] args) { String data = "Output File"; try { FileOutputStream output = new FileOutputStream("outfile.txt"); byte[] b = data.getBytes(); // Writes byte to the file output.write(b); output.close(); }
  • 105. flush() Method  To clear the output stream, we can use the flush() method. This method forces the output stream to write all data to the destination. import java.io.*; public class FlushExample { public static void main(String[] args) throws IOException { FileOutputStream out = null; String data = "Printed by flush method"; try { out = new FileOutputStream("flush.txt"); // Using write() method out.write(data.getBytes());
  • 106. // Using the flush() method out.flush(); out.close(); } catch(Exception e) { System.out.println("Error:" +e); } } } flush.txt Printed by flush method
  • 107. ByteArrayInputStream  The ByteArrayInputStream class of the java.io package can be used to read an array of input data (in bytes).  It extends the InputStream abstract class.
  • 108. Create a ByteArrayInputStream  In order to create a byte array input stream, we must import the java.io.ByteArrayInputStream package first. // Creates a ByteArrayInputStream that reads entire array ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr); // Creates a ByteArrayInputStream that reads a portion of array ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr, int start, int length);
  • 109. import java.io.ByteArrayInputStream; public class ByteArrayInputExample { public static void main(String[] args) { // Creates an array of byte byte[] array = {1, 2, 3, 4}; //byte[] array ={'A','B','C'}; try { ByteArrayInputStream input = new ByteArrayInputStream(array); System.out.print("The bytes read from the input stream: ");
  • 110. for(int i= 0; i < array.length; i++) { // Reads the bytes int data = input.read(); System.out.print(data + ", "); //System.out.print((char)data + ", "); } input.close(); } catch(Exception e) { e.getStackTrace(); } } } The bytes read from the input stream: 1, 2, 3, 4,
  • 111. ByteArrayOutputStream  The ByteArrayOutputStream class of the java.io package can be used to write an array of output data (in bytes).  It extends the OutputStream abstract class.  ByteArrayOutputStream maintains an internal array of bytes to store the data.
  • 112. Create a ByteArrayOutputStream  In order to create a byte array output stream, we must import the java.io.ByteArrayOutputStream package first. // Creates a ByteArrayOutputStream with default size ByteArrayOutputStream out = new ByteArrayOutputStream();  Here, we have created an output stream that will write data to an array of bytes with default size 32 bytes. However, we can change the default size of the array. // Creating a ByteArrayOutputStream with specified size ByteArrayOutputStream out = new ByteArrayOutputStream(int size);  The size specifies the length of the array.
  • 113. Access Data from ByteArrayOutputStream toByteArray() - returns the array present inside the output stream toString() - returns the entire data of the output stream in string form import java.io.ByteArrayOutputStream; class ByteArrayOutputExample { public static void main(String[] args) { String data = "This is data."; try { // Creates an output stream ByteArrayOutputStream output = new ByteArrayOutputStream(); // Writes data to the output stream output.write(data.getBytes());
  • 114. // Returns an array of bytes byte[] byteData = output.toByteArray(); System.out.print("Data using toByteArray(): "); for(int i=0; i<byteData.length; i++) { System.out.print((char)byteData[i]); } // Returns a string String stringData = output.toString(); System.out.println("nData using toString(): " + stringData); output.close(); }
  • 115. catch(Exception e) { e.getStackTrace(); } } } Data using toByteArray(): This is data. Data using toString(): This is data.
  • 116. ObjectInputStream  The ObjectInputStream class of the java.io package can be used to read objects that were previously written by ObjectOutputStream.  It extends the InputStream abstract class.
  • 117. Working of ObjectInputStream  The ObjectInputStream is mainly used to read data written by the ObjectOutputStream.  Basically, the ObjectOutputStream converts Java objects into corresponding streams. This is known as serialization. Those converted streams can be stored in files or transferred through networks.  Now, if we need to read those objects, we will use the ObjectInputStream that will convert the streams back to corresponding objects. This is known as deserialization.
  • 118. Create an ObjectInputStream  In order to create an object input stream, we must import the java.io.ObjectInputStream package first. // Creates a file input stream linked with the specified file FileInputStream fileStream = new FileInputStream(String file); // Creates an object input stream using the file input stream ObjectInputStream objStream = new ObjectInputStream(fileStream);  An object input stream named objStream is created that is linked with the file input stream named fileStream.  Now, the objStream can be used to read objects from the file.
  • 119. Methods of ObjectInputStream  The ObjectInputStream class provides implementations of different methods present in the InputStream class. read() Method read() - reads a byte of data from the input stream readBoolean() - reads data in boolean form readChar() - reads data in character form readInt() - reads data in integer form readObject() - reads the object from the input stream
  • 120. import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; class ObjectInputExample { public static void main(String[] args) { int data1 = 200; String data2 = "Two Hundred"; try { FileOutputStream file = new FileOutputStream("Objectinfile.txt"); ObjectOutputStream output = new ObjectOutputStream(file); // Writing to the file using ObjectOutputStream output.writeInt(data1); output.writeObject(data2);
  • 121. FileInputStream fileStream = new FileInputStream("Objectinfile.txt"); // Creating an object input stream ObjectInputStream objStream = new ObjectInputStream(fileStream); //Using the readInt() method System.out.println("Integer data :" + objStream.readInt()); // Using the readObject() method System.out.println("String data: " + objStream.readObject()); output.close(); objStream.close(); }
  • 122. catch (Exception e) { e.getStackTrace(); } } } Integer data :200 String data: Two Hundred
  • 123. ObjectOutputStream  The ObjectOutputStream class of the java.io package can be used to write objects that can be read by ObjectInputStream.  It extends the OutputStream abstract class.
  • 124. Working of ObjectOutputStream  Basically, the ObjectOutputStream encodes Java objects using the class name and object values. And, hence generates corresponding streams. This process is known as serialization.  Those converted streams can be stored in files and can be transferred among networks.  The ObjectOutputStream class only writes those objects that implement the Serializable interface. This is because objects need to be serialized while writing to the stream.
  • 125. Create an ObjectOutputStream  In order to create an object output stream, we must import the java.io.ObjectOutputStream package first. // Creates a FileOutputStream where objects from ObjectOutputStream are written FileOutputStream fileStream = new FileOutputStream(String file); // Creates the ObjectOutputStream ObjectOutputStream objStream = new ObjectOutputStream(fileStream);  An object output stream named objStream is created which is linked with the file output stream named fileStream.
  • 126. Methods of ObjectOutputStream  The ObjectOutputStream class provides implementations for different methods present in the OutputStream class. write() Method write() - writes a byte of data to the output stream writeBoolean() - writes data in boolean form writeChar() - writes data in character form writeInt() - writes data in integer form writeObject() - writes object to the output stream
  • 127. import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; class ObjectOutputExample { public static void main(String[] args) { int data1 = 300; String data2 = "Three Hundred"; try { FileOutputStream file = new FileOutputStream("ObjectOutfile.txt"); // Creates an ObjectOutputStream ObjectOutputStream output = new ObjectOutputStream(file); // writes objects to output stream output.writeInt(data1); output.writeObject(data2);
  • 128. // Reads data using the ObjectInputStream FileInputStream fileStream = new FileInputStream("ObjectOutfile.txt"); ObjectInputStream objStream = new ObjectInputStream(fileStream); System.out.println("Integer data :" + objStream.readInt()); System.out.println("String data: " + objStream.readObject()); output.close(); objStream.close(); } catch (Exception e) { e.getStackTrace(); } } }
  • 129. Integer data :300 String data: Three Hundred
  • 130. BufferedInputStream  The BufferedInputStream class of the java.io package is used with other input streams to read the data (in bytes) more efficiently.  It extends the InputStream abstract class
  • 131. Working of BufferedInputStream  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.
  • 132. Create a BufferedInputStream  In order to create a BufferedInputStream, we must import the java.io.BufferedInputStream package first. // Creates a FileInputStream FileInputStream file = new FileInputStream(String path); // Creates a BufferedInputStream BufferedInputStream buffer = new BufferInputStream(file);  A BufferdInputStream named buffer with the FileInputStream named file.  Here, the internal buffer has the default size of 8192 bytes. However, we can specify the size of the internal buffer as well.
  • 133. // Creates a BufferedInputStream with specified size internal buffer BufferedInputStream buffer = new BufferInputStream(file, int size);  The buffer will help to read bytes from the files more quickly.
  • 134. Methods of BufferedInputStream  The BufferedInputStream class provides implementations for different methods present in the InputStream class. read() Method read() - reads a single byte from the input stream read(byte[] arr) - reads bytes from the stream and stores in the specified array read(byte[] arr, int start, int length) - reads the number of bytes equal to the length from the stream and stores in the specified array starting from the position start
  • 135. import java.io.BufferedInputStream; import java.io.FileInputStream; class BufferedInputExample { public static void main(String[] args) { try { // Creates a FileInputStream FileInputStream file = new FileInputStream("BufIn.txt");
  • 136. // Creates a BufferedInputStream BufferedInputStream input = new BufferedInputStream(file); // Reads first byte from file int i = input .read(); while (i != -1) { System.out.print((char) i); // Reads next byte from the file i = input.read(); } input.close(); }
  • 137. catch (Exception e) { e.getStackTrace(); } } } This line is printed from BufIn File
  • 138. PrintStream  The PrintStream class of the java.io package can be used to write output data in commonly readable form (text) instead of bytes.  It extends the abstract class OutputStream.
  • 139. Create a PrintStream  In order to create a PrintStream, we must import the java.io.PrintStream package first. 1. Using other output streams // Creates a FileOutputStream FileOutputStream file = new FileOutputStream(String file); // Creates a PrintStream PrintStream output = new PrintStream(file, autoFlush);
  • 140.  Here, we have created a print stream that will write formatted data to the file represented by FileOutputStream  the autoFlush is an optional boolean parameter that specifies whether to perform auto flushing or not. 2. Using filename // Creates a PrintStream PrintStream output = new PrintStream(String file, boolean autoFlush);  We have created a print stream that will write formatted data to the specified file.  autoFlush is an optional boolean parameter that specifies whether to perform autoflush or not.
  • 141. Methods of PrintStream The PrintStream class provides various methods that allow us to print data to the output. print() Method print() - prints the specified data to the output stream println() - prints the data to the output stream along with a new line character at the end
  • 142. Example: print() method with System class class Main { public static void main(String[] args) { String data = "Hello World."; System.out.print(data); } } Hello World.
  • 143. Example: print() method with System class class Main { public static void main(String[] args) { String data = "Hello World."; System.out.print(data); } } Hello World.
  • 144. Example: print() method with PrintStream class import java.io.PrintStream; class Main { public static void main(String[] args) { String data = "This is a text written to Print file."; try { PrintStream output = new PrintStream("Print.txt"); output.print(data); output.close(); }
  • 146. 2. Character Streams  Reader  Writer  FileReader  FileWriter STREAM CLASSES
  • 147. Reader  The Reader class of the java.io package is an abstract superclass that represents a stream of characters.  Since Reader is an abstract class, it is not useful by itself. However, its subclasses can be used to read data. Subclasses of Reader In order to use the functionality of Reader, we can use its subclasses. Some of them are:  BufferedReader  InputStreamReader  FileReader  StringReader
  • 148.
  • 149. Create a Reader  In order to create a Reader, we must import the java.io.Reader package first. // Creates a Reader Reader input = new FileReader(); Methods of Reader ready() - checks if the reader is ready to be read read(char[] array) - reads the characters from the stream and stores in the specified array read(char[] array, int start, int length) - reads the number of characters equal to length from the stream and stores in the specified array starting from the start mark() - marks the position in the stream up to which data has been read reset() - returns the control to the point in the stream where the mark is set skip() - discards the specified number of characters from the stream
  • 150. import java.io.Reader; import java.io.FileReader; class ReaderExample { public static void main(String[] args) { // Creates an array of character char[] array = new char[100]; try { // Creates a reader using the FileReader Reader input = new FileReader("ReaderInput.txt");
  • 151. // Checks if reader is ready System.out.println("Is there data in the stream? " + input.ready()); // Reads characters input.read(array); System.out.println("Data in the stream:"); System.out.println(array); // Closes the reader input.close(); } catch(Exception e) { e.getStackTrace(); } } } This line is printed from the ReaderInput File.
  • 152. Writer  The Writer class of the java.io package is an abstract superclass that represents a stream of characters. Subclasses of Writer  In order to use the functionality of the Writer, we can use its subclasses. Some of them are:  BufferedWriter  OutputStreamWriter  FileWriter  StringWriter
  • 153.
  • 154. Create a Writer  In order to create a Writer, we must import the java.io.Writer package first. // Creates a Writer Writer output = new FileWriter();  Here, we have created a writer named output using the FileWriter class. It is because the Writer is an abstract class. Hence we cannot create an object of Writer.
  • 155. The Writer class provides different methods that are implemented by its subclasses. Here are some of the methods: write(char[] array) - writes the characters from the specified array to the output stream write(String data) - writes the specified string to the writer append(char c) - inserts the specified character to the current writer flush() - forces to write all the data present in the writer to the corresponding destination close() - closes the writer
  • 156. import java.io.FileWriter; import java.io.Writer; public class WriterExample { public static void main(String args[]) { String data = "This line is printed from FileWriterOut File"; try { // Creates a Writer using FileWriter Writer output = new FileWriter("FileWriterOut.txt"); // Writes string to the file output.write(data);
  • 157. // Closes the writer output.close(); } catch (Exception e) { e.getStackTrace(); } } }
  • 158. InputStreamReader  The InputStreamReader class of the java.io package can be used to convert data in bytes into data in characters.  It extends the abstract class Reader.
  • 159.  The InputStreamReader class works with other input streams. It is also known as a bridge between byte streams and character streams.  This is because the InputStreamReader reads bytes from the input stream as characters.  For example, some characters required 2 bytes to be stored in the storage.  To read such data we can use the input stream reader that reads the 2 bytes together and converts into the corresponding character.
  • 160. Create an InputStreamReader  In order to create an InputStreamReader, we must import the java.io.InputStreamReader package first. // Creates an InputStream FileInputStream file = new FileInputStream(String path); // Creates an InputStreamReader InputStreamReader input = new InputStreamReader(file);
  • 161. Methods of InputStreamReader  The InputStreamReader class provides implementations for different methods present in the Reader class. read() Method read() - reads a single character from the reader read(char[] array) - reads the characters from the reader and stores in the specified array read(char[] array, int start, int length) - reads the number of characters equal to length from the reader and stores in the specified array starting from the start
  • 162. import java.io.InputStreamReader; import java.io.FileInputStream; class IPStreamReaderEx { public static void main(String[] args) { // Creates an array of character char[] array = new char[100]; try { // Creates a FileInputStream FileInputStream file = new FileInputStream("IPStreamReaderFile.txt");
  • 163. // Creates an InputStreamReader InputStreamReader input = new InputStreamReader(file); // Reads characters from the file input.read(array); System.out.println("Data in the stream:"); System.out.println(array); // Closes the reader input.close(); } catch(Exception e) { e.getStackTrace(); } } }
  • 164. Data in the stream: This line is printed from IPStreamReaderFile
  • 165. OutputStreamWriter  The OutputStreamWriter class of the java.io package can be used to convert data in character form into data in bytes form.  It extends the abstract class Writer.
  • 166.  The OutputStreamWriter class works with other output streams. It is also known as a bridge between byte streams and character streams.  This is because the OutputStreamWriter converts its characters into bytes.  For example, some characters require 2 bytes to be stored in the storage.  To write such data we can use the output stream writer that converts the character into corresponding bytes and stores the bytes together.
  • 167. Create an OutputStreamWriter  In order to create an OutputStreamWriter, we must import the java.io.OutputStreamWriter package first. // Creates an OutputStream FileOutputStream file = new FileOutputStream(String path); // Creates an OutputStreamWriter OutputStreamWriter output = new OutputStreamWriter(file);
  • 168. write() Method write() - writes a single character to the writer write(char[] array) - writes the characters from the specified array to the writer write(String data) - writes the specified string to the writer
  • 169. import java.io.FileOutputStream; import java.io.OutputStreamWriter; public class OPStreamWriterEx { public static void main(String args[]) { String data = "This line is written to OPStreamWriterFile"; try { // Creates a FileOutputStream FileOutputStream file = new FileOutputStream("OPStreamWriterFile.txt"); // Creates an OutputStreamWriter OutputStreamWriter output = new OutputStreamWriter(file);
  • 170. // Writes string to the file output.write(data); // Closes the writer output.close(); } catch (Exception e) { e.getStackTrace(); } } }
  • 172. FileReader  The FileReader class of the java.io package can be used to read data (in characters) from files.  It extends the InputSreamReader class.
  • 173. Create a FileReader  In order to create a file reader, we must import the java.io.FileReader package first. 1. Using the name of the file FileReader input = new FileReader(String name); 2. Using an object of the file FileReader input = new FileReader(File fileObj);
  • 174. read() Method read() - reads a single character from the reader read(char[] array) - reads the characters from the reader and stores in the specified array read(char[] array, int start, int length) - reads the number of characters equal to length from the reader and stores in the specified array starting from the position start
  • 175. import java.io.FileReader; class FileReaderEx { public static void main(String[] args) { // Creates an array of character char[] array = new char[100]; try { // Creates a reader using the FileReader FileReader input = new FileReader("FreaderFile.txt"); // Reads characters input.read(array);
  • 176. System.out.println("Data in the file: "); System.out.println(array); // Closes the reader input.close(); } catch(Exception e) { e.getStackTrace(); } } } Data in the file: This line is written in File Reader
  • 177. FileWriter  The FileWriter class of the java.io package can be used to write data (in characters) to files.  It extends the OutputStreamWriter class.
  • 178. Create a FileWriter  In order to create a file writer, we must import the Java.io.FileWriter package first. 1. Using the name of the file FileWriter output = new FileWriter(String name); 2. Using an object of the file FileWriter input = new FileWriter(File fileObj);
  • 179. Methods of FileWriter The FileWriter class provides implementations for different methods present in the Writer class. write() Method write() - writes a single character to the writer write(char[] array) - writes the characters from the specified array to the writer write(String data) - writes the specified string to the writer
  • 180. import java.io.FileWriter; public class FileWriterEx { public static void main(String args[]) { String data = "This line is written to FWriter File"; try { // Creates a FileWriter FileWriter output = new FileWriter("FWriterFile.txt");
  • 181. // Writes the string to the file output.write(data); // Closes the writer output.close(); } catch (Exception e) { e.getStackTrace(); } } }
  • 182. BufferedReader  The BufferedReader class of the java.io package can be used with other readers to read data (in characters) more efficiently.  It extends the abstract class Reader.
  • 183. Working of BufferedReader  The BufferedReader maintains an internal buffer of 8192 characters.  During the read operation in BufferedReader, a chunk of characters is read from the disk and stored in the internal buffer. And from the internal buffer characters are read individually.  Hence, the number of communication to the disk is reduced. This is why reading characters is faster using BufferedReader.
  • 184. Create a BufferedReader  In order to create a BufferedReader, we must import the java.io.BuferedReader package first. // Creates a FileReader FileReader file = new FileReader(String file); // Creates a BufferedReader BufferedReader buffer = new BufferedReader(file); // Creates a BufferdReader with specified size internal buffer BufferedReader buffer = new BufferedReader(file, int size);
  • 185. Methods of BufferedReader  The BufferedReader class provides implementations for different methods present in Reader. read() Method read() - reads a single character from the internal buffer of the reader read(char[] array) - reads the characters from the reader and stores in the specified array read(char[] array, int start, int length) - reads the number of characters equal to length from the reader and stores in the specified array starting from the position start
  • 186. import java.io.FileReader; import java.io.BufferedReader; class BufferReaderEx { public static void main(String[] args) { // Creates an array of character char[] array = new char[100]; try { // Creates a FileReader FileReader file = new FileReader("BufferReaderFile.txt"); // Creates a BufferedReader BufferedReader input = new BufferedReader(file);
  • 187. // Reads characters input.read(array); System.out.println("Data in the file: "); System.out.println(array); // Closes the reader input.close(); } catch(Exception e) { e.getStackTrace(); } } } Data in the file: This line is printed from BufferReaderFile
  • 188. BufferedWriter  The BufferedWriter class of the java.io package can be used with other writers to write data (in characters) more efficiently.  It extends the abstract class Writer.
  • 189. Working of BufferedWriter  The BufferedWriter maintains an internal buffer of 8192 characters.  During the write operation, the characters are written to the internal buffer instead of the disk. Once the buffer is filled or the writer is closed, the whole characters in the buffer are written to the disk.  Hence, the number of communication to the disk is reduced. This is why writing characters is faster using BufferedWriter.
  • 190. Create a BufferedWriter  In order to create a BufferedWriter, we must import the java.io.BufferedWriter package first. // Creates a FileWriter FileWriter file = new FileWriter(String name); // Creates a BufferedWriter BufferedWriter buffer = new BufferedWriter(file); // Creates a BufferedWriter with specified size internal buffer BufferedWriter buffer = new BufferedWriter(file, int size);
  • 191. Methods of BufferedWriter  The BufferedWriter class provides implementations for different methods present in Writer. write() Method write() - writes a single character to the internal buffer of the writer write(char[] array) - writes the characters from the specified array to the writer write(String data) - writes the specified string to the writer
  • 192. import java.io.FileWriter; import java.io.BufferedWriter; public class BufferedWriterEx { public static void main(String args[]) { String data = "This line is written to BufferedWriterFile"; try { // Creates a FileWriter FileWriter file = new FileWriter("BufferedWriterFile.txt");
  • 193. // Creates a BufferedWriter BufferedWriter output = new BufferedWriter(file); // Writes the string to the file output.write(data); // Closes the writer output.close(); } catch (Exception e) { e.getStackTrace(); } } } This line is written to BufferedWriterFile
  • 194. StringReader  The StringReader class of the java.io package can be used to read data (in characters) from strings.  It extends the abstract class Reader.  In StringReader, the specified string acts as a source from where characters are read individually.
  • 195. Create a StringReader  In order to create a StringReader, we must import the java.io.StringReader package first. // Creates a StringReader StringReader input = new StringReader(String data); Methods of StringReader  The StringReader class provides implementations for different methods present in the Reader class.
  • 196. Methods of StringReader  The StringReader class provides implementations for different methods present in the Reader class. read() Method read() - reads a single character from the string reader read(char[] array) - reads the characters from the reader and stores in the specified array read(char[] array, int start, int length) - reads the number of characters equal to length from the reader and stores in the specified array starting from the position start
  • 197. import java.io.StringReader; public class StringReaderEX { public static void main(String[] args) { String data = "This is the text read from StringReader."; // Create a character array char[] array = new char[100]; try { // Create a StringReader StringReader input = new StringReader(data); //Use the read method input.read(array);
  • 198. System.out.println("Data read from the string:"); System.out.println(array); input.close(); } catch(Exception e) { e.getStackTrace(); } } } Data read from the string: This is the text read from StringReader.
  • 199. StringWriter  The StringWriter class of the java.io package can be used to write data (in characters) to the string buffer.  It extends the abstract class Writer.
  • 200. Create a StringWriter  In order to create a StringWriter, we must import the java.io.StringWriter package first. // Creates a StringWriter StringWriter output = new StringWriter(); // Creates a StringWriter with specified string buffer capacity StringWriter output = new StringWriter(int size);
  • 201. Methods of StringWriter write() Method write() - writes a single character to the string writer write(char[] array) - writes the characters from the specified array to the writer write(String data) - writes the specified string to the writer
  • 202. import java.io.StringWriter; public class StringWriterEx { public static void main(String[] args) { String data = "This is the text in the string."; try { // Create a StringWriter with default string buffer capacity StringWriter output = new StringWriter(); // Writes data to the string buffer output.write(data);
  • 203. // Prints the string writer System.out.println("Data in the StringWriter: " + output); output.close(); } catch(Exception e) { e.getStackTrace(); } } } Data in the StringWriter: This is the text in the string.
  • 204. Access Data from StringBuffer getBuffer() - returns the data present in the string buffer toString() - returns the data present in the string buffer as a string
  • 205. import java.io.StringWriter; public class StringWriterBufferEx { public static void main(String[] args) { String data = "This is the original data"; try { // Create a StringWriter with default string buffer capacity StringWriter output = new StringWriter(); // Writes data to the string buffer output.write(data);
  • 206. // Returns the string buffer StringBuffer stringBuffer = output.getBuffer(); System.out.println("StringBuffer: " + stringBuffer); // Returns the string buffer in string form String string = output.toString(); System.out.println("String: " + string); output.close(); } catch(Exception e) { e.getStackTrace(); } } } StringBuffer: This is the original data String: This is the original data
  • 207. PrintWriter  The PrintWriter class of the java.io package can be used to write output data in a commonly readable form (text).  It extends the abstract class Writer.
  • 208. Working of PrintWriter  Unlike other writers, PrintWriter converts the primitive data (int, float, char, etc.) into the text format. It then writes that formatted data to the writer.  Also, the PrintWriter class does not throw any input/output exception. Instead, we need to use the checkError() method to find any error in it.  The PrintWriter class also has a feature of auto flushing. This means it forces the writer to write all data to the destination if one of the println() or printf() methods is called.
  • 209. Create a PrintWriter  In order to create a print writer, we must import the java.io.PrintWriter package first. 1. Using other writers // Creates a FileWriter FileWriter file = new FileWriter("output.txt"); // Creates a PrintWriter PrintWriter output = new PrintWriter(file, autoFlush); Here,  we have created a print writer that will write data to the file represented by the FileWriter  autoFlush is an optional parameter that specifies whether to perform auto flushing or not
  • 210. 2. Using other output streams // Creates a FileOutputStream FileOutputStream file = new FileOutputStream("output.txt"); // Creates a PrintWriter PrintWriter output = new PrintWriter(file, autoFlush); Here,  We have created a print writer that will write data to the file represented by the FileOutputStream  The autoFlush is an optional parameter that specifies whether to perform auto flushing or not
  • 211. 3. Using filename // Creates a PrintWriter PrintWriter output = new PrintWriter(String file, boolean autoFlush); Here,  We have created a print writer that will write data to the specified file  The autoFlush is an optional boolean parameter that specifies whether to perform auto flushing or nor  In all the above cases, the PrintWriter writes data to the file using some default character encoding. However, we can specify the character encoding (UTF8 or UTF16) as well.
  • 212. Methods of PrintWriter  The PrintWriter class provides various methods that allow us to print data to the output. print() Method print() - prints the specified data to the writer println() - prints the data to the writer along with a new line character at the end
  • 213. import java.io.PrintWriter; class PrintWriterEx { public static void main(String[] args) { String data = "This is a text inside the file."; try { PrintWriter output = new PrintWriter("output.txt"); output.print(data); output.close(); }
  • 215. 1. The Java Thread Model 2. Creating a Thread  Implementing Runnable  Extending Thread 3. Creating Multiple Threads 4. Thread Priorities 5. Synchronization  Using Synchronized methods  The synchronized Statement MULTITHREADED PROGRAMMING
  • 216. Multithreaded Programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently.  Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.  You are almost certainly acquainted with multitasking because it is supported by virtually all modern operating systems. However, there are two distinct types of multitasking: process-based and thread-based.
  • 217.  It is important to understand the difference between the two. For many readers, process-based multitasking is the more familiar form.  A process is, in essence, a program that is executing. Thus, process- based multitasking is the feature that allows your computer to run two or more programs concurrently.  For example, process-based multitasking enables you to run the Java compiler while you are using a text editor or visiting a web site.  In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.
  • 218.  In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code.  This means that a single program can perform two or more tasks simultaneously. For instance, a text editor can format text at the same time that it is printing, as long as these two actions are being performed by two separate threads.  Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking handles the details.  Multitasking threads require less overhead than multitasking processes. Processes are heavyweight tasks that require their own separate address spaces.
  • 219.  Interprocess communication is expensive and limited. Context switching from one process to another is also costly.  Threads, on the other hand, are lighter weight. They share the same address space and cooperatively share the same heavyweight process.  Interthread communication is inexpensive, and context switching from one thread to the next is lower in cost.  While Java programs make use of process-based multitasking environments, process-based multitasking is not under Java’s control. However, multithreaded multitasking is.
  • 220.  Multithreading enables you to write efficient programs that make maximum use of the processing power available in the system.  One important way multithreading achieves this is by keeping idle time to a minimum. This is especially important for the interactive, networked environment in which Java operates because idle time is common.  For example, the transmission rate of data over a network is much slower than the rate at which the computer can process it.  Even local file system resources are read and written at a much slower pace than they can be processed by the CPU. And, of course, user input is much slower than the computer.
  • 221.  In a single-threaded environment, your program has to wait for each of these tasks to finish before it can proceed to the next one— even though most of the time the program is idle, waiting for input.  Multithreading helps you reduce this idle time because another thread can run when one is waiting.
  • 222. 1. The Java Thread Model  The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading in mind.  The value of a multithreaded environment is best understood in contrast to its counterpart.  Single-threaded systems use an approach called an event loop with polling. In this model, a single thread of control runs in an infinite loop, polling a single event queue to decide what to do next.
  • 223.  Once this polling mechanism returns with, say, a signal that a network file is ready to be read, then the event loop dispatches control to the appropriate event handler.  Until this event handler returns, nothing else can happen in the program. This wastes CPU time.  It can also result in one part of a program dominating the system and preventing any other events from being processed.  In general, in a single-threaded environment, when a thread blocks (that is, suspends execution) because it is waiting for some resource, the entire program stops running.
  • 224.  The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated.  One thread can pause without stopping other parts of your program. For example, the idle time created when a thread reads data from a network or waits for user input can be utilized elsewhere.  Multithreading allows animation loops to sleep for a second between each frame without causing the whole system to pause.  When a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run.
  • 225.  Threads exist in several states. Here is a general description. A thread can be running.  It can be ready to run as soon as it gets CPU time. A running thread can be suspended, which temporarily halts its activity.  A suspended thread can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource.  At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed.
  • 226. The Main Thread  When a Java program starts up, one thread begins running immediately.  This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons:  It is the thread from which other “child” threads will be spawned.  Often, it must be the last thread to finish execution because it performs various shutdown actions.  Although the main thread is created automatically when your program is started, it can be controlled through a Thread object.
  • 227.  To do so, you must obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread. Its general form is shown here: static Thread currentThread( )  This method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you can control it just like any other thread.
  • 228. class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t);
  • 229. try { for(int n = 6; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); } } }
  • 230. Output: Current thread: Thread[main,5,main] After name change: Thread[My Thread,5,main] 6 5 4 3 2 1
  • 231.  In this program, a reference to the current thread (the main thread, in this case) is obtained by calling currentThread( ), and this reference is stored in the local variable t.  Next, the program displays information about the thread. The program then calls setName( ) to change the internal name of the thread.  Information about the thread is then redisplayed. Next, a loop counts down from five, pausing one second between each line.  The pause is accomplished by the sleep( ) method. The argument to sleep( ) specifies the delay period in milliseconds. Notice the try/catch block around this loop.
  • 232.  The sleep( ) method in Thread might throw an InterruptedException. This would happen if some other thread wanted to interrupt this sleeping one.  Notice the output produced when t is used as an argument to println( ). This displays, in order: the name of the thread, its priority, and the name of its group.  By default, the name of the main thread is main. Its priority is 5, which is the default value, and main is also the name of the group of threads to which this thread belongs.  A thread group is a data structure that controls the state of a collection of threads as a whole.  After the name of the thread is changed, t is again output. This time, the new name of the thread is displayed.
  • 233.  The sleep( ) method causes the thread from which it is called to suspend execution for the specified period of milliseconds. Its general form is shown here: static void sleep(long milliseconds) throws InterruptedException  The number of milliseconds to suspend is specified in milliseconds. This method may throw an InterruptedException.  The sleep( ) method has a second form, shown next, which allows you to specify the period in terms of milliseconds and nanoseconds: static void sleep(long milliseconds, int nanoseconds) throws InterruptedException  This second form is useful only in environments that allow timing periods as short as nanoseconds.
  • 234.  The name of a thread can be set by using setName( ).  The name of a thread can be obtained by calling getName( ) (but note that this is not shown in the program).  These methods are members of the Thread class and are declared like this: final void setName(String threadName) final String getName( )  Here, threadName specifies the name of the thread.
  • 235. 2. Creating a Thread  A thread can be created by instantiating an object of type Thread.  Java defines two ways in which this can be accomplished:  Implement the Runnable interface.  Extend the Thread class, itself.
  • 236. Implementing Runnable  The easiest way to create a thread is to create a class that implements the Runnable interface.  Runnable abstracts a unit of executable code. A thread can be constructed on any object that implements Runnable.  To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( )  Inside run( ), the code is defined that constitutes the new thread.
  • 237.  It is important to understand that run( ) can call other methods, use other classes, and declare variables, just like the main thread can.  The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within your program.  This thread will end when run( ) returns.  After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class.  Thread defines several constructors. The one that we will use is shown here: Thread(Runnable threadOb, String threadName)
  • 238.  In this constructor, threadOb is an instance of a class that implements the Runnable interface.  This defines where execution of the thread will begin. The name of the new thread is specified by threadName.  After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. In essence, start( ) executes a call to run( ).  The start( ) method is shown here: void start( )
  • 239. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); // Start the thread t.start(); }
  • 240. // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } }
  • 241. class RunnableExample { public static void main(String args[ ] ) { // create a new thread new NewThread(); try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } }
  • 242. catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }
  • 243. Output: Child thread: Thread[Demo Thread,5,main] Child Thread: 5 Main Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.
  • 244.  Passing this as the first argument indicates that you want the new thread to call the run( ) method on this object.  Next, start( ) is called, which starts the thread of execution beginning at the run( ) method.  This causes the child thread’s for loop to begin.  After calling start( ), NewThread’s constructor returns to main( ).  When the main thread resumes, it enters its for loop. Both threads continue running, sharing the CPU in singlecore systems, until their loops finish.
  • 245. Extending Thread  The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class.  The extending class must override the run( ) method, which is the entry point for the new thread.  It must also call start( ) to begin execution of the new thread.
  • 246. class NewThread extends Thread { NewThread() { // Create a new, second thread super("Demo Thread"); System.out.println("Child thread: " + this); // Start the thread start(); }
  • 247. // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } }
  • 248. class ExtendThread { public static void main(String args[]) { // create a new thread new NewThread(); try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } }
  • 249. catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }
  • 250. Output: Child thread: Thread[Demo Thread,5,main] Child Thread: 5 Main Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.
  • 251.  The child thread is created by instantiating an object of NewThread, which is derived from Thread.  Notice the call to super( ) inside NewThread. This invokes the following form of the Thread constructor: public Thread(String threadName)  Here, threadName specifies the name of the thread
  • 252. 3. Creating Multiple Threads  So far, only two threads : the main thread and one child thread have been used.  However, the program can spawn as many threads as it needs.
  • 253. class NewThread implements Runnable { // name of thread String name; Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); // Start the thread t.start(); }
  • 254. // This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + "Interrupted"); } System.out.println(name + " exiting."); } }
  • 255. class MultiThreadDemo { public static void main(String args[]) { // start threads new NewThread("One"); new NewThread("Two"); new NewThread("Three"); try { // wait for other threads to end Thread.sleep(10000); }
  • 256. catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } }
  • 257. Output: New thread: Thread[One,5,main] New thread: Thread[Two,5,main] New thread: Thread[Three,5,main] One: 5 Three: 5 Two: 5 One: 4 Three: 4 Two: 4 One: 3 Three: 3 Two: 3 One: 2 Three: 2 Two: 2 One: 1 Three: 1 Two: 1 One exiting. Three exiting. Two exiting. Main thread exiting.
  • 258.  Once started, all three child threads share the CPU.  Notice the call to sleep(10000) in main( ).  This causes the main thread to sleep for ten seconds and ensures that it will finish last.
  • 259. Using isAlive( ) and join( )  Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread.  This method is defined by Thread, and its general form is shown here: final boolean isAlive( )  The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise.  While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join( ), shown here: final void join( ) throws InterruptedException
  • 260. class NewThread implements Runnable { // name of thread String name; Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); // Start the thread t.start(); }
  • 261. // This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); } }
  • 262. class DemoJoin { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); NewThread ob3 = new NewThread("Three"); System.out.println("Thread One is alive: "+ ob1.t.isAlive()); System.out.println("Thread Two is alive: "+ ob2.t.isAlive()); System.out.println("Thread Three is alive: "+ ob3.t.isAlive()); // wait for threads to finish try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); ob3.t.join(); }
  • 263. catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Thread One is alive: "+ ob1.t.isAlive()); System.out.println("Thread Two is alive: "+ ob2.t.isAlive()); System.out.println("Thread Three is alive: "+ ob3.t.isAlive()); System.out.println("Main thread exiting."); } }
  • 264. Output: New thread: Thread[One,5,main] New thread: Thread[Two,5,main] New thread: Thread[Three,5,main] Thread One is alive: true Two: 5 One: 5 Thread Two is alive: true Three: 5 Thread Three is alive: true Waiting for threads to finish. Three: 4 Two: 4 One: 4 Three: 3 One: 3 Two: 3
  • 265. Three: 2 One: 2 Two: 2 Three: 1 Two: 1 One: 1 Three exiting. Two exiting. One exiting. Thread One is alive: false Thread Two is alive: false Thread Three is alive: false Main thread exiting.
  • 266. 4. Threads Priorities  Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.  In theory, over a given period of time, higher-priority threads get more CPU time than lower-priority threads.  In practice, the amount of CPU time that a thread gets often depends on several factors besides its priority. (For example, how an operating system implements multitasking can affect the relative availability of CPU time.)  In theory, threads of equal priority should get equal access to the CPU. But you need to be careful.
  • 267.  To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its general form: final void setPriority(int level)  Here, level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5.  These priorities are defined as static final variables within Thread.  You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here: final int getPriority( )
  • 268. public class ThreadPriorityEx extends Thread { public void run() { System.out.println("Thread Running... "+Thread.currentThread().getName()); } public static void main(String args[]) { ThreadPriorityEx t1=new ThreadPriorityEx(); ThreadPriorityEx t2=new ThreadPriorityEx(); ThreadPriorityEx t3=new ThreadPriorityEx(); ThreadPriorityEx t4=new ThreadPriorityEx(); ThreadPriorityEx t5=new ThreadPriorityEx();
  • 270. System.out.println("Priority of thread t1 is: " + t1.getPriority()); //1 System.out.println("Priority of thread t2 is: " + t2.getPriority()); //5 System.out.println("Priority of thread t3 is: " + t3.getPriority()); //10 System.out.println("Priority of thread t4 is: " + t4.getPriority()); //9 try { t5.setPriority(11); System.out.println("Priority of thread t5 is: " + t5.getPriority()); //11 } catch (Exception e) { System.out.println("Illegal Arguement"); } } }
  • 271. Output: Thread Running... Thread-2 Thread Running... Thread-1 Thread Running... Thread-4 Thread Running... Thread-3 Thread Running... Thread-0 Priority of thread t1 is: 1 Priority of thread t2 is: 5 Priority of thread t3 is: 10 Priority of thread t4 is: 9 Illegal Arguement
  • 272. 5. Synchronization  When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.  Key to synchronization is the concept of the monitor. A monitor is an object that is used as a mutually exclusive lock. Only one thread can own a monitor at a given time.  When a thread acquires a lock, it is said to have entered the monitor.
  • 273.  All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.  These other threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires.
  • 274. Using Synchronized Methods  Synchronization is easy in Java, because all objects have their own implicit monitor associated with them.  To enter an object’s monitor, just call a method that has been modified with the synchronized keyword.  While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait.  To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method.
  • 275. class Callme { void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Interrupted"); } System.out.println("]"); } }
  • 276. class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); }
  • 277. // synchronize calls to call() public void run() { synchronized(target) { // synchronized block target.call(msg); } } }
  • 278. class Synch1 { public static void main(String args[]) { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); // wait for threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join(); }
  • 280. The Synchronized Statement The general form of the synchronized statement: synchronized(objRef) { // statements to be synchronized }  Here, objRef is a reference to the object being synchronized.  A synchronized block ensures that a call to a synchronized method that is a member of objRef’s class occurs only after the current thread has successfully entered objRef’s monitor.
  • 281. References 1. Herbert Schildt, “Java The Complete Reference”, 9th Edition, McGraw-Hill Education, New Delhi, 2017.