Dr D Y Patil Institute of Engineering Management

  • Slides: 153
Download presentation
Dr. D. Y. Patil Institute of Engineering, Management and Research, Akurdi, Pune - 44

Dr. D. Y. Patil Institute of Engineering, Management and Research, Akurdi, Pune - 44 Department of Electronics and Telecommunication Engineering Unit VI Multithreading, Exception handling & Applets Prepared By: - Mrs. Neha Tiwari

Introduction to multithreading: Introduction, Creating thread and extending thread class. Concept of Exception handling:

Introduction to multithreading: Introduction, Creating thread and extending thread class. Concept of Exception handling: Introduction, Types of errors, Exception handling syntax, Multiple catch statements. I/O basics, Reading console inputs, Writing Console output.

Applets: Concepts of Applets, differences between applets and applications, life cycle of an applet,

Applets: Concepts of Applets, differences between applets and applications, life cycle of an applet, types of applets, creating a simple applet.

UNIT –VI –Chapter No-01 -Exception-Handling v. Exception-Handling Fundamentals Ø A Java exception is an

UNIT –VI –Chapter No-01 -Exception-Handling v. 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. Ø Java exception handling is managed via five keywords: try, catch, throws, and finally. Ø Program statements that you want to monitor for exceptions are contained within a try block. Ø 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. Ø System-generated exceptions are automatically thrown by the Java runtime system.

This is the general form of an exception-handling block: try { // block of

This is the general form of an exception-handling block: try { // block of code to monitor for errors } catch (Exception. Type 1 ex. Ob) { // exception handler for Exception. Type 1 } catch (Exception. Type 2 ex. Ob) { // exception handler for Exception. Type 2 } //. . . finally { // block of code to be executed after try block ends } Here, Exception. Type is the type of exception that has occurred.

 • The exception handling in java is one of the powerful mechanism to

• The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained. • Exceptions are nothing but the runtime errors. • It generally alters the flow of program execution. • When exception occurs, program execution stops and terminates the program abnormally. • Program execution does not continue. In this situation we get system generated error on screen.

 • The statement after the instructions which causes exceptions does not get executed.

• The statement after the instructions which causes exceptions does not get executed. • It is not always acceptable to terminate program abnormally. • In safety critical applications it not acceptable to terminate program abnormally. Exceptions occur due to so many reasons. Some of the reasons are as follows: 1] Invalid Input 2] File not available 3] Network Error 4] In sufficient memory 5] Improper use of array

Some of the real time exceptions are 1] We are trying to divide the

Some of the real time exceptions are 1] We are trying to divide the number by zero 2] We are trying to open file which is not existing 3] We are storing incompatible value in array 4] RAM is not enough to load your program. 5] WE are trying to access address which is pointing to NULL. 6] Improper type conversion. NOTE: When exception occurs , statements following that instructions will not get executed.

Example: public class Exception { public static void main(String args[]) { System. out. println(“This

Example: public class Exception { public static void main(String args[]) { System. out. println(“This is exception Example”); int a=100; double div=a/0; System. out. println(“Division of number is: ”+div); System. out. println(“This statement is after printing result”); } } Output: This is exception Example Exception in thread “main” java. lang. Arithmetic. Exception: /by zero

 • Exception is an abnormal condition. • In java, exception is an event

• Exception is an abnormal condition. • In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. • Exception Handling is a mechanism to handle runtime errors such as Class. Not. Found, IO, SQL, Remote etc.

Advantage of Exception Handling The core advantage of exception handling is to maintain the

Advantage of Exception Handling The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling.

statement 1; statement 2; statement 3; statement 4; statement 5; //exception occurs statement 6;

statement 1; statement 2; statement 3; statement 4; statement 5; //exception occurs statement 6; statement 7; statement 8; statement 9; statement 10; Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i. e. statement 6 to 10 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use exception handling in java.

Type of Error Java. lang Object Fig: Exception Hierarchy Throwable Errors Runtime exceptions Exceptions

Type of Error Java. lang Object Fig: Exception Hierarchy Throwable Errors Runtime exceptions Exceptions Other exceptions

 • Java provides mechanism to handle exceptional conditions. • It is possible with

• Java provides mechanism to handle exceptional conditions. • It is possible with concept of exception handling • Exception handling is fundamental in java programming language. • It is one of the reasons why java is so successful. • All exception in java is subclass of java. lang. Object. • Exception class is subclass of Throwable. • Throwable have two subclasses one is exception and another is errors. • Errors are mostly beyond the reach of programmer because programmers cannot deal with hardware problem. • Error handling is not part of exception handling mechanism. • Exception again have two subclasses namely runtime exceptions and other exceptions.

Types of Exceptions There are mainly two types of exceptions: checked and unchecked where

Types of Exceptions There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions: 1. Checked Exception 2. Unchecked Exception 3. Error

Difference between checked and unchecked exceptions 1) Checked Exception The classes that extend Throwable

Difference between checked and unchecked exceptions 1) Checked Exception The classes that extend Throwable class except Runtime. Exception and Error are known as checked exceptions. These exceptions should not be ignored and must be corrected by the programmer. e. g. IOException, SQLException etc. Checked exceptions are checked at compiletime.

Exception. Error. java import java. io. File; import java. io. File. Reader; public class

Exception. Error. java import java. io. File; import java. io. File. Reader; public class Exception. Error{ public static void main(String args[]) { File file=new File(“E: //file. txt”); File. Reader fr=new File. Reader(file); } }

Output: Exception in thread “main” java. lang. Error: Unresolved compilation problem: Unhandled exception type

Output: Exception in thread “main” java. lang. Error: Unresolved compilation problem: Unhandled exception type File. Not. Found. Exception at a. Exception. Error. main(Exception. Error. java)

2) Unchecked Exception The classes that extend Runtime. Exception are known as unchecked exceptions

2) Unchecked Exception The classes that extend Runtime. Exception are known as unchecked exceptions e. g. Arithmetic. Exception, Null. Pointer. Exception, Array. Index. Out. Of. Bounds. Exception etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. 3) Error is irrecoverable e. g. Out. Of. Memory. Error, Virtual. Machine. Error, Assertion. Error etc.

Example: package a; public class Unchecked. Exception{ public static void main(String args[]) { System.

Example: package a; public class Unchecked. Exception{ public static void main(String args[]) { System. out. println(“Example of unchecked exceptions”); int a=10; double div=a/0; System. out. println(“Division”+div); } } Output: Example of unchecked exceptions Exception in thread “main” java. lang. Arithmetic. Exception: / by zero at a. Unchecked. Exception. main(Unchecked. Exception. java)

Exception Types Ø All exception types are subclasses of the built-in class Throwable. Ø

Exception Types Ø All exception types are subclasses of the built-in class Throwable. Ø 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 Runtime. Exception. Ø 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.

Exception handling syntax Java Exception Handling Keywords There are 5 keywords used in java

Exception handling syntax Java Exception Handling Keywords There are 5 keywords used in java exception handling. 1. try 2. catch 3. finally 4. throw 5. throws

 • To handle the exceptions we need to identify the section of code

• To handle the exceptions we need to identify the section of code which may result into runtime error and apply the exception handling mechanisms. • It is always good programming practice to handle the exceptions.

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 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

String s="abc"; int i=Integer. parse. Int(s); //Number. Format. Exception 4) Scenario where Array. Index.

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

Java try-catch Java try block • Java try block is used to enclose the

Java try-catch Java try block • Java try block is used to enclose the code that might throw an exception. • It must be used within the method. • Java try block must be followed by either catch or finally block.

1. Syntax of java try-catch try{ //code that may throw exception }catch(Exception_class_Name ref){} 2.

1. Syntax of java try-catch try{ //code that may throw exception }catch(Exception_class_Name ref){} 2. Syntax of try-finally block try{ //code that may throw exception }finally{}

Java catch block • Java catch block is used to handle the Exception. •

Java catch block • Java catch block is used to handle the Exception. • It must be used after the try block only. • You can use multiple catch block with a single try. Problem without exception handling public class Testtrycatch 1{ public static void main(String args[]){ int data=50/0; //may throw exception System. out. println("rest of the code. . . "); } }

Output: Compile by: javac Testtrycatch 1. java Run by: java Testtrycatch 1 Exception in

Output: Compile by: javac Testtrycatch 1. java Run by: java Testtrycatch 1 Exception in thread "main" java. lang. Arithmetic. Exception: / by zero at Testtrycatch 1. main(Testtrycatch 1. java: 3) As displayed in the above example, rest of the code is not executed (in such case, rest of the code. . . statement is not printed). There can be 100 lines of code after exception. So all the code after exception will not be executed.

Solution by exception handling Let's see the solution of above problem by java try-catch

Solution by exception handling Let's see the solution of above problem by java try-catch block. public class Testtrycatch 2{ public static void main(String args[]){ try{ int data=50/0; }catch(Arithmetic. Exception e){System. out. p rintln(e); } System. out. println("rest of the code. . . "); } }

Compile by: javac Testtrycatch 2. java Run by: java Testtrycatch 2 java. lang. Arithmetic.

Compile by: javac Testtrycatch 2. java Run by: java Testtrycatch 2 java. lang. Arithmetic. Exception: / by zero rest of the code. . . Now, as displayed in the above example, rest of the code is executed i. e. rest of the code. . . statement is printed.

Internal working of java try-catch block

Internal working of java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is

The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks: 1. Prints out exception description. 2. Prints the stack trace (Hierarchy of methods where the exception occurred). 3. Causes the program to terminate. But if exception is handled by the application programmer, normal flow of the application is maintained i. e. rest of the code is executed.

Example: Try. Catch. java public class Try. Catch{ public static void main(String args[]){ System.

Example: Try. Catch. java public class Try. Catch{ public static void main(String args[]){ System. out. println(“Try Catch example”); int a=10; double div; System. out. println(“Before try catch”); try{ div=a/0; System. out. println(“Division is: ”+div); }catch(Arithmetic. Exception e){ System. out. println(“Divide by zero error”); } System. out. println(“After run time error”); }}

Output: Try Catch example Before try catch Divide by zero error After run time

Output: Try Catch example Before try catch Divide by zero error After run time error 1. Try block executed normally if there is no run time error. 2. If run time error occurs then it will directly jump to catch block and execute the statement from it. 3. Once catch block is over it will execute remaining statement after catch block. 4. After catch it will not go back to try block to execute remaining statements.

Example: Try. Catch. Desc. java public class Try. Catch. Desc{ public static void main(String

Example: Try. Catch. Desc. java public class Try. Catch. Desc{ public static void main(String args[]){ System. out. println(“Try Catch example with exception description”); int a=10; double div; System. out. println(“Before try catch”); try{ div=a/0; System. out. println(“Division is: ”+div); }catch(Arithmetic. Exception e){ System. out. println(“Exception description”+e); } System. out. println(“After run time error”); } }

Output: Try Catch example with exception description Before try catch Divide by zero error

Output: Try Catch example with exception description Before try catch Divide by zero error Exception description java. lang. Arithmetic. Exception: / by zero After run time error

Uncaught Exceptions class Exc 0 { public static void main(String args[]) { int d

Uncaught Exceptions class Exc 0 { 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 Exc 0 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 runtime Ø 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. Arithmetic.

Ø Here is the exception generated when this example is executed: java. lang. Arithmetic. Exception: / by zero at Exc 0. main(Exc 0. java: 4) Using try and catch class Exc 2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System. out. println("This will not be printed. "); } catch (Arithmetic. Exception e) { // catch divide-by-zero error System. out. println("Division by zero. "); } System. out. println("After catch statement. "); } } This program generates the following output: Division by zero. After catch statement.

Java catch multiple exceptions • If you have to perform different tasks at the

Java catch multiple exceptions • If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block. • Simple example of java multi-catch block.

public class Test. Multiple. Catch. Block{ public static void main(String args[]){ try{ int a[]=new

public class Test. Multiple. Catch. Block{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(Arithmetic. Exception e) { System. out. println("task 1 is completed"); } catch(Array. Index. Out. Of. Bounds. Exception e) { System. out. println("task 2 completed"); } catch(Exception e) { System. out. println("common task completed"); } System. out. println("rest of the code. . . "); } }

Compile by: javac Test. Multiple. Catch. Block. java Run by: java Test. Multiple. Catch.

Compile by: javac Test. Multiple. Catch. Block. java Run by: java Test. Multiple. Catch. Block task 1 is completed rest of the code. . . NOTE: Rule 1: At a time only one Exception is occured and at a time only one catch block is executed. Rule 2: All catch blocks must be ordered from most specific to most general i. e. catch for Arithmetic. Exception must come before catch for Exception.

class Test. Multiple. Catch. Block 1{ public static void main(String args[]){ try{ int a[]=new

class Test. Multiple. Catch. Block 1{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(Exception e) { System. out. println("common task completed"); } catch(Arithmetic. Exception e) { System. out. println("task 1 is completed"); } catch(Array. Index. Out. Of. Bounds. Exception e) { System. out. println("task 2 completed"); } System. out. println("rest of the code. . . "); } }

Compile by: javac Test. Multiple. Catch. Block 1. java: 8: error: exception Arithmetic. Exception

Compile by: javac Test. Multiple. Catch. Block 1. java: 8: error: exception Arithmetic. Exception has already been caught pleted"); } ^ e. Catch. Block 1. java: 9: error: exception Array. Index. Out. Of. Bounds. Exception has already been caught ask 2 completed"); } ^ 2 errors

Multiple catch Clauses Ø In some cases, more than one exception could be raised

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. // Demonstrate multiple catch statements. class Multiple. Catches { 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(Arithmetic. Exception e) { System. out. println("Divide by 0: " + e); } catch(Array. Index. Out. Of. Bounds. Excepti on e) { System. out. println("Array index oob: " + e); } System. out. println("After try/catch blocks. "); } }

Nested try Statements Ø The try statement can be nested. That is, a try

Nested try Statements Ø The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. Ø If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. Ø This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception

Java Nested try block The try block within a try block is known as

Java Nested try block The try block within a try block is known as nested try block in java. Why use nested try block Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax: . . try { statement 1; statement 2; } catch(Exception e) { }

Syntax: . . try { statement 1; statement 2; } catch(Exception e) { } . .

Java nested try example class Excep 6{ public static void main(String args[]){ try{ System.

Java nested try example class Excep 6{ public static void main(String args[]){ try{ System. out. println("going to divide"); int b =39/0; }catch(Arithmetic. Exception e){System. out. println(e); }

try{ int a[]=new int[5]; a[5]=4; }catch(Array. Index. Out. Of. Bounds Exception e) { System.

try{ int a[]=new int[5]; a[5]=4; }catch(Array. Index. Out. Of. Bounds Exception e) { System. out. println(e); } System. out. println("other statement); }catch(Exception e) { System. out. println("handeled"); } System. out. println("normal flow. . "); }}

// An example of nested try statements. class Nest. Try { public static void

// An example of nested try statements. class Nest. Try { public static void main(String args[]) { try { int a = args. length; /* If no command-line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System. out. println("a = " + a); try { // nested try block /* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero /* If two command-line args are used, then generate an out-of-bounds exception. */ if(a==2) { int c[] = { 1 }; c[42] = 99; // generate an out-ofbounds exception } } catch(Array. Index. Out. Of. Bounds. Excep tion e) { System. out. println("Array index outof-bounds: " + e); } } catch(Arithmetic. Exception e) { System. out. println("Divide by 0: " + e); } } }

Java finally block • Java finally block is a block that is used to

Java finally block • Java finally block is a block that is used to execute important code such as closing connection, stream etc. • Java finally block is always executed whether exception is handled or not. • Java finally block follows try or catch block. Why use java finally Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

Note: Rule 1: If you don't handle exception, before terminating the program, JVM executes

Note: Rule 1: If you don't handle exception, before terminating the program, JVM executes finally block(if any). Rule 2: For each try block there can be zero or more catch blocks, but only one finally block. Rule 3: The finally block will not be executed if program exits(either by calling System. exit() or by causing a fatal error that causes the process to abort).

Usage of Java finally Let's see the different cases where java finally block can

Usage of Java finally Let's see the different cases where java finally block can be used. Case 1 Let's see the java finally example where exception doesn't occur.

class Test. Finally. Block{ public static void main(String args[]){ try{ int data=25/5; System. out.

class Test. Finally. Block{ public static void main(String args[]){ try{ int data=25/5; System. out. println(data); } catch(Null. Pointer. Exception e) { System. out. println(e); } finally { System. out. println("finally block is always executed"); } System. out. println("rest of the code. . . "); }}

Compile by: javac Test. Finally. Block. java Run by: java Test. Finally. Block Output:

Compile by: javac Test. Finally. Block. java Run by: java Test. Finally. Block Output: 5 finally block is always executed rest of the code. . . Case 2 Let's see the java finally example where exception occurs and not handled.

1. class Test. Finally. Block 1{ 2. public static void main(String args[]){ 3. try{

1. class Test. Finally. Block 1{ 2. public static void main(String args[]){ 3. try{ 4. int data=25/0; 5. System. out. println(data); 6. } 7. catch(Null. Pointer. Exception e) 8. { 9. System. out. println(e); 10. } 11. finally 12. { 13. System. out. println("finally block is always executed" ); 14. } 15. System. out. println("rest of the code. . . "); 16. } 17. }

Compile by: javac Test. Finally. Block 1. java Run by: java Test. Finally. Block

Compile by: javac Test. Finally. Block 1. java Run by: java Test. Finally. Block 1 Exception in thread "main" java. lang. Arithmetic. Exception: / by zero at Test. Finally. Block 1. main(Test. Finally. Block 1. java: 4) finally block is always executed

Case 3 Let's see the java finally example where exception occurs and handled.

Case 3 Let's see the java finally example where exception occurs and handled.

public class Test. Finally. Block 2{ public static void main(String args[]){ try{ int data=25/0;

public class Test. Finally. Block 2{ public static void main(String args[]){ try{ int data=25/0; System. out. println(data); } catch(Arithmetic. Exception e){System. out. println(e ); } finally{ System. out. println("finally block is always executed "); } System. out. println("rest of the code. . . "); } }

Compile by: javac Test. Finally. Block 2. java Run by: java Test. Finally. Block

Compile by: javac Test. Finally. Block 2. java Run by: java Test. Finally. Block 2 java. lang. Arithmetic. Exception: / by zero finally block is always executed rest of the code. . .

Java throw keyword • The Java throw keyword is used to explicitly throw an

Java throw keyword • The Java throw keyword is used to explicitly throw an exception. • We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. • The syntax of java throw keyword is given below. throw exception;

Example: throw new IOException("sorry device error); public class Test. Throw 1{ static void validate(int

Example: throw new IOException("sorry device error); public class Test. Throw 1{ static void validate(int age){ if(age<18) throw new Arithmetic. Exception("not valid"); else System. out. println("welcome to vote"); } public static void main(String args[]){ validate(13); System. out. println("rest of the code. . . "); } }

we have created the validate method that takes integer value as a parameter. If

we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the Arithmetic. Exception otherwise print a message welcome to vote.

throw The general form of throw is shown here: throw Throwable. Instance; Ø Here,

throw The general form of throw is shown here: throw Throwable. Instance; Ø Here, Throwable. Instance 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. Ø For e. g. public static void main(String // Demonstrate throw. args[]) { class Throw. Demo { try { static void demoproc() { demoproc(); try { } catch(Null. Pointer. Exception e) throw new Null. Pointer. Exception("demo"); { } catch(Null. Pointer. Exception e) { System. out. println("Recaught: " System. out. println("Caught inside + e); demoproc. "); } throw e; // rethrow the exception } }

throws Ø A throws clause lists the types of exceptions that a method might

throws Ø A throws clause lists the types of exceptions that a method might throw. 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. If they are not, a compile-time error will result. Ø This is the general form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list{ // body of method } Ø Here, exception-list is a comma-separated list of the exceptions that a method can throw.

class Throws. Demo { static void throw. One() throws Illegal. Access. Exception { System.

class Throws. Demo { static void throw. One() throws Illegal. Access. Exception { System. out. println("Inside throw. One. "); throw new Illegal. Access. Exception("demo"); } public static void main(String args[]) { try { throw. One(); } catch (Illegal. Access. Exception e) { System. out. println("Caught " + e); } } } Ø Here is the output generated by running this example program: inside throw. One caught java. lang. Illegal. Access. Exception: demo

Java throws keyword The Java throws keyword is used to declare an exception. It

Java throws keyword The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as Null. Pointer. Exception, it is programmers fault that he is not performing check up before the code being used.

return_type method_name() throws exception_class_name { //method code } import java. io. IOException; class Testthrows{

return_type method_name() throws exception_class_name { //method code } import java. io. IOException; class Testthrows{ void m()throws IOException { throw new IOException("device error"); //checked exception } void n()throws IOException { m(); }

void p(){ try{ n(); }catch(Exception e) { System. out. println("exception handled"); } } public

void p(){ try{ n(); }catch(Exception e) { System. out. println("exception handled"); } } public static void main(String args[]){ Testthrows obj=new Testthrows(); obj. p(); System. out. println("normal flow. . . "); } }

Output: exception handled normal flow. . .

Output: exception handled normal flow. . .

No. throws 1. Java throw keyword is used to explicitly throw an exception 2.

No. throws 1. Java throw keyword is used to explicitly throw an exception 2. Checked exception cannot be Checked exception can be propagated using throw only. propagated with throws. 3. Throw is followed by an instance Throws is followed by class 4. Throw is used within the method. You cannot throw multiple exceptions. Throws is used with the method signature. You can declare multiple exceptions e. g. public void method()throws IOException, SQLException. 5. Java throws keyword is used to declare an exception.

finally Ø finally creates a block of code that will be executed after a

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. Ø For e. g.

// Demonstrate finally. class Finally. Demo { // Throw an exception out of the

// Demonstrate finally. class Finally. Demo { // Throw an exception out of the method. static void proc. A() { try { System. out. println("inside proc. A"); throw new Runtime. Exception("demo"); } finally { System. out. println("proc. A's finally"); } } // Return from within a try block. static void proc. B() { try { System. out. println("inside proc. B"); return; } finally { System. out. println("proc. B's finally"); } } // Execute a try block normally. 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"); } proc. B(); proc. C(); } } Here is the output generated by the preceding program: inside proc. A's finally Exception caught inside proc. B's finally inside proc. C's finally

 • Java finally block is a block that is used to execute important

• Java finally block is a block that is used to execute important code such as closing connection, stream etc. • Java finally block is always executed whether exception is handled or not. • Java finally block follows try or catch block. • Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).

java finally example where exception doesn't occur. class Test. Finally. Block{ public static void

java finally example where exception doesn't occur. class Test. Finally. Block{ public static void main(String args[]){ try{ int data=25/5; System. out. println(data); } catch(Null. Pointer. Exception e){System. out. println(e); } finally{System. out. println("finally block is always execut ed"); } System. out. println("rest of the code. . . "); } } Output: 5 finally block is always executed rest of the code. . .

java finally example where exception occurs and not handled. class Test. Finally. Block 1{

java finally example where exception occurs and not handled. class Test. Finally. Block 1{ public static void main(String args[]){ try{ int data=25/0; System. out. println(data); } catch(Null. Pointer. Exception e){System. out. println(e); } finally{System. out. println("finally block is always execute d"); } System. out. println("rest of the code. . . "); } } Output: finally block is always executed Exception in thread main java. lang. Arithmetic. Exception: /

java finally example where exception occurs and handled. public class Test. Finally. Block 2{

java finally example where exception occurs and handled. public class Test. Finally. Block 2{ public static void main(String args[]){ try{ int data=25/0; System. out. println(data); } catch(Arithmetic. Exception e){System. out. println(e); } finally{System. out. println("finally block is always execute d"); } System. out. println("rest of the code. . . "); } } Output: Exception in thread main java. lang. Arithmetic. Exception: / by zero finally block is always executed rest of the code. . .

For each try block there can be zero or more catch blocks, but only

For each try block there can be zero or more catch blocks, but only one finally block.

Java’s Built-in Exceptions Ø Inside the standard package java. lang, Java defines several exception

Java’s Built-in Exceptions Ø Inside the standard package java. lang, Java defines several exception classes. Ø The most general of these exceptions are subclasses of the standard type Runtime. Exception. • The exceptions need not be included in any method’s throws list. 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. The unchecked exceptions defined in java. lang 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.

Exception Meaning. Arithmetic. Exception Arithmetic error, such as divide-by-zero. Array. Index. Out. Of. Bounds.

Exception Meaning. Arithmetic. Exception Arithmetic error, such as divide-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. Enum. Constant. Not. Present. Exception An attempt is made to use an undefined enumeration value. Illegal. Argument. Exception Illegal argument used to invoke a method. Illegal. Monitor. 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. Null. Pointer. Exception Invalid use of a null reference. Number. Format. Exception Invalid conversion of a string to a numeric format.

Java Custom Exception If you are creating your own Exception that is known as

Java Custom Exception If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need. By the help of custom exception, you can have your own exception and message. Simple example of java custom exception.

class Test. Custom. Exception 1{ static void validate(int age)throws Invalid. Age. Exception{ if(age<18) throw

class Test. Custom. Exception 1{ static void validate(int age)throws Invalid. Age. Exception{ if(age<18) throw new Invalid. Age. Exception("not valid"); else System. out. println("welcome to vote"); } public static void main(String args[]){ try{ validate(13); }catch(Exception m){ System. out. println("Exception occured: "+m); } System. out. println("rest of the code. . . "); } }

Output: Exception occured: Invalid. Age. Exception: not valid rest of the code. . .

Output: Exception occured: Invalid. Age. Exception: not valid rest of the code. . .

Exception Meaning. Instantiation. Exception Attempt to create an object of an abstract class or

Exception Meaning. 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. Reflective. Operation. Exception Superclass of reflection-related exceptions. Security. Exception Attempt to violate security. String. Index. Out. Of. Bounds Attempt to index outside the bounds of a string. Type. Not. Present. Exception Type not found Unsupported. Operation. Exception An unsupported operation was encountered 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.

Creating Your Own Exception Subclasses Ø you will probably want to create your own

Creating Your Own Exception Subclasses Ø 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 Ø 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. Ø Exception defines four public constructors. Ø Two support chained exceptions Ø 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

Introduction to Multithreading • Many processes are running in the Operating System. • Use

Introduction to Multithreading • Many processes are running in the Operating System. • Use of processes to provide concurrency within an application incurs high process switching. • Multithreading in java is a process of executing multiple threads simultaneously. • Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

 • But we use multithreading than multiprocessing because threads share a common memory

• But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. • Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading 1) It doesn't block the user because threads are independent

Advantages of Java Multithreading 1) It doesn't block the user because threads are independent and you can perform multiple operations at same time. 2) You can perform many operations together so it saves time. 3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

What is Thread in java • A thread is a lightweight sub process, a

What is Thread in java • A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution. • Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area.

As shown in the above figure, thread is executed inside the process. There is

As shown in the above figure, thread is executed inside the process. There is contextswitching between the threads. There can be multiple processes inside the OS and one process can have multiple threads. Note: At a time one thread is executed only.

Below diagram shows different states of thread life cycle in java. We can create

Below diagram shows different states of thread life cycle in java. We can create a thread in java and start it but how the thread states change from Runnable to Running to Blocked depends on the OS implementation of thread scheduler and java doesn’t have full control on that.

New When we create a new Thread object using new operator, thread state is

New When we create a new Thread object using new operator, thread state is New Thread. At this point, thread is not alive and it’s a state internal to Java programming.

Runnable When we call start() function on Thread object, it’s state is changed to

Runnable When we call start() function on Thread object, it’s state is changed to Runnable. The control is given to Thread scheduler to finish it’s execution. Whether to run this thread instantly or keep it in runnable thread pool before running, depends on the OS implementation of thread scheduler. Running When thread is executing, it’s state is changed to Running. Thread scheduler picks one of the thread from the runnable thread pool and change it’s state to Running. Then CPU starts executing this thread. A thread can change state to Runnable, Dead or Blocked from running state depends on time slicing, thread completion of run() method or waiting for some resources.

Blocked/Waiting A thread can be waiting for other thread to finish using thread join

Blocked/Waiting A thread can be waiting for other thread to finish using thread join or it can be waiting for some resources to available. For example producer consumer or waiter notifier implementation or IO resources, then it’s state is changed to Waiting. Once thread wait state is over, it’s state is changed to Runnable and it’s moved back to runnable thread pool. Dead Once thread finished executing, it’s state is changed to Dead and it’s considered to be not alive. Above are the different states of thread. It’s good to know them and how thread changes it’s state.

Thread Priorities 1. Every Java thread has a priority that helps the operating system

Thread Priorities 1. Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). 2. Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.

public class Thread. Priority extends Thread{ public void run(){ System. out. println(“running thread name

public class Thread. Priority extends Thread{ public void run(){ System. out. println(“running thread name is: ”+Thread. current. Thread(). get. Name()); System. out. println(“running thread priority is: ”+Thread. current. Thread(). get. Priority()); } public static void main(String args[]){ Thread. Priority m 1=new Thread. Priority(); Thread. Priority m 2=new Thread. Priority(); Thread. Priority m 3=new Thread. Priority(); m 1. set. Priority(Thread. MIN-Priority); m 2. set. Priority(Thread. MAX-Priority); m 1. start(); m 2. start(); m 3. start(); } } Output: running thread name is: Thread-1 running thread name is: Thread-2 running thread name is: Thread-0 running thread priority is: 10 running thread priority is: 5

class X extends Thread { public void run() { System. out. println("Thread x Started");

class X extends Thread { public void run() { System. out. println("Thread x Started"); for(int i=0; i<5; i++) { System. out. println("t value of i in Thread x : " + i); } System. out. println("Threadx finished "); } } class Y extends Thread { public void run() { System. out. println("Thread Y started"); for(int i=0; i<5; i++) { System. out. println("t. Value of i in Thread Y : " + i); } System. out. println("Thread. Y Finished"); }}

class Z extends Thread { public void run() { System. out. println("Thread Z started");

class Z extends Thread { public void run() { System. out. println("Thread Z started"); for(int i=0; i<5; i++) { System. out. println("t. Value of i in Thread Z : " + i); } System. out. println("Thread. Z Finished"); } } class Thread. Priority { public static void main(String[] args) { System. out. println("Main thread started"); X thread. X = new X(); Y thread. Y = new Y (); Z thread. Z = new Z ();

 thread. Z. set. Priority(Thread. MAX_PRIORITY); // priority = 10 thread. Y. set. Priority(thread.

thread. Z. set. Priority(Thread. MAX_PRIORITY); // priority = 10 thread. Y. set. Priority(thread. X. get. Priority()+1); // priority = 6 thread. X. set. Priority(Thread. MIN_PRIORITY); // priority =l thread. X. start(); thread. Y. start(); thread. Z. start(); try { thread. X. join(); thread. Y. join(); thread. Z. join(); } catch(Interrupted. Exception e){} System. out. println("Main Thread Finished"); } }

How to create thread There are two ways to create a thread: 1] By

How to create thread There are two ways to create a thread: 1] By extending Thread class 2] By implementing Runnable interface. Thread class: Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class: 1] Thread() 2] Thread(String name) 3] Thread(Runnable r)

Commonly used Constructors of Thread class: 1] Thread() 2] Thread(String name) 3] Thread(Runnable r) 4] Thread(Runnable r, String name) Commonly used methods of Thread class: public void run(): is used to perform action for a thread. public void start(): starts the execution of the thread. JVM calls the run() method on the thread.

public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution)

public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. public void join(): waits for a thread to die. public void join(long miliseconds): waits for a thread to die for the specified miliseconds. public int get. Priority(): returns the priority of the thread. public int set. Priority(int priority): changes the priority of the thread. public String get. Name(): returns the name of the thread. public void set. Name(String name): changes the name of the thread. public Thread current. Thread(): returns the reference of currently executing thread. public int get. Id(): returns the id of the thread.

public Thread. State get. State(): returns the state of the thread. public boolean is.

public Thread. State get. State(): returns the state of the thread. public boolean is. Alive(): tests if the thread is alive. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. public void suspend(): is used to suspend the thread(depricated). public void resume(): is used to resume the suspended thread(depricated). public void stop(): is used to stop the thread(depricated). public boolean is. Daemon(): tests if the thread is a daemon thread. public void set. Daemon(boolean b): marks the thread as daemon or user thread. public void interrupt(): interrupts the thread. public boolean is. Interrupted(): tests if the thread has been interrupted. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface: The Runnable interface should be implemented by any class whose instances are

Runnable interface: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). public void run(): is used to perform action for a thread. Starting a thread: start() method of Thread class is used to start a newly created thread. It performs following tasks: 1. A new thread starts(with new callstack). 2. The thread moves from New state to the Runnable state. 3. When the thread gets a chance to execute, its target run() method will run.

Create a Thread by Extending a Thread Class The second way to create a

Create a Thread by Extending a Thread Class The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. Step 1 You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method − public void run( ) Step 2 Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start( );

Java Thread Example by extending Thread class Multi extends Thread{ public void run(){ System.

Java Thread Example by extending Thread class Multi extends Thread{ public void run(){ System. out. println("thread is running. . . "); } public static void main(String args[]){ Multi t 1=new Multi(); t 1. start(); } } Output: thread is running. . .

Create a Thread by Implementing a Runnable Interface If your class is intended to

Create a Thread by Implementing a Runnable Interface If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps − Step 1 As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method − public void run( ) Step 2 As a second step, you will instantiate a Thread object using the following constructor − Thread(Runnable thread. Obj, String thread. Name); Where, thread. Obj is an instance of a class that implements the Runnableinterface and thread. Name is the name given to the new thread.

Step 3 Once a Thread object is created, you can start it by calling

Step 3 Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Java Thread Example by implementing Runnable interface class Multi 3 implements Runnable{ public void run(){ System. out. println("thread is running. . . "); } public static void main(String args[]){ Multi 3 m 1=new Multi 3(); Thread t 1 =new Thread(m 1); t 1. start(); } } Output: thread is running. . .

If you are not extending the Thread class, your class object would not be

If you are not extending the Thread class, your class object would not be treated as a thread object. So you need to explicitely create Thread class object. We are passing the object of your class that implements Runnable so that your class run() method may execute.

public class Thread. Join extends Thread{ public void run(){ for(int 1=1; i<=3; i++){ Try{

public class Thread. Join extends Thread{ public void run(){ for(int 1=1; i<=3; i++){ Try{ Thread. sleep(500); } Catch(Exception e){ System. out. println(i); } } public static void main(String args[]){ System. out. println(“This is thread join example”); Thread. Join t 1=new Thread. Join(); Thread. Join t 2=new Thread. Join(); Thread. Join t 3=new Thread. Join(); t 1. start(); t 2. start(); t 3. start(); } } Output: This is thread join example 1 2 3 1 1 2 2 3 3

UNIT –VI –Chapter No-02 –Managing I/O v. Streams: Ø A stream is an abstraction

UNIT –VI –Chapter No-02 –Managing I/O v. Streams: Ø A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. Ø All streams behave in the same manner, even if the actual physical devices to which they are linked differ. Thus, the same I/O classes and methods can be applied to different types of devices. Ø This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise, an output stream may refer to the console, a disk file, or a network connection. Ø Streams are a clean way to deal with input/ output without having every part of your code understand the difference between a keyboard and a network, Ø Java defines two types of streams: 1. byte and 2. character.

Ø Byte streams provide a convenient means for handling input and output of bytes.

Ø Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. Ø Character streams provide a convenient means for handling input and output of characters. They use Unicode and, therefore, can be internationalized. Also, in some cases, character streams are more efficient than byte streams. v The Byte Stream Classes Ø Byte streams are defined by using two class hierarchies. At the top are two abstract classes: Input. Stream and Output. Stream. Ø Each of these abstract classes has several concrete subclasses that handle the differences among various devices, such as disk files, network connections, and even memory buffers. Ø The abstract classes Input. Stream and Output. Stream define several key methods that the other stream classes implement. Ø Two of the most important are read( ) and write( ), which, respectively, read and write bytes of data. Ø Each has a form that is abstract and must be overridden by derived stream classes.

v The Character Stream Classes Ø Character streams are defined by using two class

v The Character Stream Classes Ø Character streams are defined by using two class hierarchies. At the top are two abstract classes: Reader and Writer. These abstract classes handle Unicode character streams. Java has several concrete subclasses of each of these. The character stream classes in java. io are shown in following Table Ø The abstract classes Reader and Writer define several key methods that the other stream classes implement. Ø Two of the most important methods are read( ) and write( ), which read and write characters of data, respectively. Ø Each has a form that is abstract and must be overridden by derived stream classes. .

v The Predefined Streams Ø all Java programs automatically import the java. lang package.

v The Predefined Streams Ø all Java programs automatically import the java. lang package. This package defines a class called System, which encapsulates several aspects of the run-time environment. Ø System also contains three predefined stream variables: in, out, and err. These fields are declared as public, static, and final within System. Ø This means that they can be used by any other part of your program and without reference to a specific System object. Ø System. out refers to the standard output stream. By default, this is the console. Ø System. in refers to standard input, which is the keyboard by default. Ø System. err refers to the standard error stream, which also is the console by default. Ø System. in is an object of type Input. Stream; System. out and System. err are objects of type Print. Stream. Ø These are byte streams, even though they are typically used to read and write characters from and to the console

Reading Console Input Ø In Java, console input is accomplished by reading from System.

Reading Console Input Ø In Java, console input is accomplished by reading from System. in. To obtain a characterbased stream that is attached to the console, wrap System. in in a Buffered. Reader object. Buffered. Reader supports a buffered input stream. A commonly used constructor is shown here: Buffered. Reader(Reader input. Reader) Ø Here, input. Reader is the stream that is linked to the instance of Buffered. Reader that is being created. Reader is an abstract class. One of its concrete subclasses is Input. Stream. Reader, which converts bytes to characters. To obtain an Input. Stream. Reader object that is linked to System. in, use the following constructor: Input. Stream. Reader(Input. Stream input. Stream) Ø Because System. in refers to an object of type Input. Stream, it can be used for input. Stream. Putting it all together, the following line of code creates a Buffered. Reader that is connected to the keyboard: Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in)); Ø After this statement executes, br is a character-based stream that is linked to the console through System. in.

Reading Characters Ø To read a character from a Buffered. Reader, use read( ).

Reading Characters Ø To read a character from a Buffered. Reader, use read( ). The version of read( ) that we will be using is int read( ) throws IOException Ø Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns – 1 when the end of the stream is encountered. As you can see, it can throw an IOException.

// Use a Buffered. Reader to read characters from the console. import java. io.

// Use a Buffered. Reader to read characters from the console. import java. io. *; class BRRead { public static void main(String args[]) throws IOException { char c; Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in)); System. out. println("Enter characters, 'q' to quit. "); // read characters do { c = (char) br. read(); System. out. println(c); } while(c != 'q'); } } Here is a sample run: Enter characters, 'q' to quit. 123 abcq 1 2 3 a b c q

Reading Strings Ø To read a string from the keyboard, use the version of

Reading Strings Ø To read a string from the keyboard, use the version of read. Line( ) that is a member of the Buffered. Reader class. Its general form is shown here: String read. Line( ) throws IOException As you can see, it returns a String object. Ø The following program demonstrates Buffered. Reader and the read. Line( ) method; the program reads and displays lines of text until you enter the word "stop": // Read a string from console using a Buffered. Reader. import java. io. *; class BRRead. Lines { public static void main(String args[]) throws IOException { // create a Buffered. Reader using System. in Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in)); String str; System. out. println("Enter lines of text. "); System. out. println("Enter 'stop' to quit. "); do { str = br. read. Line(); System. out. println(str); } while(!str. equals("stop")); } }

Writing Console Output Ø Console output is most easily accomplished with print( ) and

Writing Console Output Ø Console output is most easily accomplished with print( ) and println( ). These methods are defined by the class Print. Stream (which is the type of object referenced by System. out). Ø Even though System. out is a byte stream, using it for simple program output is still acceptable. However, a character-based alternative Ø Because Print. Stream is an output stream derived from Output. Stream, it also implements the low-level method write( ). Thus, write( ) can be used to write to the console. Ø The simplest form of write( ) defined by Print. Stream is shown here: void write(int byteval) Ø This method writes the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written. Here is a short example that uses write( ) to outputthe character "A" followed by a newline to the screen:

// Demonstrate System. out. write(). class Write. Demo { public static void main(String args[])

// Demonstrate System. out. write(). class Write. Demo { public static void main(String args[]) { int b; b = 'A'; System. out. write(b); System. out. write('n'); } } You will not often use write( ) to perform console output (although doing so might be useful in some situations) because print( ) and println( ) are substantially easier to use.

The Print. Writer Class Ø Print. Writer is one of the character-based classes. Using

The Print. Writer Class Ø Print. Writer is one of the character-based classes. Using a character-based class for console output makes internationalizing your program easier. Ø Print. Writer defines several constructors. The one we will use is shown here: Print. Writer(Output. Stream output. Stream, boolean flushing. On) Ø Here, output. Stream is an object of type Output. Stream, and flushing. On controls whether Java flushes the output stream every time a println( ) method (among others) is called. If flushing. On is true, flushing automatically takes place. If false, flushing is not automatic. Ø Print. Writer supports the print( ) and println( ) methods. Thus, you can use these methods in the same way as you used them with System. out. Ø If an argument is not a simple type, the Print. Writer methods call the object’s to. String( ) method and then display the result. Ø To write to the console by using a Print. Writer, specify System. out for the output stream and automatic flushing. Ø For example

// Demonstrate Print. Writer import java. io. *; public class Print. Writer. Demo {

// Demonstrate Print. Writer import java. io. *; public 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); } } The output from this program is shown here: This is a string -7 4. 5 E-7

Applet Fundamentals Java Applet is a special type of program that is embedded in

Applet Fundamentals Java Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side. Advantage of Applet There are many advantages of applet. They are as follows: 1. It works at client side so less response time. 2. Secured 3. It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os etc. Drawback of Applet Plugin is required at client browser to execute applet.

As displayed in the above diagram, Applet class extends Panel class extends Container which

As displayed in the above diagram, Applet class extends Panel class extends Container which is the subclass of Component. Lifecycle of Java Applet 1. Applet is initialized. 2. Applet is started. 3. Applet is painted. 4. Applet is stopped. 5. Applet is destroyed.

Lifecycle methods for Applet: The java. applet. Applet class 4 life cycle methods and

Lifecycle methods for Applet: The java. applet. Applet class 4 life cycle methods and java. awt. Component class provides 1 life cycle methods for an applet. java. applet. Applet class For creating any applet java. applet. Applet class must be inherited. It provides 4 life cycle methods of applet. public void init(): is used to initialized the Applet. It is invoked only once. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized. public void destroy(): is used to destroy the Applet. It is invoked only once.

java. awt. Component class The Component class provides 1 life cycle method of applet.

java. awt. Component class The Component class provides 1 life cycle method of applet. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc. How to run an Applet? There are two ways to run an applet 1. By html file. 2. By applet. Viewer tool (for testing purpose).

Note: class must be public because its object is created by Java Plugin software

Note: class must be public because its object is created by Java Plugin software that resides on the browser. import java. applet. Applet; import java. awt. Graphics; public class First extends Applet { public void paint(Graphics g){ g. draw. String("welcome", 150); } } c: >javac First. java c: >appletviewer First. java

import java. applet. *; import java. awt. *; public class Test 1 extends Applet

import java. applet. *; import java. awt. *; public class Test 1 extends Applet { public void paint(Graphics g) { g. draw. String("Welcome to Java", 100); } }

<html> <head> <title> Applet Program</title> </head> <body BGCOLOR=Green> <center><H 1> Applet</H 1> <Applet code=Test

<html> <head> <title> Applet Program</title> </head> <body BGCOLOR=Green> <center><H 1> Applet</H 1> <Applet code=Test 1. class Height=300 Width=300> </Applet> </center> </body> </html>

import java. applet. *; import java. awt. *; //<Applet code=Test 2 Height=300 Width=300>//</Applet> public

import java. applet. *; import java. awt. *; //<Applet code=Test 2 Height=300 Width=300>//</Applet> public class Test 2 extends Applet { public void paint(Graphics g) { g. draw. String("Welcome to Java", 100); } }

import java. awt. *; import java. awt. event. *; import java. applet. *; /*<applet

import java. awt. *; import java. awt. event. *; import java. applet. *; /*<applet code="p 22" height=200 width=200> </applet>*/ public class p 22 extends Applet implements Action. Listener { Text. Field t 1, t 2, t 3; Label l 1, l 2, l 3, l 4; Choice c; Button b; float s=0; public void init() { l 1=new Label("Frist No. : -"); add(l 1); t 1=new Text. Field(10); add(t 1);

l 2=new Label("Second No. : -"); add(l 2); t 2=new Text. Field(10); add(t 2);

l 2=new Label("Second No. : -"); add(l 2); t 2=new Text. Field(10); add(t 2); l 3=new Label("Result : -"); add(l 3); t 3=new Text. Field(10); add(t 3); b=new Button("OK"); add(b); l 4=new Label("Select Operation to Perform : ");

c=new Choice(); c. add("+"); c. add("-"); c. add("*"); c. add("/"); add(l 4); add(c); b.

c=new Choice(); c. add("+"); c. add("-"); c. add("*"); c. add("/"); add(l 4); add(c); b. add. Action. Listener(this); } public void action. Performed(Action. Event ae) { if(ae. get. Source()==b) { if(c. get. Selected. Item()=="+") { s=Integer. parse. Int(t 1. get. Text())+Integer. parse. Int(t 2. get. Text()); t 3. set. Text(String. value. Of(s)); }

 if(c. get. Selected. Item()=="-") { s=Integer. parse. Int(t 1. get. Text())-Integer. parse. Int(t

if(c. get. Selected. Item()=="-") { s=Integer. parse. Int(t 1. get. Text())-Integer. parse. Int(t 2. get. Text()); t 3. set. Text(String. value. Of(s)); } if(c. get. Selected. Item()=="*") { s=Integer. parse. Int(t 1. get. Text())*Integer. parse. Int(t 2. get. Text()); t 3. set. Text(String. value. Of(s)); } if(c. get. Selected. Item()=="/") { s=Integer. parse. Int(t 1. get. Text())/Integer. parse. Int(t 2. get. Text()); t 3. set. Text(String. value. Of(s)); } }

Note: Browser do not have a Java compiler as a compiled applet file (.

Note: Browser do not have a Java compiler as a compiled applet file (. class file) is given to browser to execute.

Advantages of Applets Vs Applications 1] Execution of applets is easy in a Web

Advantages of Applets Vs Applications 1] Execution of applets is easy in a Web browser and does not require any installation or deployment procedure in realtime programming (where as servlets require). 2] Writing and displaying (just opening in a browser) graphics and animations is easier than applications. 3] In GUI development, constructor, size of frame, window closing code etc. are not required (but are required in applications).

Restrictions of Applets Vs Applications 1] Applets are required separate compilation before opening in

Restrictions of Applets Vs Applications 1] Applets are required separate compilation before opening in a browser. 2] In realtime environment, the bytecode of applet is to be downloaded from the server to the client machine. Applets are treated as untrusted (as they were developed by unknown people and placed on unknown servers whose trustworthiness is not guaranteed) and for this reason they are not allowed, as a security measure, to access any system resources like file system etc. available on the client system. 3] Extra Code is required to communicate between applets using Applet. Context.