UNIT - V. Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O

Similar documents
CSC 1214: Object-Oriented Programming

UNIT - II Object Oriented Programming - Inheritance

Here is a hierarchy of classes to deal with Input and Output streams.

Unit 5 - Exception Handling & Multithreaded

BBM 102 Introduction to Programming II Spring Exceptions

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Programming II (CS300)

BBM 102 Introduction to Programming II Spring 2017

Programming II (CS300)

Fundamentals of Object Oriented Programming

Unit 4. Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage.

ANNA UNIVERSITY OF TECHNOLOGY COIMBATORE B.E./B.TECH DEGREE EXAMINATIONS: NOV/DEC JAVA PROGRAMMING


Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

C16b: Exception Handling

INDEX SL.NO NAME OF PROGRAMS PAGE NO REMARKS PROGRAM TO FIND FACTORIAL OF THREE

POLYTECHNIC OF NAMIBIA SCHOOL OF COMPUTING AND INFORMATICS DEPARTMENT OF COMPUTER SCIENCE


COE318 Lecture Notes Week 10 (Nov 7, 2011)

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Object Oriented Programming

Full file at Chapter 2 - Inheritance and Exception Handling

More on Exception Handling

Data Structures. 02 Exception Handling

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Std 12 Lesson-10 Exception Handling in Java ( 1

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

More on Exception Handling

17. Handling Runtime Problems

ECE 122. Engineering Problem Solving with Java

National University. Faculty of Computer Since and Technology Object Oriented Programming

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Chapter 12 Exception Handling

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Exception-Handling Overview

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CSCI 261 Computer Science II

Software Practice 1 - Error Handling

Unit III Rupali Sherekar 2017

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

6.Introducing Classes 9. Exceptions

Lecture 19 Programming Exceptions CSE11 Fall 2013

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

Chapter 13 Exception Handling

ITI Introduction to Computing II

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Object Oriented Programming

EXCEPTIONS. Java Programming

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

ITI Introduction to Computing II

Exceptions. CSC207 Winter 2017

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Exception Handling in Java

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Sri Vidya College of Engineering & Technology Question Bank

What are Exceptions?

Note: Answer any five questions. Sun micro system officially describes java with a list of buzz words

CH. 2 OBJECT-ORIENTED PROGRAMMING

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Java Programming MCA 205 Unit - II. Learning Objectives. Introduction. 7/31/2013MCA-205 Java Programming

F I N A L E X A M I N A T I O N

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

1 Shyam sir JAVA Notes

What is Inheritance?

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

Object Oriented Programming Exception Handling

Modern Programming Languages. Lecture Java Programming Language. An Introduction

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Chapter 11 Classes Continued

CS159. Nathan Sprague

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Chapter 5 Object-Oriented Programming

Chapter 14. Exception Handling and Event Handling ISBN

Selected Java Topics

Introduction to Programming Using Java (98-388)

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

JAVA. Lab-9 : Inheritance

1 - Basics of Java. Explain features of JAVA.

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

16-Dec-10. Consider the following method:

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

CMSC 331 Second Midterm Exam

Java Programming Language Mr.Rungrote Phonkam

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Programming II (CS300)

20 Most Important Java Programming Interview Questions. Powered by

School of Informatics, University of Edinburgh

EXCEPTION HANDLING. Summer 2018

Object Oriented Java

Hierarchical abstractions & Concept of Inheritance:

VALLIAMMAI ENGINEERING COLLEGE

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don t have to throw, you can but isn t necessary

Transcription:

UNIT - V Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O 1

INHERITANCE 2

INHERITANCE What is Inheritance? Inheritance is the mechanism which allows a class B to inherit properties/characteristics- attributes and methods of a class A. We say B inherits from A". A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class What are the Advantages of Inheritance 1. Reusability of the code. 2. To Increase the reliability of the code. 3. To add some enhancements to the base class. 3

Inheritance achieved in two different forms 1. Classical form of Inheritance 2. Containment form of Inheritance Classical form of Inheritance A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class Example: We can now create objects of classes A and B independently. A a; B b; //a is object of A //b is object of B 4

In Such cases, we say that the object b is a type of a. Such relationship between a and b is referred to as is a relationship Example 1. Dog is a type of animal 2. Manager is a type of employee 3. Ford is a type of car Employee Teaching Non-Teaching House-Keeping 5

Containment Inheritance We can also define another form of inheritance relationship known as containership between class A and B. Example: class A class B -------- --------- A a; B b; ------------ // a is contained in b 6

In such cases, we say that the object a is contained in the object b. This relationship between a and b is referred to as has a relationship. The outer class B which contains the inner class A is termed the parent class and the contained class A is termed a child class. Example: 1. car has a radio. 2. House has a store room. 3. City has a road. Car object Radio object 7

Types of Inheritance 1. Single Inheritance (Only one Super Class and One Only Sub Class) 2. Multilevel Inheritance (Derived from a Derived Class) 3. Hierarchical Inheritance (One Super Class, Many Subclasses) 1. Single Inheritance (Only one Super Class and Only one Sub Class) A B 8

2. Multilevel Inheritance (Derived from a Derived Class) A B 3. Hierarchical Inheritance (One Super class, Many Subclasses) C A B C D 9

Single Inheritance (Only one Super Class and One Only Sub Class) //Single Inheritance class Room protected int length, breadth; Room() length = 10; breadth = 20; void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom() length = 10; breadth = 20; height = 30; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height)); 10

class SingleMainRoom public static void main(string [] args) HallRoom hr = new HallRoom(); hr.room_area(); hr.hallroom_volume(); Output E:\Programs\javapgm\RUN>javac SingleMainRoom.java E:\Programs\javapgm\RUN>java MainRoom The Area of the Room is:200 The Volume of the HallRoom is:6000 E:\Programs\javapgm\RUN> 11

Multilevel Inheritance (Derived from a Derived Class) //Multilevel Inheritance class Room protected int length, breadth; Room() length = 10; breadth = 20; void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom() length = 10; breadth = 20; height = 30; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height)); 12

class BedRoom extends HallRoom int height_1; BedRoom() length = 10; breadth = 20; height = 30; height_1 = 40; void BedRoom_Volume1() System.out.println("The Volume of the the BedRoom is:" + (length * breadth * height * height_1)); class MultilevelMainRoom public static void main(string [] args) BedRoom br = new BedRoom(); br.room_area(); br.hallroom_volume(); br.bedroom_volume1(); 13

Output E:\Programs\javapgm\RUN>javac MultilevelMainRoom.java E:\Programs\javapgm\RUN>java MultilevelMainRoom The Area of the Room is:200 The Volume of the HallRoom is:6000 The Volume of the the BedRoom is:240000 14

Hierarchical Inheritance (One Super Class, Many Subclasses) //Hierarchical Inheritance class Room protected int length, breadth, height; Room() length = 10; breadth = 20; height = 30; class HallRoom extends Room void HallRoom_Area() System.out.println("The Area of the HallRoom is:" + (length * breadth)); 15

class BedRoom extends Room void BedRoom_Volume() System.out.println("The Volume of the BedRoom is:" + (length * breadth * height)); class HierarchicalMainRoom public static void main(string [] args) HallRoom hr =new HallRoom(); BedRoom br = new BedRoom(); hr.hallroom_area(); br.bedroom_volume(); Output E:\Programs\javapgm\RUN>javac HierarchicalMainRoom.java E:\Programs\javapgm\RUN>java HierarchicalMainRoom The Area of the HallRoom is:200 The Volume of the BedRoom is:6000 16

INHERITANCE WITH super KEYWORD 17

The purpose of the super keyword: 1. Using super to call Superclass Constructors 2. Using super to call Superclass Methods 1. Using super to Call Superclass Constructor A Subclass can call a constructor method defined by its superclass by use of the following form of super: super (parameter list) Here, parameter list specifies any parameter needed by the constructor in the superclass, super() must always be the first statement executed inside a subclass constructor. Restriction of the Subclass constructor 1. super may only be used within a subclass constructor method. 2. The call to superclass constructor must appear as the first statement within the subclass constructor 3. The parameters in the subclass must match the order and type of the instance variable declared in the superclass. 18

class Room protected int length, breadth, height; Room(int length, int breath) this.length = length; this.breadth = breath; void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom(int length, int breath, int height) super(length,breath); this.height = height; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height)); 19

class ssupermainroom public static void main(string [] args) HallRoom hr =new HallRoom(10,20,30); hr.room_area(); hr.hallroom_volume(); Output E:\Programs\javapgm\RUN>javac ssupermainroom.java E:\Programs\javapgm\RUN>java ssupermainroom The Area of the Room is:200 The Volume of the HallRoom is:6000 20

//super keyword in Multilevel Inheritance class Room protected int length, breadth, height; Room(int length, int breath) this.length = length; this.breadth = breath; void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom(int length, int breath, int height) super(length,breath); this.height = height; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height)); 21

class BedRoom extends HallRoom int height_1; BedRoom(int length, int breath, int height, int height_1) super(length,breath,height); this.height_1 = height_1; void BedRoom_Volume_1() System.out.println("The Volume 1 of the BedRoom is:" + (length * breadth * height * height_1)); Class MLSuperMainRoom public static void main(string [] args) BedRoom br =new BedRoom(10,20,30,40); br.room_area(); br.hallroom_volume(); br.bedroom_volume_1(); 22

Output E:\Programs\javapgm\RUN>javac MLSuperMainRoom.java E:\Programs\javapgm\RUN>java MLSuperMainRoom The Area of the Room is:200 The Volume of the HallRoom is:6000 The Volume 1 of the BedRoom is:240000 23

2. Using super to Call Superclass Method //super keyword call Super Class Methods class Room void Room_Super() System.out.println("The Room Base is Displayed"); class HallRoom extends Room void HallRoom_Intermetiate() System.out.println("The Hall Room is Displayed"); class BedRoom extends HallRoom void BedRoom_Sub() super.room_super(); super.hallroom_intermetiate(); 24

System.out.println("The Bed Room is Displayed"); class SuperMethMainRoom public static void main(string [] args) BedRoom br = new BedRoom(); br.bedroom_sub(); Output E:\Programs\javapgm\RUN>javac SuperMethMainRoom.java E:\Programs\javapgm\RUN>java SuperMethMainRoom The Room Base is Displayed The Hall Room is Displayed The Bed Room is Displayed 25

Inheritance with Method Overriding 26

1. Method overriding in java means a subclass method overriding a super class method. 2. Superclass method should be non-static. 3. Subclass uses extends keyword to extend the super class. 4. In the example class B is the sub class and class A is the super class. 5. In overriding methods of both subclass and superclass possess same signatures. 6. Overriding is used in modifying the methods of the super class. 7. In overriding return types and constructor parameters of methods should match. 27

//Method Overriding class Room void Room_Super() System.out.println("The Room Base is Displayed"); class HallRoom extends Room void Room_Super() System.out.println("The Sub Class Room Base is Displayed"); class momainroom public static void main(string [] args) HallRoom br = new HallRoom(); br.room_super(); 28

Output E:\Programs\javapgm\RUN>javac momainroom.java E:\Programs\javapgm\RUN>java momainroom The Sub Class Room Base is Displayed 29

Super Keyword in Method Overriding If your method overrides one of its super class's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). //Super keyword in Method Overriding class Room void Room_Super() System.out.println("The Room Base is Displayed"); class HallRoom extends Room void Room_Super() System.out.println("The Sub Class Room Base is Displayed"); super.room_super(); 30

class mosupermainroom public static void main(string [] args) HallRoom br = new HallRoom(); br.room_super(); Output E:\Programs\javapgm\RUN>javac mosupermainroom.java E:\Programs\javapgm\RUN>java mosupermainroom The Sub Class Room Base is Displayed The Room Base is Displayed 31

Inheritance with Abstract Class 32

Abstract Class You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super class. Thus, a subclass must override them it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form: abstract type name (parameter list) Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. Conditions for the Abstract Class 1. We cannot use abstract classes to instantiate objects directly. For example. Shape s = new Shape(); is illegal because shape is an abstract class. 2. The abstract methods of an abstract class must be defined in its subclass. 3. We cannot declare abstract constructors or abstract static methods. 33

//Abstract Class Implementation abstract class A abstract void callme( ); // Abstract Method void callmetoo( ) // Concrete Method System.out.println("This is a Concrete method"); class B extends A void callme( ) //Redefined for the Abstract Method System.out.println("B's Implementation of Callme"); class AbsMainRoom public static void main(string [] args) B b = new B( ); b.callme( ); b.callmetoo( ); 34

Output E:\Programs\javapgm\RUN>javac AbsMainRoom.java E:\Programs\javapgm\RUN>java AbsMainRoom B's Implementation of Callme This is a Concrete method 35

Inheritance with final Keyword 36

What is the purpose of final keyword? 1. Can t initialize to variable again and again (Equivalent to Constant) 2. Can t Method Overriding 3. Can t Inherited 1. Can t initialize to variable again and again (Equivalent to Constant) class Final1 public static void main(string args[]) final int a = 45; a = 78; //cannot assign the value to final Variable System.out.println("The A Value is:" + a); Output E:\Programs\javapgm\RUN>javac Final1.java Final1.java:7: cannot assign a value to final variable a a = 78; //cannot assign the value to final Variable ^ 1 error 37

2. Can t Method Overriding class Super final void Super_Method() System.out.println("This is Super Method"); class Sub extends Super //Super method in sub cannot override Super_Method() in super; Overridden //method is final void Super_Method() System.out.println("This is Sub Method"); class Final2 public static void main(string args[]) Sub s = new Sub(); s.super_method(); 38

Output E:\Programs\javapgm\RUN>javac Final2.java Final2.java:12: Super_Method() in Sub cannot override Super_Method() in Super; overridden method is final void Super_Method() ^ 1 error E:\Programs\javapgm\RUN> 39

3. Can t Inherited final class Super void Super_Method() System.out.println("This is Super Method"); class Sub extends Super //cannot inherit from final super void Super_Method() System.out.println("This is Sub Method"); class Final3 public static void main(string args[]) Sub s = new Sub(); s.super_method(); 40

Output E:\Programs\javapgm\RUN>javac Final3.java Final3.java:8: cannot inherit from final Super class Sub extends Super //cannot inherit from final super ^ 1 error E:\Programs\javapgm\RUN> 41

Interface 42

Why are you using Interface? 1. Java does not support multiple inheritances. That is, classes in java cannot have more than one superclass. For instances, class A extends B extends C ------------------- ------------------- 2. a is not permitted in Java. However, the designers of java could not overlook the importance of multiple inheritances. 3. A large number of real life applications require the use of multiple inheritances whereby we inherit methods and properties from several distinct classes. 4. Since C++ like implementation of multiple inheritances proves difficult and adds complexity to the language, Java provides an alternate approach known as interfaces to support the concept of multiple inheritances. 5. Although a java class cannot be a subclass or more than one superclass, it can implement more than one interface, thereby enabling us to create classes that build upon other classes without the problems created by multiple inheritances. 43

An interface is a blueprint of a class. It has static constants and abstract methods. The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the interface. As shown below, a class extends another class, an interface extends another interface but a class implements an interface. 44

45

Defining Interfaces An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with major difference. The difference is that interfaces define only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contain only constants. Syntax: interface Interface_name Variable declaration; Method declaration; Ex: interface Item static final int code = 1001; static final String name = CCET ; void display (); Ex: interface Area final static float pi = 3.142F; float compute (float x,float y); void show(); 46

How to Interface implements to the Classes Syntax: class class_name implements interface_name //Member of the Classes //Definition of the Interfaces Ex: interface student int slno = 12345; String name = "CCET"; void print_details(); class Inter_Def implements student void print_details() System.out.println("The Serial Number is:" + slno); System.out.println("The Student name is:" + name); 47

Difference between Abstract Classes and Interfaces Abstract classes Abstract classes are used only when there is a is-a type of relationship between the classes. You cannot extend more than one abstract class. it contains both abstract methods and non Abstract Methods Abstract class can implemented some methods also. Interfaces Interfaces can be implemented by classes that are not related to one another. You can implement more than one interface. Interface contains all abstract methods Interfaces can not implement methods. 48

Difference between Classes and Interfaces 1. Interface is little bit like a class... but interface is lack in instance variables...that's can't create object for it. 2. Interfaces are developed to support multiple inheritances. 3. The methods present in interfaces are pure abstract. 4. The access specifiers public, private, protected are possible with classes. But the interface uses only one specifier public 5. Interfaces contain only the method declarations... no definitions... 6. In Class the variable declaration as well as initialization, but interface only for initializing. 49

50

51

Example 52

53

54

Types of Interfaces A Interface Implementation A Class D Interface B Class Extension B Extension Implementation Class E Extension Interface C Class Extension C Class A Interface Implementation B Class C Class 55

Interface A B Interface Extension C Interface Implementation D Class 56

// HIERARICHICAL INHERITANCE USING INTERFACE interface Area final static float pi = 3.14F; float compute (float x,float y); A Implementation Interface class Rectangle implements Area public float compute(float x,float y) return (x * y); B Class C Class class Circle implements Area public float compute(float x,float y) return (pi * x * x); 57

class HInterfaceTest public static void main(string args[]) Rectangle rect = new Rectangle (); Circle cir = new Circle(); Area area; //Interface object //Area area = new Rectangle(); area = rect; System.out.println("Area of Rectangle = " + area.compute(10,20)); //Area area1 = new Circle(); area = cir; System.out.println("Area of Circle = " + area.compute(10,0)); Output E:\Programs\javapgm\RUN>javac HInterfaceTest.java E:\Programs\javapgm\RUN>java HInterfaceTest Area of Rectangle = 200.0 Area of Circle = 314.0 E:\Programs\javapgm\RUN> 58

//HYBRID INHERITANCE USING INTERFACES class Student int rollnumber; void getnumber(int n) rollnumber = n; void putnumber() System.out.println("Roll No: " + rollnumber); class Test extends Student float sub1, sub2; void getmarks(float m1,float m2) sub1 = m1; sub2 = m2; void putmarks() System.out.println("Marks obtained"); System.out.println( Subject1 = " + sub1); System.out.println( Subject2 = " + sub2); Class Extension Class Extension Class A B C Interface D Implementation 59

interface Sports float sportwt = 6.0F; void putwt(); class Results extends Test implements Sports float total; public void putwt() System.out.println("Sports Wt = " + sportwt); void display() total = sub1 + sub2 + sportwt; putnumber(); putmarks(); putwt(); System.out.println("Total Score = " + total); 60

class InterfaceHybrid public static void main(string args[]) Results stud = new Results(); stud.getnumber(1234); stud.getmarks(27.5f, 33.0F); stud.display(); Output E:\Programs\javapgm\RUN>javac InterfaceHybrid.java E:\Programs\javapgm\RUN>java InterfaceHybrid Roll No: 1234 Marks obtained Subject1 = 27.5 Subject2 = 33.0 Sports Wt = 6.0 Total Score = 66.5 E:\Programs\javapgm\RUN> 61

What is Partial Implementation? The Interface is implementation to the Abstract class is called Partial Implementation. Example: interface Partial_Interface public void display_one(); abstract class Abstract_Class implements Partial_Interface public void display_one() //Definition for the Interface Method System.out.println("This is Interface Method"); void display_two() //Concrete Method System.out.println("This is Concrete Method"); abstract void display_three(); //Abstract Method 62

class Pure_Class extends Abstract_Class void display_three() //Definition for the Abstract Method System.out.println("This is Abstract Method"); class Final public static void main(string args[]) Pure_Class pc = new Pure_Class(); pc.display_one(); pc.display_two(); pc.display_three(); Output E:\Programs\javapgm\RUN>javac Final.java E:\Programs\javapgm\RUN>java Final This is Interface Method This is Concrete Method This is Abstract Method 63

EXCEPTION HANDLING 64

What is Error? - Error means mistakes or bugs - Error is classified into types Error Compile Time Error Run 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 A program may compile success fully creating the.exe file but not run properly. Such programs may produce wrong results due to wrong logic or may terminate due to errors 1. Dividing an integer by zero 2. Accessing an element that is out of the bounds of an array 65

Exception Handling Exception is an abnormal condition. It provides the mechanism to handle the runtime errors. It is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. Example 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 66

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

68

69

70

71

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 Asynchronous Exception 1. Division by Zero 1. Keyboard Interrupt 2. Mouse Interrupt 72

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 73

74

Using try and catch ------------------ ------------------ try ------------- ------------- ------------- catch(exception_type e) -------------- -------------- ------------------ ------------------ //Block of statements which detects and //throws an exception //Catches exception //Block of statements that handles the //exception 75

76

77

Example Program for Exception Handling Mechanism class Error_Handling1 public static void main(string args[]) int i,j,k1,k2; i = 10; j = 0; try k1 = i / j; System.out.println("The Division of the K1 Value is: " + k1); catch(arithmeticexception e) System.out.println("Division by Zero"); k2 = i + j; There is an Exception Catches the exception System.out.println("The addition of the K2 Value is: " + k2); Output: Division by Zero, The addition of the K2 Value is:10 78

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 79

class Error_Handling2 public static void main(string args[]) int a[ ] = 5,10; int b = 5; try int x = a[2] / b - a[1]; catch(arithmeticexception e) System.out.println("Division by Zero"); catch(arrayindexoutofboundsexception e) System.out.println("Array Index Error"); catch(arraystoreexception e) System.out.println("Wrong data type"); int y = a[1] / a[0]; System.out.println("Y = " + y); E:\Programs\javapgm\RUN>javac Error_Handling2.java E:\Programs\javapgm\RUN>java Error_Handling2 Array Index Error Y = 2 80

COMMON EXCEPTION HANDLER class Error_Handling3 public static void main(string args[]) int a[ ] = 5,10; int b = 5; try int x = a[2] / b - a[1]; catch(arithmeticexception e) System.out.println("Division by Zero"); /*catch(arrayindexoutofboundsexception e) System.out.println("Array Index Error"); */ catch(arraystoreexception e) System.out.println("Wrong data type"); 81

catch(exception e) System.out.println("The Producing any Runtime Error" + e.getmessage()); int y = a[1] / a[0]; System.out.println("Y = " + y); Output E:\Programs\javapgm\RUN>javac Error_Handling3.java E:\Programs\javapgm\RUN>java Error_Handling3 The Producing any Runtime Error2 Y = 2 82

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 finally //statements ------------------- ------------------- try //statements catch(exception-type-1 e) //statements catch(exception-type-2 e) //statements ----------- ----------- catch(exception-type-n e) //statements finally ------------------- ------------------- 83

84

85

86

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 ThrowableInstance; 1. Here, ThrowableInstance 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. 87

Z:\Programs\javapgm\RUN> class Error_Handling5 static void display() try throw new NullPointerException("Demo"); catch(nullpointerexception e) throw e; public static void main(string args[]) try display(); catch(nullpointerexception e) System.out.println("Recaught : " + e); Output Z:\Programs\javapgm\RUN>javac Error_Handling5.java Z:\Programs\javapgm\RUN>java Error_Handling5 Recaught : java.lang.nullpointerexception: Demo 88

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 RuntimeException, 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 89

class Error_Handling6 static void throwdemo() throws IllegalAccessException System.out.println("Inside throw demo"); public static void main(string args[]) try throwdemo(); catch(illegalaccessexception e) System.out.println("Caught " + e); Output Z:\Programs\javapgm\RUN>javac Error_Handling6.java Z:\Programs\javapgm\RUN>java Error_Handling6 Inside throwdemo 90

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 RuntimeException. 3. Since java.lang is implicitly imported into all java programs, most exceptions derived from RuntimeException 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. 91

Java s Unchecked RuntimeException Subclasses Exception Meaning ArithmeticException Arithmetic error, such as divde by zero ArrayIndexOutOfBoundsException ArrayStoreException ClassCastException IllegalArgumentException IllegalMonitoStateException Array index is out of bounds. Assignment to an array element of an incompatible type. Invalid Cast. Illegal argument used to invoke a method Illegal Monitor Operation, such as waiting on an unlocked thread. IllegalStateException Environment or application is in incorrect state. IllegalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out of bounds NegativeArraySizeException Array Created with a negative size. 92

Exception NullPointerException NumberFormatException SecurityException Meaning Invalid use of a null reference. Invalid conversion of a string to a numeric format. Attempt to violate security StringIndexOutOfBounds Attempt to index outside the bounds of a string. UnsupportedOperationException An unsupported Operation was encountered. 93

Java s Checked Exception Defined in java.lang Exception ClassNotFoundException Class not found Meaning CloneNotSupportedException IllegalAccessException InstantiationException InterruptedException NoSuchFieldException NoSuchMethodException Attempt to clone an object that does not implement the cloneable interface. Access to a class is denied Attempt to create an object of an abstract class or interface One thread has been interrupted by another thread. A requested field does not exist. A requested method does not exist. 94

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 ArithmeticException(); throw new NumberFormatException(); Note: 1. Exception is subclass of Throwable and therefore MyException is a subclass of Throwable class. 2. An object of a class that extends Throwable can be thrown and caught 95

import java.lang.exception; class MyException extends Exception MyException(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 MyException("Number is too small"); 96

catch(myexception e) System.out.println("Caught my exception"); System.out.println(e.getMessage()); finally System.out.println("I am always here"); 97

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

THREADS 99

MULTI-THREADING IN JAVA PROGRAM: class MultiThread15 extends Thread String msg; MultiThread15(String str) msg = str; start(); public void run() for(int i=1;i<=5;i++) System.out.println(msg); try Thread.sleep(1000); catch(interruptedexception e) System.out.println("Exception in Thread"); public class MThread15 public static void main(string arg[]) MultiThread15 t1 = new MultiThread15("First"); MultiThread15 t2 = new MultiThread15("Second"); 120