EXCEPTION HANDLING OR ERROR HANDLING 1 Agenda Introduction

  • Slides: 120
Download presentation
EXCEPTION HANDLING OR ERROR HANDLING 1

EXCEPTION HANDLING OR ERROR HANDLING 1

Agenda • • Introduction Errors and Exception Hierarchy Classification of Exceptions Built in Exceptions

Agenda • • Introduction Errors and Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined Exceptions

What is Error? - Error means mistakes or buggs - Error is classified into

What is Error? - Error means mistakes or buggs - Error is classified into types Error Compile Time Error All syntax errors will be detected And displayed by the Java compi ler and therefore these errors Are known as compile – time – errors 1. Missing Semicolon 2. Missing brackets in classes and methods 3. Use of undeclared variables Run Time Error A program may compile success fully creating the. exe file but not run properly. Such programs may produce wrong results due to wrong loaic or may terminate due to errors 1. Dividing an integer by zero 2. Accessing an element that is out of 3 the bounds of an array

Some Example of Runtime Errors class Error_Handling { public static void main(String args[]) {

Some Example of Runtime Errors class Error_Handling { public static void main(String args[]) { int a, b, c; a = 10; b = 0; c = a / b; System. out. println("The Value of the C Value is: " + c); } } Output: / by zero 4

Exception Types 1. All Exception types are subclasses of the built – in class

Exception Types 1. All Exception types are subclasses of the built – in class Throwable is at the top of the exception class hierarchy Throwable Exception (or) Runtime. 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 Error Which defines exceptions that are not Expected to be caught under normal Circumstances by our program. Ex. Stack overflow 5

Uncaught Exception class Error_Handling { public static void main(String args[]) { int i, j,

Uncaught Exception class Error_Handling { public static void main(String args[]) { int i, j, k 1, k 2; i = 10; j = 0; k 1 = i / j; k 2 = i + j; System. out. println("The Division of the K 1 Value is: " + k 1); System. out. println("The addition of the K 2 Value is: " + k 2); } } Output: java. lang. Arithmetic. Exception: / by zero at Error_Handling. main(Error_Handling. java: 4) In this example, we haven’t supplied any exception handlers of our own, so 6 the exception is caught by the default handler provided by the java run – time system

What is Exceptions? An Exception is condition that is caused by a run –

What is Exceptions? An Exception is condition that is caused by a run – time error in the program. What is Exception Handling? If the exception object is not caught and handled properly, the compiler will display an error message and will terminate the program. If we want the program to continue with the execution of the remaining appropriate message for taking corrective actions. This task is known as exception handling. Exceptions Types Exception Synchronous Exception 1. Division by Zero Asynchronous Exception 1. Keyboard Interrupt 2. Mouse Interrupt 7

Exception Handling Mechanism The purpose of the exception handling mechanism is to provide means

Exception Handling Mechanism The purpose of the exception handling mechanism is to provide means to detect and report an “exceptional circumstance”, so that appropriate action can be taken. The Error Handling code that performs the following tasks: 1. Find the problem (Hit the Exception) 2. Inform that an error has occurred (Throw the exception) 3. Receive the error information (Catch the exception) 4. Take corrective actions (Handle the exception) try block Detects and throws an exception catch block Exception object Catches and handles the exception 8

Using try and catch -----------------try { ------------------- //Block of statements which detects and //throws

Using try and catch -----------------try { ------------------- //Block of statements which detects and //throws an exception } catch(Exception_Type e) //Catches exception { -------------- //Block of statements that handles the //exception } ------------------ 9

Example Program for Exception Handling Mechanism class Error_Handling { public static void main(String args[])

Example Program for Exception Handling Mechanism class Error_Handling { public static void main(String args[]) { int i, j, k 1, k 2; i = 10; j = 0; try { There is an Exception k 1 = i / j; System. out. println("The Division of the K 1 Value is: " + k 1); } catch(Arithmetic. Exception e) Catches the exception { System. out. println("Division by Zero"); } k 2 = i + j; System. out. println("The addition of the K 2 Value is: " + k 2); } } Output: Division by Zero, The addition of the K 2 Value is: 10 10

Multiple Catch Statements It is possible that a program segment has more than one

Multiple Catch Statements It is possible that a program segment has more than one condition to throw an exception. try { //statements } catch(Exception-Type-1 e) { //statements } catch(Exception-Type-2 e) { //statements } ----------catch(Exception-Type-N e) { //statements } 11

class Error_Handling { public static void main(String args[]) { int a[ ] = {5,

class Error_Handling { public static void main(String args[]) { int a[ ] = {5, 10}; int b = 5; try { int x = a[2] / b - a[1]; } catch(Arithmetic. Exception e) { System. out. println("Division by Zero"); } catch(Array. Index. Out. Of. Bounds. Exception e) { System. out. println("Array Index Error"); } catch(Array. Store. Exception e) { System. out. println("Wrong data type"); } int y = a[1] / a[0]; System. out. println("Y = " + y); } } 12

COMMAN EXCEPTION HANDLER class Error_Handling { public static void main(String args[]) { int a[

COMMAN EXCEPTION HANDLER class Error_Handling { public static void main(String args[]) { int a[ ] = {5, 10}; int b = 5; try { int x = a[2] / b - a[1]; } catch(Arithmetic. Exception e) { System. out. println("Division by Zero"); } /*catch(Array. Index. Out. Of. Bounds. Exception e) { System. out. println("Array Index Error"); }*/ catch(Array. Store. Exception e) { System. out. println("Wrong data type"); } 13

catch(Exception e) { System. out. println("The Producing any Runtime Error" + e. get. Message());

catch(Exception e) { System. out. println("The Producing any Runtime Error" + e. get. Message()); } int y = a[1] / a[0]; System. out. println("Y = " + y); } } 14

EXCEPTION HIERARCHY class Error_Handling { public static void main(String args[]) { int a[ ]

EXCEPTION HIERARCHY class Error_Handling { public static void main(String args[]) { int a[ ] = {5, 10}; int b = 5; try { int x = a[2] / b - a[1]; } catch(Arithmetic. Exception e) { System. out. println("Division by Zero"); } catch(Exception e) { System. out. println("The Producing any Runtime Error" + e. get. Message()); } /*catch(Array. Index. Out. Of. Bounds. Exception e) { System. out. println("Array Index Error"); }*/ 15

catch(Array. Store. Exception e) { System. out. println("Wrong data type"); } int y =

catch(Array. Store. Exception e) { System. out. println("Wrong data type"); } int y = a[1] / a[0]; System. out. println("Y = " + y); } } 16

Nested try Statements class Error_Handling { public static void main(String args[]) { try {

Nested try Statements class Error_Handling { public static void main(String args[]) { try { int a = args. length; int b = 42 / a; //If no command - line args are present, //the following statement will generate a divide - by - zero exception System. out. println("a = " + a); // nested try bloack // If one command - line arg is used, then a divide - by //- zero exception will be generated by the following code. 17

try { if ( a == 1) a = a / (a - a);

try { if ( a == 1) a = a / (a - a); //division by zero if(a == 2) { int c[] = {1}; c[42] = 99; //generate an out - of - bounds exception } } catch(Array. Index. Out. Of. Bounds. Exception e) { System. out. println("Array index out - of - bounds: " + e); } } catch(Arithmetic. Exception e) { System. out. println("Divide by Zero: " + e); } } } 18

Nested try Statements using Subroutine class Error_Handling { static void nesttry(int a) { try

Nested try Statements using Subroutine class Error_Handling { static void nesttry(int a) { try { if ( a == 1) a = a / (a - a); //division by zero if(a == 2) { int c[] = {1}; c[42] = 99; //generate an out - of - bounds exception } } catch(Array. Index. Out. Of. Bounds. Exception e) { System. out. println("Array index out - of - bounds: " + e); } } 19

public static void main(String args[]) { try { int a = args. length; int

public static void main(String args[]) { try { int a = args. length; int b = 42 / a; //If no command - line args are present, the //following statement will generate a divide - by - zero exception System. out. println("a = " + a); // nested try bloack // If one command - line arg is used, then a divide - by //zero exception will be generated by the following code. nesttry(a); // Calling Static Method } catch(Arithmetic. Exception e) { System. out. println("Divide by Zero: " + e); } } } 20

throw 1. You have only been catching exceptions that are thrown by the java

throw 1. You have only been catching exceptions that are thrown by the java run – time system. 2. However, it is possible for your program to throw an exception explicitly. Using throw statement. Syntax: throw Throwable. Instance; 1. Here, Throwable. Instance must be an object of type Throwable or a subclass of Throwable. 2. Simple types, such as int or char, as well as non – Throwable classes, such as String and Object, cannot be used as exception. 3. There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator. 21

class Error_Handling { static void display() { try { throw new Null. Pointer. Exception("Demo");

class Error_Handling { static void display() { try { throw new Null. Pointer. Exception("Demo"); } catch(Null. Pointer. Exception e) { throw e; } } public static void main(String args[]) { try { display(); } catch(Null. Pointer. Exception e) { System. out. println("Recaught : " + e); } } } 22

throws 1. If a method is capable of causing an exception that it does

throws 1. If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. 2. You do this by including a throws clause in the method’s declaration. A throws clause list the types of exceptions that a method might throw. 3. This is necessary for all exceptions, except those of type Error or Runtime. Exception, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. 4. If they are not, a compile – time error will result. type method-name (parameter-list) throws exception-list { //body of method } Here, exception – list is comma – separated list of the exceptions that a method can throw 23

class Error_Handling { static void throwdemo() throws Illegal. Access. Exception { System. out. println("Inside

class Error_Handling { static void throwdemo() throws Illegal. Access. Exception { System. out. println("Inside throwdemo"); } public static void main(String args[]) { try { throwdemo(); } catch(Illegal. Access. Exception e) { System. out. println("Caught " + e); } } } 24

Using finally Statement 1. Java supports another statement known as finally statement that can

Using finally Statement 1. Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. 2. finally block can be used to handle any exception generated within a try block. 3. It may be added immediately after the try block or after the last catch block. try { //statements } finally { ------------------} //statements } catch(Exception-Type-1 e) { //statements } catch(Exception-Type-2 e) { //statements } ----------catch(Exception-Type-N e) { //statements } finally { ------------------} 25

class Error_Handling { static void proc. A() { try { System. out. println("Inside Proc.

class Error_Handling { static void proc. A() { try { System. out. println("Inside Proc. A"); throw new Runtime. Exception("demo"); } finally { System. out. println("Proc. A's finally"); } } static void proc. B() { try { System. out. println("inside Proc. B"); //return; } finally { System. out. println("Proc. B's finally"); } } 26

static void proc. C() { try { System. out. println("inside Proc. C"); } finally

static void proc. C() { try { System. out. println("inside Proc. C"); } finally { System. out. println("Proc. C's finally"); } } public static void main(String args[]) { try { proc. A(); } catch(Exception e) { System. out. println("Exception Caught"); } finally { System. out. println("Procedure A is Wind up"); } proc. B(); proc. C(); } } 27

Common scenarios where exceptions may occur There are given some scenarios where unchecked exceptions

Common scenarios where exceptions may occur There are given some scenarios where unchecked exceptions can occur. They are as follows: 1) Scenario where Arithmetic. Exception occurs If we divide any number by zero, there occurs an Arithmetic. Exception. int a=50/0; //Arithmetic. Exception 2) Scenario where Null. Pointer. Exception occurs If we have null value in any variable, performing any operation by the variable occurs an Null. Pointer. Exception. String s=null; System. out. println(s. length()); //Null. Pointer. Exception 28

3) Scenario where Number. Format. Exception occurs The wrong formatting of any value, may

3) Scenario where Number. Format. Exception occurs The wrong formatting of any value, may occur Number. Format. Exception. Suppose I have a string variable that have characters, converting this variable into digit will occur Number. Format. Exception. String s="abc"; int i=Integer. parse. Int(s); //Number. Format. Exception 4) Scenario where Array. Index. Out. Of. Bounds. Exception occurs If you are inserting any value in the wrong index, it would result Array. Index. Out. Of. Bounds. Exception as shown below: int a[]=new int[5]; a[10]=50; //Array. Index. Out. Of. Bounds. Exception 29

Java’s Built – in Exceptions 1. The standard package java. lang, Java defines several

Java’s Built – in Exceptions 1. The standard package java. lang, Java defines several exception classes. A few have been used by the preceding examples. 2. The most general of these exceptions are subclasses of the standard type Runtime. Exception 3. Since java. lang is implicitly imported into all java programs, most exceptions derived from Runtime. Exception are automatically available. 4. Furthermore, they need not be included in any method’s throws list. 5. In the language of Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. 6. The other exceptions defined by java. lang that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions. 30

Java’s Unchecked Runtime. Exception Subclasses Exception Meaning Arithmetic. Exception Arithmetic error, such as divde

Java’s Unchecked Runtime. Exception Subclasses Exception Meaning Arithmetic. Exception Arithmetic error, such as divde – by – zero Array. Index. Out. Of. Bounds. Exception Array index is out – of – bounds. Array. Store. Exception Assignment to an array element of an incompatible type. Class. Cast. Exception Invalid Cast. Illegal. Argument. Exception Illegal argument used to invoke a method Illegal. Monito. State. Exception Illegal Monitor Operation, such as waiting on an unlocked thread. Illegal. State. Exception Environment or application is in incorrect state. Illegal. Thread. State. Exception Requested operation not compatible with current thread state. Index. Out. Of. Bounds. Exception Some type of index is out – of – bounds Negative. Array. Size. Exception Array Created with a negative size. 31

Exception Meaning Null. Pointer. Exception Invalid use of a null reference. Number. Format. Exception

Exception Meaning Null. Pointer. Exception Invalid use of a null reference. Number. Format. Exception Invalid conversion of a string to a numeric format. Security. Exception Attempt to violate security String. Index. Out. Of. Bounds Attempt to index outside the bounds of a string. Unsupported. Operation. Exception An unsupported encountered. Operation was 32

Java’s Checked Exception Defined in java. lang Exception Meaning Class. Not. Found. Exception Class

Java’s Checked Exception Defined in java. lang Exception Meaning Class. Not. Found. Exception Class not found Clone. Not. Supported. Exception Attempt to clone an object that does not implement the cloneable interface. Illegal. Access. Exception Access to a class is denied Instantiation. Exception Attempt to create an object of an abstract class or interface Interrupted. Exception One thread has been interrupted by another thread. No. Such. Field. Exception A requested field does not exist. No. Such. Method. Exception A requested method does not exist. 33

Throwing our own Exceptions There may be times when we would like to throw

Throwing our own Exceptions There may be times when we would like to throw our own exceptions. We can do this by using the keyword throw as follows: throw new Throwable_subclass; Example: throw new Arithmetic. Exception(); throw new Number. Format. Exception(); Note: 1. Exception is subclass of Throwable and therefore My. Exception is a subclass of Throwable class. 2. An object of a class that extends Throwable can be thrown and caught 34

import java. lang. Exception; class My. Exception extends Exception { My. Exception(String message) {

import java. lang. Exception; class My. Exception extends Exception { My. Exception(String message) { super(message); } } class Exception_Handling { public static void main(String args[]) { int x = 5, y = 1000; try { float z = (float) x / (float) y; if (z < 0. 01) { throw new My. Exception("Number is too small"); 35 } }

catch(My. Exception e) { System. out. println("Caught my exception"); System. out. println(e. get. Message());

catch(My. Exception e) { System. out. println("Caught my exception"); System. out. println(e. get. Message()); } finally { System. out. println("I am always here"); } } } 36

Using Exceptions 1. Exception handling provides a powerful mechanism for controlling complex programs that

Using Exceptions 1. Exception handling provides a powerful mechanism for controlling complex programs that have many dynamic run – time characteristics. 2. It is important to think of try, throw and catch as clean ways to handle errors and unusual boundary conditions in your program’s logic. 3. If you are like most programmers, then you probably are used to returning an error code when a method fails. 4. When you are programming in Java, you should break this habit. When a method can fail, have it throw an exception. 5. This is a cleaner way to handle failure modes. 6. One last point: Java’s Exception – handling statements should not be considered a general mechanism for nonlocal branching. 7. If you do so, it will only confuse your code and make it hard to maintain. 37

When to Throw Exceptions • An exception occurs in a method. • If you

When to Throw Exceptions • An exception occurs in a method. • If you want the exception to be processed by its caller, you should create an exception object and throw it. • If you can handle the exception in the method where it occurs, there is no need to throw it. 38

When to Use Exceptions When should you use the try-catch block in the code?

When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code try { System. out. println(ref. Var. to. String()); } catch (Null. Pointer. Exception ex) { System. out. println("ref. Var is null"); } 39

When to Use Exceptions is better to be replaced by if (ref. Var !=

When to Use Exceptions is better to be replaced by if (ref. Var != null) System. out. println(ref. Var. to. String()); else System. out. println("ref. Var is null"); 40

Creating Custom Exception Classes F Use the exception classes in the API whenever possible.

Creating Custom Exception Classes F Use the exception classes in the API whenever possible. F Create custom exception classes if the predefined classes are not sufficient. F Declare custom exception classes by extending Exception or a subclass of Exception. 41

Custom Exception Class Example In Listing 17. 1, the set. Radius method throws an

Custom Exception Class Example In Listing 17. 1, the set. Radius method throws an exception if the radius is negative. Suppose you wish to pass the radius to the handler, you have to create a custom exception class. Invalid. Radius. Exception Circle. With. Radius. Exception Run Test. Circle. With. Radius. Exception 42

Assertions • An assertion is a Java statement that enables you to assert an

Assertions • An assertion is a Java statement that enables you to assert an assumption about your program. • An assertion contains a Boolean expression that should be true during program execution. • Assertions can be used to assure program correctness and avoid logic errors. 43

Assertion: • While executing assertion, it is believed to be true. • If it

Assertion: • While executing assertion, it is believed to be true. • If it fails, JVM will throw an error named Assertion. Error. • It is mainly used for testing purpose. • Advantage of Assertion: • It provides an effective way to detect and correct programming errors. 44

Syntax of using Assertion: • There are two ways to use assertion. First way

Syntax of using Assertion: • There are two ways to use assertion. First way is: • assert expression; and second way is: • assert expression 1 : expression 2; 45

import java. util. Scanner; class Assertion. Example{ public static void main( String args[] ){

import java. util. Scanner; class Assertion. Example{ public static void main( String args[] ){ Scanner scanner = new Scanner( System. in ); System. out. print("Enter ur age "); int value = scanner. next. Int(); assert value>=18: " Not valid"; System. out. println("value is "+value); } } 46

 • if you use assertion, It will not run simply because assertion is

• if you use assertion, It will not run simply because assertion is disabled by default. • To enable the assertion, -ea or -enableassertions switch of java must be used. • Compile it by: javac Assertion. Example. java • Run it by: java -ea Assertion. Example • Output: Enter ur age 11 • Exception in thread "main" java. lang. Assertion. Error: Not valid 47

Where not to use Assertion: • There are some situations where assertion should be

Where not to use Assertion: • There are some situations where assertion should be avoid to use. • According to Sun Specification, assertion should not be used to check arguments in the public methods because it should result in appropriate runtime exception e. g. Illegal. Argument. Exception, Null. Pointer. Exception etc. • Do not use assertion, if you don't want any error in any situation. 48

Compiling Programs with Assertions Since assert is a new Java keyword introduced in JDK

Compiling Programs with Assertions Since assert is a new Java keyword introduced in JDK 1. 4, you have to compile the program using a JDK 1. 4 compiler. Furthermore, you need to include the switch – source 1. 4 in the compiler command as follows: javac –source 1. 4 Assertion. Demo. java NOTE: If you use JDK 1. 5, there is no need to use the –source 1. 4 option in the command. 49

Running Programs with Assertions By default, the assertions are disabled at runtime. To enable

Running Programs with Assertions By default, the assertions are disabled at runtime. To enable it, use the switch –enableassertions, or –ea for short, as follows: java –ea Assertion. Demo Assertions can be selectively enabled or disabled at class level or package level. The disable switch is – disableassertions or –da for short. For example, the following command enables assertions in package 1 and disables assertions in class Class 1. java –ea: package 1 –da: Class 1 Assertion. Demo 50

Using Exception Handling or Assertions • Assertion should not be used to replace exception

Using Exception Handling or Assertions • Assertion should not be used to replace exception handling. • Exception handling deals with unusual circumstances during program execution. • Assertions are to assure the correctness of the program. • Exception handling addresses robustness and assertion addresses correctness. • Like exception handling, assertions are not used for normal tests, but for internal consistency and validity checks. • Assertions are checked at runtime and can be turned on or off at startup time. 51

Using Exception Handling or Assertions, cont. Do not use assertions for argument checking in

Using Exception Handling or Assertions, cont. Do not use assertions for argument checking in public methods. Valid arguments that may be passed to a public method are considered to be part of the method’s contract. The contract must always be obeyed whether assertions are enabled or disabled. public void set. Radius(double new. Radius) { assert new. Radius >= 0; radius = new. Radius; } 52

Using Exception Handling or Assertions, cont. Another good use of assertions is place assertions

Using Exception Handling or Assertions, cont. Another good use of assertions is place assertions in a switch statement without a default case. For example, switch (month) { case 1: . . . ; break; case 2: . . . ; break; . . . case 12: . . . ; break; default: assert false : "Invalid month: " + month } 53

THE CHARACTER STREAMS 54

THE CHARACTER STREAMS 54

The character Streams 1. While the byte stream classes provide sufficient functionality to handle

The character Streams 1. While the byte stream classes provide sufficient functionality to handle any type of I/O operation, they cannot work directly with Unicode characters. 2. Since one of the main purposes of Java is to support the “write once, run anywhere” philosophy, it was necessary to include direct I/O support for characters. 3. At the top of the character stream hierarchies are the Reader and Writer abstract classes. Reader is an abstract class that defines java’s model of streaming character input. All of the methods in this class will throw an IOException on error conditions. Writer is an abstract class that defines streaming character output. All of the methods in this class return a void value and throw an IOException in the case of errors. 55

The Methods Defined by Reader Method abstract void close() Description Closes the input source.

The Methods Defined by Reader Method abstract void close() Description Closes the input source. Further read attempts will generate an IOException. void mark(int num. Chars) Places a mark at the current point in the input stream that will remain valid until num. Chars characters are read boolean mark. Supported() Returns true if mark() / reset() are supported on this stream int read() Returns an integer representation of the next available character from the invoking input stream. -1 is returned when the end of the file is encountered. int read(char buffer[]) Attempts to read up to buffer. length characters into buffer and returns the actual number of character that were successfully read. -1 is returned when the end of the file encountered. abstract int read( char buffer[], int offset, int num. Chars) Attempts to read up to num. Chars characters into buffer starting at buffer[offset], returning the number of characters successfully read. -1 is returned when the end of the file is encountered. 56

Method Description boolean ready() Returns true if the next input request will not wait.

Method Description boolean ready() Returns true if the next input request will not wait. Otherwise, it returns false. void reset() Resets the input pointer to the previously set mark long skip( long num. Chars) Skips over num. Chars characters of input , returning the number of characters actually skipped. 57

The Methods Defined by Writer Method Description abstract void close() Closes the output stream.

The Methods Defined by Writer Method Description abstract void close() Closes the output stream. Further write attempts will generate an IOException. abstract void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. void write (int ch) Writes a single character to the invoking output stream. Note that the parameter is an int, which allows you to call write with expressions without having to cast them back to char. void write(char buffer[]) Writes a complete array of characters to the invoking output stream. abstract void write( char buffer[], int num. Chars) Writes a subrange of num. Chars characters from the array buffer, beginning at buffer[offset] to the invoking output stream. void write(String str) Writes str to the invoking output stream. void write(String str, int offset, int num. Chars) Writes a subrange of num. Chars characters from the array str, beginning at the specified offset. 58

File. Reader The File. Reader class creates a Reader that you can use to

File. Reader The File. Reader class creates a Reader that you can use to read the contents of a file. Its most commonly used constructors are shown here: File. Reader (String file. Path) File. Reader (File fil. Obj) Note: Either can throw a File. Not. Found. Exception. Here, file. Path is the full path name of a file and fileobj is a File object that describes the file. 59

import java. io. *; class File. Reader. Demo { public static void main(String args[])

import java. io. *; class File. Reader. Demo { public static void main(String args[]) throws IOException { File. Reader fr = new File. Reader("File. Reader. Demo. java"); Buffered. Reader br = new Buffered. Reader(fr); String s; while((s = br. read. Line()) != null) { System. out. println(s); } fr. close(); } } 60

File. Writer The File. Writer class creates a Writer that you can use to

File. Writer The File. Writer class creates a Writer that you can use to writet to a file. Its most commonly used constructors are shown here: File. Writer(String file. Path) File. Writer(String file. Path, boolean append) File. Writer(File file. Obj, boolean append) They can throw an IOException. Here, file. Path is the full path name of a file, and file. Obj is a File Object that describes the file. If append is true, then output is appended to the end fo the file. 61

import java. io. *; class File. Writer. Demo { public static void main(String args[])

import java. io. *; class File. Writer. Demo { public static void main(String args[]) { try { // Create file File. Writer fstream = new File. Writer("out. txt"); Buffered. Writer out = new Buffered. Writer(fstream); out. write("Hello Java"); //Close the output stream out. close(); } catch (Exception e) { //Catch exception if any System. err. println("Error: " + e. get. Message()); } } } 62

Char. Array. Reader is an implementation of an input stram that uses a character

Char. Array. Reader is an implementation of an input stram that uses a character array as the source. The class has two constructos, each of which requires a character array to provide the data source: Char. Array. Reader(char arrray[]) Char. Array. Reader(char array[], int start, int num. Chars) Here, array is the input source. The second constructor creates a Reader from a subset of your character array that begins with the character at the index specified by start and is num. Chars long. 63

import java. io. *; class Char. Array. Reader. Demo { public static void main(String

import java. io. *; class Char. Array. Reader. Demo { public static void main(String args[]) throws IOException { String tmp = "abcdefghijklmnopqrstuvwxyz"; int length = tmp. length(); char c[] = new char[length]; tmp. get. Chars(0, length, c, 0); Char. Array. Reader input 1 = new Char. Array. Reader(c); Char. Array. Reader input 2 = new Char. Array. Reader(c, 0, 5); int i; System. out. println("input 1 is: "); while((i = input 1. read()) != -1) { System. out. print((char)i); } System. out. println(); System. out. println("input 2 is: "); while((i = input 2. read()) != -1) { System. out. print((char)i); } System. out. println(); } } 64

Char. Array. Writer is an implementation of an output stram that uses a character

Char. Array. Writer is an implementation of an output stram that uses a character array as the destination. The class has two constructos, each of which requires a character array to provide the data destination: Char. Array. Writer() Char. Array. Writer(int num. Chars) In the first form, a buffer with a default size is created. In the second, a buffer is created with a size equal to that specified by num. Chars. The buffer is held in the buf field of Char. Array. Writer. The buffer size will be increased automatically, if needed. The number of characters held by the buffer is contained in the count field of Char. Array. Writer. Both buf and count are protected fields. 65

import java. io. *; class Char. Array. Writer. Demo { public static void main(String

import java. io. *; class Char. Array. Writer. Demo { public static void main(String args[]) throws IOException { Char. Array. Writer f = new Char. Array. Writer(); String s = "This should end up in the array"; char buf[] = new char[s. length()]; s. get. Chars(0, s. length(), buf, 0); f. write(buf); System. out. println("Buffer as a string"); System. out. println(f. to. String()); System. out. println("Into array"); char c[] = f. to. Char. Array(); for (int i=0; i<c. length; i++) { System. out. print(c[i]); } System. out. println("n. To a File. Writer()"); File. Writer f 2 = new File. Writer("test. txt"); f. write. To(f 2); f 2. close(); System. out. println("Doing a reset"); f. reset(); for (int i=0; i<3; i++) f. write('X'); System. out. println(f. to. String()); }} 66

Buffered. Reader improves performance by buffering input. It has two constructors: Buffered. Reader(Reader input.

Buffered. Reader improves performance by buffering input. It has two constructors: Buffered. Reader(Reader input. Stream) Buffered. Reader(Reader input. Stream, int bufsize) The first form creates a buffered character stream using a default buffer size. In the second, the size of the buffer is passed in bufsize. 67

import java. io. *; class Buffered. Reader. Demo { public static void main(String args[])

import java. io. *; class Buffered. Reader. Demo { public static void main(String args[]) throws IOException { String s = "This is a © copyright symbol " + "but this is &copy not. n"; char buf[] = new char[s. length()]; s. get. Chars(0, s. length(), buf, 0); Char. Array. Reader in = new Char. Array. Reader(buf); Buffered. Reader f = new Buffered. Reader(in); int c; while((c = f. read()) != -1) { System. out. print((char)c); } } } 68

Buffered. Writer A Buffered. Writer is a Writer that adds a flush() method that

Buffered. Writer A Buffered. Writer is a Writer that adds a flush() method that can be used to ensure that data buffers are physically wirtten to the actual output stream. Using a Buffered. Writer can increase performance by reducing the number of times data is actually physically written to the output stream. A Buffered. Writer has these two constructors: Buffered. Writer(Writer output. Stream) Buffered. Writer(Writer output. Stream, int bufsize) The first form creates a buffered character stream using a default buffer size. In the second, the size of the buffer is passed in bufsize. 69

import java. io. *; class Buffered. Writer. Demo { public static void main(String args[])

import java. io. *; class Buffered. Writer. Demo { public static void main(String args[]) throws Exception { // Create a new instance of a Buffered. Writer object using a String. Writer sw = new String. Writer(); Buffered. Writer bw = new Buffered. Writer(sw); // Write to the underlying String. Writer. String str = new String("This is the string being written. "); // Print out the 6 characters. bw. write(str, 12, 6); bw. flush(); System. out. println(sw. get. Buffer()); // Close the Buffered. Writer object and the underlying String. Writer object. sw. close(); bw. close(); } } 70

Pushback. Reader The Pushback. Reader class allows one or more characters to be returned

Pushback. Reader The Pushback. Reader class allows one or more characters to be returned to the input stream. This allows you to look ahead in the input stream. Here are its two constructors: Pushback. Reader(Reader input. Stream) Pushback. Reader(Reader input. Stream, int buf. Size) The first form creates a buffered stream that allows one character to be pushed back. In the second, the size of the pushback buffer is passed in buf. Size. Pushback. Reader provides unread(), which returns one or more characters to the invoking input stream. It has the three forms shown here: void unread(int ch) void unread(char buffer[], int offset, int num. Chars) The first form pushes back the character passed in ch. This will be the next character returned by a subsequent call to read(). The second form returns the characters in buffer. The third form 71 be pushes back num. Chars characters beginning at offset from buffer. An IOException will thrown if there is an attempt to return a character when the pushback buffer is full.

import java. io. *; class Pushback. Reader. Demo { public static void main(String args[])

import java. io. *; class Pushback. Reader. Demo { public static void main(String args[]) throws IOException { String s = "if (a == 4) a = 0 ; \n"; char buf[] = new char[s. length()]; s. get. Chars(0, s. length(), buf, 0); Char. Array. Reader in = new Char. Array. Reader(buf); Pushback. Reader f = new Pushback. Reader(in); int c; while ((c = f. read()) != -1) { switch(c) { case '=': if ((c = f. read()) == '=') System. out. print(". eq. "); else { System. out. print("<-"); f. unread(c); } break; default: System. out. print((char) c); break; } } 72

Print. Writer is essentially a character – oriented version of Print. Stream. It provides

Print. Writer is essentially a character – oriented version of Print. Stream. It provides the formatted output methods print() and println(). Print. Writer has four constructors: Print. Writer(Output. Stream output. Stream) Print. Writer(Output. Stream output. Stream, boolean flush. On. Newline) Print. Writer(Writer output. Stream, boolean flush. On. Newline) Where flush. On. Newline controls whether Java flushes the output stream every time println() is called. If flush. On. Newline is true, flushing automatically takes place. If false, flushing is not automatic. The first and third constructors do not automatically flush. 73

import java. io. *; class Print. Writer. Demo { public static void main(String args[])

import java. io. *; class Print. Writer. Demo { public static void main(String args[]) { Print. Writer pw = new Print. Writer(System. out, true); pw. println("This is a string"); int i = -7; pw. println(i); double d = 4. 5 e-7; pw. println(d); } } 74

SERIALIZATION 75

SERIALIZATION 75

Serialization 1. Serialization is the process of writing the state of an object to

Serialization 1. Serialization is the process of writing the state of an object to a byte stream. 2. This is useful when you want to save the state of your program to a persistent storage area, such as a file. 3. At a later time, you may restore these objects by using the process of deserialization. 4. Serialization is also needed to implement Remote Method Invocation (RMI). 5. RMI allows a Java object on one machine to invoke a method of a Java object on a different machine. 6. An object may be supplied as an argument to that remote method. 7. The sending machine serializes the object and transmits it. 8. The receiving machine deserializes it. 76

Serializable 1. Only an object that implements the Serializable interface can be saved and

Serializable 1. Only an object that implements the Serializable interface can be saved and restored by the serialization facilities. 2. The Serializable interface defines no members. It is simply used to indicate that a class may be serialized. 3. If a class is serializable, all of its subclasses are also serializable. 4. Variables that are declared as transient are not saved by the serialization facilities. 5. Also static variable are not saved. Externalizable 1. The Java facilities for serialization and deserialization have been designed so that much of the work to save and restore the state of an object occurs automatically. 2. However, there are cases in which the programmer may need to have control over these processes. 3. For example, it may be desirable to use compression or encryption techniques. The Externalizable interface is designed for these situations. 4. The Externalizable interface defines these two methods: void read. External(Object. Input in. Stream) throws IOException, Class. Not. Found. Exception void write. External(Object. Output out. Stream) throws IOException 77 In these methods, in. Stream is the byte stream from which the object is to be read, and out. Stream is the byte stream to which the object is to be written.

Object. Output The Object. Output interface extends the Data. Output interface and support object

Object. Output The Object. Output interface extends the Data. Output interface and support object Serialization. The following Methods is called the serialize an object. All of these methods will throw an IOException on error condition. Method Description void close() Closes the invoking stream. Further write attempts will generate an IOException. void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. void wirte(byte buffer[]) Writes an array of bytes to the invoking stream. void write(byte buffer[], int offset, int num. Bytes) Writes a subrange of num. Bytes bytes from the array buffer, beginning at buffer[offset]. void write(int b) Writes a single byte to the invoking stream. The byte written is the low – order byte of b. Void write. Object(Object obj) Writes object obj to the invoking stream. 78

Object. Output. Stream The Object. Output. Stream class extends the Output. Stream class and

Object. Output. Stream The Object. Output. Stream class extends the Output. Stream class and implements the Object. Output interface. It is responsible for writing objects to a stream. A constructor of this class is: Object. Output. Stream(Output. Stream out. Stream) throws IOException The argument out. Stream is the output stream to which serialized objects will be written. Method Description void close() Closes the invoking stream. Further write attempts will generate an IOException. void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. void wirte(byte buffer[]) Writes an array of bytes to the invoking stream. void write(byte buffer[], int offset, int num. Bytes) Writes a subrange of num. Bytes bytes from the array buffer, beginning at buffer[offset]. void write(int b) Writes a single byte to the invoking stream. The byte written is the low – order byte of b. void write. Boolean(boolean b) Writes boolean to the invoking stream. 79

Method Description void write. Byte(int b) Writes a byte to the invoking stream. The

Method Description void write. Byte(int b) Writes a byte to the invoking stream. The byte written is the low – order byte of b. void write. Bytes(String str) Writes the bytes representing str to the invoking stream. void write. Char(int c) Writes a char to the invoking stream. void write. Chars(String str) Writes the characters in str to the invoking stream. void write. Double(double d) Writes a double to the invoking stream. void write. Float(float f) Writes a float to the invoking stream. void write. Int(int i) Writes a int to the invoking stream. void Write. Short(int i) Writes a short to the invoking stream. void write. Long(long i) Writes a long to the invoking stream. final void write. Object(Object obj) Writes a obj to the invoking stream. 80

Object. Input The Object. Input interface extends the Data. Input interface and support object

Object. Input The Object. Input interface extends the Data. Input interface and support object Serialization. The following Methods is called the serialize an object. All of these methods will throw an IOException on error condition. Method Description int available() Returns the number of bytes that are now available in the input buffer. void close() Closes the invoking stream. Further read attempts will generate an IOException. int read() Returns an integer representation of the next available byte of input. -1 is returned when the end of the file is encountered. int read(byte buffer[]) Attempts to read up to buffer length bytes into buffer, returning the number of bytes that were successfully read. -1 is returned when the end of the file is encountered. int read(byte buffer[], int offset, int num. Bytes) Attempts to read up to num. Bytes bytes into buffer starting at buffer[offset], returning the number of bytes that were successfully read. -1 is returned when the end of the file is encountered. 81

Method Description Object read. Object() Reads an object from the invoking stream. Long skip(long

Method Description Object read. Object() Reads an object from the invoking stream. Long skip(long num. Bytes) Ignores(that is, skips) num. Bytes bytes in the invoking stream, returnign the number of bytes actually ignored. Object. Input. Stream The Object. Input. Stream class extends the Input. Stream class and implements the Object. Input interface. It is responsible for Reading objects from a stream. A constructor of this class is: Object. Input. Stream(Input. Stream in. Stream) throws IOException, Stream. Corrupted. Exception The argument in. Stream is the input stream from which serialized objects should be read. 82

Method Description int available() Returns the number of bytes that are now available in

Method Description int available() Returns the number of bytes that are now available in the input buffer. void close() Closes the invoking stream. Further read attempts will generate an IOException int read() Returns an integer representation of the next available byte of input. -1 is returned when the end of the file is encountered. int read(byte buffer[], int offset, int num. Bytes) Attempts to read up to num. Bytes bytes into buffer starting at buffer[offset], returning the number of bytes successfully read. -1 is returned when the end of the file is encountered. boolean read. Boolena() Reads and returns boolean from the invoking stream. byte read. Byte() Reads and returns a byte from the invoking stream. char read. Char() Reads and returns a char from the invoking stream. double read. Double() Reads and returns a double from the invoking stream. float read. Float() Reads and returns a float from the invoking stream. void read. Fully(byte buffer[]) Reads buffer length bytes into buffer. Returns only when all bytes have been read. void read. Fully(byte buffer[], int offset, int num. Bytes) 83 Reads num. Bytes bytes into buffer starting at buffer[offset]. Returns only when num. Bytes have been read.

Method Description int read. Int() Reads and returns an int from the invoking stream.

Method Description int read. Int() Reads and returns an int from the invoking stream. long read. Long() Reads and returns a long from the invoking stream. final Object read. Object() Reads and returns an object from the invoking stream. short read. Short() Reads and returns a short from the invoking stream. int read. Unsigned. Byte() Reads and returns an unsigned byte from the invoking stream. int read. Unsigned. Short() Reads an unsigned short from the invoking stream. 84

import java. io. *; class Serialization. Demo { public static void main(String arg[]) {

import java. io. *; class Serialization. Demo { public static void main(String arg[]) { //Object Serialization try { My. Class object 1 = new My. Class("Hello", -7, 2. 7 e 10); System. out. println("Object 1: " + object 1); File. Output. Stream fos = new File. Output. Stream("serial"); Object. Output. Stream oos = new Object. Output. Stream(fos); oos. write. Object(object 1); oos. flush(); oos. close(); } catch(Exception e) { System. out. println("Exception during serialization: " + e); System. exit(0); 85 }

//Object Deserialization try { My. Class object 2; File. Input. Stream fis = new

//Object Deserialization try { My. Class object 2; File. Input. Stream fis = new File. Input. Stream("serial"); Object. Input. Stream ois = new Object. Input. Stream(fis); object 2 = (My. Class)ois. read. Object(); ois. close(); System. out. println("object 2: " + object 2); } catch(Exception e) { System. out. println("Exception during deserialization: " + e); System. exit(0); } } } class My. Class implements Serializable { String s; int i; double d; public My. Class(String s, int i, double d) { this. s = s; this. i = i; this. d = d; } public String to. String() { return "S=" + s + "; i=" + i + "; d=" + d; } } 86

Converting Primitive Numbers to Object Numbers using Constructor Methods Constructor Calling Conversion Action Integer

Converting Primitive Numbers to Object Numbers using Constructor Methods Constructor Calling Conversion Action Integer intval = new Integer(i) Primitive integer to Integer object Float floatval = new Float(f) Primitive float to Float object Double doubleval = new Double(d) Primitive double to Double object Long longval = new Long(l) Primitive long to Long object Converting Object Numbers to Primitive Numbers using type. Value() method Method Calling Conversion Action int i = Int. Val. int. Value() Object to Primitive integer float f = Float. Val. float. Value() Object to Primitive float long l = Long. Val. long. Value() Object to Primitive long double d = Double. Val. double. Value() Object to Primitive double 87

Converting Numbers to Strings Using a String( ) Method Constructor Calling Conversion Action str

Converting Numbers to Strings Using a String( ) Method Constructor Calling Conversion Action str = Integer. to. String(i) Primitive Integer to string str = Float. to. String(f) Primitive float to string str = Double. to. String(d) Primitive double to string str = Long. to. String(l) Primitive long to string Converting String Objects to Numeric Object Using the Static Method Value. Of() Method Calling Conversion Action Double. Val = Double. Value. Of(str) Converts String to Double object Float. Val = Float. Value. Of(str) Converts String to Float object Int. Val = Integer. Value. Of(str) Converts string to Integer object Long. Val = Long. Valueof(str) Converts string to Long object 88

Converting Numberic Strings to Primitive Numbers Using Parsing Methods Constructor Calling Conversion Action int

Converting Numberic Strings to Primitive Numbers Using Parsing Methods Constructor Calling Conversion Action int i = Integer. parse. Int(str) Converts String to Primitive Integer long l = Long. parse. Long(str) Converts String to Primitive long 89

THREAD MODEL 90

THREAD MODEL 90

INTRODUCTION 1. Those who are familiar with the modern operation systems such as windows

INTRODUCTION 1. Those who are familiar with the modern operation systems such as windows 95 may recognize that they can execute several programs simultaneously. This ability is known as multitasking. In System’s terminology, it is called multithreading. 2. Multithreading is a conceptual programming paradigm where a program is divided into two or more subprograms, which can be implemented at the same time in parallel. For example, one subprogram can display an animation on the screen while another may build the next animation to be displayed. This something similar to dividing a task into subtasks and assigning them to different people for execution independently and simultaneously. 3. In most of our computers, we have only a single processor and therefore, in reality, the processor is doing only one thing at a time. However, the processor switches between the processes so fast that it appears to human beings that all of them are being done simultaneously. 4. Java programs contain only a single sequential flow of control. This is what happens when we execute a normal program. The program begins, runs through a sequence of executions, and finally ends. At any given point of time, there is only one statement under execution. 5. A thread is similar to a program that has a single flow of control. It has a beginning, a body and an end, and executes commands sequentially. In fact, all main programs in our earlier examples can be called single – threaded programs. 6. A unique property of Java is its support for multithreading. That is, java enables us to use multiple flows of control in developing programs. Each flow of control may be thought of as in separate tiny program known as thread that runs in parallel to others. 91

SINGLE THREADED PROGRAM class ABC { -------------------------------------------------------} Beginning Single – threaded body of execution

SINGLE THREADED PROGRAM class ABC { -------------------------------------------------------} Beginning Single – threaded body of execution End 92

MULTITHREADED PROGRAM Main Thread _______________ _______________ start _______________ _______________ Thread A switching start _______________

MULTITHREADED PROGRAM Main Thread _______________ _______________ start _______________ _______________ Thread A switching start _______________ _______________ Thread B Main method module start switching _______________ _______________ 93 Thread C

7. A program that contains multiple flows of control is known as multithreaded program.

7. A program that contains multiple flows of control is known as multithreaded program. 8. The above fig. is a java program with four threads, one main and three others. The main thread is actually the main method module, which is designed to create and start the other three threads, namely A, B and C 9. Once initiated by the main thread, the threads A, B and C run concurrently and share the resources jointly. The ability of a language to support multithreads is referred to as concurrency. 10. Threads in java are subprograms of main application program and share the same memory space, they are known as lightweight threads or lightweight processes. . Note: It is important to remember that ‘threads running in parallel’ does not really mean that they actually run at the same time. Since all the threads are running on a single processor, the flow of execution is shared between the threads. 94

CREATING THREADS 1. Creating threads in Java is simple. 2. Threads are implemented in

CREATING THREADS 1. Creating threads in Java is simple. 2. Threads are implemented in the form of objects that contain a method called run(). 3. The run() method is the heart and soul of any thread. It makes up the entire body of a thread and is the only method in which the thread’s behaviour can be implemented. 4. A typical run() would appear as follows: public void run() { --------------------------} Statements for implementing thread 95

5. The run() method should be invoked by an object for the concerned thread.

5. The run() method should be invoked by an object for the concerned thread. 6. This can be achieved by creating the thread and initiating it with the help of another thread method called start(). 7. A new thread can be created in two ways. a. By creating a thread class: Define a class that extends Thread class and override its run() method with the code required by the thread. b. By converting a class to a thread: Define a class that implements Runnable interface. The Runnable interface has only one method, run(), that is to be defined in the method with the code to be executed by the thread. 96

EXTENDING THE THREAD CLASS We can make our class runnable as a thread by

EXTENDING THE THREAD CLASS We can make our class runnable as a thread by extending the class java. lang. Thread. This gives us access to all the thread methods directly. It includes the following steps: 1. Declare the class as extending the Thread class 2. Implement the run() method that is responsible for executing the sequence of code that the thread will execute. 3. Create a thread object and call the start() method to initiate thread execution. 1. Declaring the class My. Thread extends Thread { ----------------------------} 97

2. Implementing the run() Method public void run() { --------------------------------} Thread Code Here 3.

2. Implementing the run() Method public void run() { --------------------------------} Thread Code Here 3. Starting New Thread My. Thread a. Thread = new My. Thread(); a. Thread. start(); //Invoke run() method 98

Creating threads using the thread class A extends Thread { public void run() {

Creating threads using the thread class A extends Thread { public void run() { for(int i = 1; i <= 5; i++) { System. out. println("t. From Thread A : i = " + i); } System. out. println("Exit from A "); } } class B extends Thread { public void run() { for(int j = 1; j <= 5; j++) { System. out. println("t. From Thread B : j = " + j); } System. out. println("Exit from B "); } } 99

class C extends Thread { public void run() { for(int k = 1; k

class C extends Thread { public void run() { for(int k = 1; k <= 5; k++) { System. out. println("t. From Thread C : k = " + k); } System. out. println("Exit from C "); } } class Thread. Test { public static void main(String args[]) { A a = new A(); B b = new B(); C c = new C(); a. start(); b. start(); c. start(); } } 100

IMPLEMENTING THE ‘RUNNABLE’ INTERFACE The Runnable interface declares the run() method that is required

IMPLEMENTING THE ‘RUNNABLE’ INTERFACE The Runnable interface declares the run() method that is required for implementing threads in our programs. To do this, we must perform the steps listed below: 1. Declare the class an implementing the Runnable interface. 2. Implementing the run() method. 3. Create a thread by defining an object that is instanitiated form the “runnable” class as the target of the thread. 4. Call the thread’s start() method to run the thread. 101

import java. lang. Thread; class X implements Runnable { public void run() { for(int

import java. lang. Thread; class X implements Runnable { public void run() { for(int i = 1; i <= 5; i++) { System. out. println("t. From Thread A : i = " + i); } System. out. println("Exit from A "); } } class Y implements Runnable { public void run() { for(int j = 1; j <= 5; j++) { System. out. println("t. From Thread B : j = " + j); } System. out. println("Exit from B "); } } 102

class Z implements Runnable { public void run() { for(int k = 1; k

class Z implements Runnable { public void run() { for(int k = 1; k <= 5; k++) { System. out. println("t. From Thread C : k = " + k); } System. out. println("Exit from C "); } } class Runnable. Test { public static void main(String args[]) { X runnable. X = new X(); Thread thread. X = new Thread(runnable. X); Y runnable. Y = new Y(); Thread thread. Y = new Thread(runnable. Y); Z runnable. Z = new Z(); Thread thread. Z = new Thread(runnable. Z); thread. X. start(); thread. Y. start(); thread. Z. start(); } } 103

LIFE CYCLE OF A THREAD During the life time of a thread, there are

LIFE CYCLE OF A THREAD During the life time of a thread, there are many states it can enter. They include 1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state 104

State Transition diagram of a Thread Newborn start stop Active Thread Runnable Running stop

State Transition diagram of a Thread Newborn start stop Active Thread Runnable Running stop Dead yield suspend resume sleep (Not Runnable) stop notify wait Idle Thread Killed Thread Blocked 105

Newborn State When we create a thread object, the thread is born and is

Newborn State When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it: 1. schedule it for funning using start() method. 2. kill it using stop() method. Newborn start Runnable state stop Dead State 106

Runnable State 1. The runnable state means that the thread is ready for execution

Runnable State 1. The runnable state means that the thread is ready for execution and is waiting for the availability of processor. 2. That is, the thread has joined the queue of threads that are waiting for execution. 3. If all threads have equal priority, then they are given time slots for execution in round robin fashion. i. e. , first – come, first – serve manner. 4. The thread that relinquishes contol joins the queue at the end again waits for its turn. This process of assigning time to threads is known as time – slicing. 5. However, if we want a thread to relinquish control to another thread of equal priority before its turn comes, we can do so by using the yield() method. Yield() Running Thread 107

Running State Running means that the processor has given its time to the thread

Running State Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread. A running thread may relinquish its control in one of the following situations: 1. suspend() and resume() It has been suspended using suspend() method. A suspended thread can be revived by using the resume() method. This approach is useful when we want to suspend a thread for some time due to certain reason, bur do not want to kill it suspend() resume() Running Runnable Suspended 108

2. sleep() It has been made to sleep, We can put a thread to

2. sleep() It has been made to sleep, We can put a thread to sleep for a specified time period using the method sleep (time) where time is in milliseconds. This means that the thread is out of the queue during this time period. The thread re – enters the runnable state as soon as this time period is elapsed. sleep (t) after t Running Runnable Sleeping 109

3. wait() and notify() It has been told to wait until some event occurs.

3. wait() and notify() It has been told to wait until some event occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method. wait() notify () Running Runnable Waiting Blocked State 1. A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. 2. This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements. 3. A blocked thread is considered “not runnable” but not dead therefore fully qualified to run again. 110

Dead State 1. Every thread has life cycle. A running thread ends its life

Dead State 1. Every thread has life cycle. A running thread ends its life when it has completed executing its run() method. 2. It is a natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it. 3. A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable” (blocked) condition. 111

import java. lang. Thread; class A extends Thread { public void run() { for(int

import java. lang. Thread; class A extends Thread { public void run() { for(int i = 1; i <= 5; i++) { if(i == 1) yield(); System. out. println("t. From Thread A : i = " + i); } System. out. println("Exit from A "); } } class B extends Thread { public void run() { for(int j = 1; j <= 5; j++) { System. out. println("t. From Thread B : j = " + j); if(j==3) stop(); } System. out. println("Exit from B "); } } 112

class C extends Thread { public void run() { for(int k = 1; k

class C extends Thread { public void run() { for(int k = 1; k <= 5; k++) { System. out. println("t. From Thread C : k = " + k); if(k==1) try { sleep(1000); } catch(Exception e) { } } System. out. println("Exit from C "); } } class Thread. Test_1 { public static void main(String args[]) { A a = new A(); B b = new B(); C c = new C(); System. out. println("Start Thread A"); a. start(); System. out. println("Start Thread B"); b. start(); System. out. println("Start Thread C"); c. start(); System. out. println("End of main Thread"); } } 113

Using is. Alive() and join() is. Alive() Two ways exist to determine whether a

Using is. Alive() and join() is. Alive() Two ways exist to determine whether a thread has finished. First, you can call is. Alive() on the thread. The method is defined by Thread, and its general form is shown here: final boolean is. Alive() The is. Alive() method returns true if the thread upon which it is called is still running. It returns false otherwise. join While is. Alive() is occasinally 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 Interrupted. Exception This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread 114 joins it.

class A extends Thread { public void run() { for(int i = 1; i

class A extends Thread { public void run() { for(int i = 1; i <= 5; i++) { System. out. println("t. From Thread A : i = " + i); } System. out. println("Exit from A "); } } class B extends Thread { public void run() { for(int j = 1; j <= 5; j++) { System. out. println("t. From Thread B : j = " + j); } System. out. println("Exit from B "); } } 115

class C extends Thread { public void run() { for(int k = 1; k

class C extends Thread { public void run() { for(int k = 1; k <= 5; k++) { System. out. println("t. From Thread C : k = " + k); } System. out. println("Exit from C "); } } class Thread. Test { public static void main(String args[]) { A a = new A(); B b = new B(); C c = new C(); 116

System. out. println("Start Thread A"); a. start(); System. out. println("Start Thread B"); b. start();

System. out. println("Start Thread A"); a. start(); System. out. println("Start Thread B"); b. start(); System. out. println("Start Thread C"); c. start(); System. out. println("End of main Thread"); System. out. println("Thread One is Alive: " + a. is. Alive()); System. out. println("Thread two is Alive: " + b. is. Alive()); System. out. println("Thread three is Alive: " + c. is. Alive()); try { a. join(); b. join(); c. join(); } catch(Interrupted. Exception e) { System. out. println("Main Thread Interrupted"); } System. out. println("Thread One is Alive: " + a. is. Alive()); System. out. println("Thread two is Alive: " + b. is. Alive()); System. out. println("Thread three is Alive: " + c. is. Alive()); } } 117

THREAD PRIORITY 1. In java, each thread is assigned a prioriy, which affects the

THREAD PRIORITY 1. In java, each thread is assigned a prioriy, which affects the order in which it is scheduled for running. 2. The threads of the same priority are given equal treatment by the Java scheduler and, therefore, they share the processor of a first – come, first – serve basis. Thread. Name. set. Priority(int. Number); The int. Number is an integer value to which the thread’s priority is set. The Thread class defines several priority constants: MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 The int. Number may assume one of these constants or any value between 1 and 10. Note that the default setting is NORM_PRIORITY 118

import java. lang. Thread; class A extends Thread { public void run() { for(int

import java. lang. Thread; class A extends Thread { public void run() { for(int i = 1; i <= 5; i++) { System. out. println("t. From Thread A : i = " + i); } System. out. println("Exit from A "); } } class B extends Thread { public void run() { for(int j = 1; j <= 5; j++) { System. out. println("t. From Thread B : j = " + j); } System. out. println("Exit from B "); } } 119

class C extends Thread { public void run() { for(int k = 1; k

class C extends Thread { public void run() { for(int k = 1; k <= 5; k++) { System. out. println("t. From Thread C : k = " + k); } System. out. println("Exit from C "); } } class Thread. Priority { public static void main(String args[]) { A a = new A(); B b = new B(); C c = new C(); c. set. Priority(5); b. set. Priority(10); a. set. Priority(1); //c. set. Priority(NORM_PRIORITY); //b. set. Priority(MAX_PRIORITY); //a. set. Priority(MIN_PRIORITY); a. start(); b. start(); c. start(); } } 120