Download presentation
Presentation is loading. Please wait.
Published byYuliani Pranoto Modified over 6 years ago
1
UNIT - V Inheritance Interfaces and inner classes Exception handling
Threads Streams and I/O
2
INHERITANCE
3
INHERITANCE A B 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.
4
Inheritance achieved in two different forms
1. Classical form of Inheritance 2. Containment form of Inheritance Classical form of Inheritance We can now create objects of classes A and B independently. Example: A a; //a is object of A B b; //b is object of B A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class
5
In Such cases, we say that the object b is a type of a
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
6
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; // a is contained in b B b;
7
In such cases, we say that the object a is contained in the object b
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
8
1. Single Inheritance (Only one Super Class and One Only Sub Class)
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
9
2. Multilevel Inheritance (Derived from a Derived Class)
B C 3. Hierarchical Inheritance (One Super class, Many Subclasses) A B C D
10
Single Inheritance (Only one Super Class and One Only Sub Class)
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));
11
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>
12
Multilevel Inheritance (Derived from a Derived Class)
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));
13
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();
14
Output E:\Programs\javapgm\RUN>javac MultilevelMainRoom
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
15
Hierarchical Inheritance (One Super Class, Many Subclasses)
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));
16
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
17
INHERITANCE WITH super KEYWORD
18
The purpose of the ‘super’ keyword:
1. Using super to call Superclass Constructors 2. Using super to call Superclass Methods 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.
19
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));
20
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
21
//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));
22
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();
23
Output E:\Programs\javapgm\RUN>javac MLSuperMainRoom
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
24
//super keyword call Super Class Methods class Room {
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();
25
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
26
Inheritance with Method Overriding
27
1. Method overriding in java means a subclass method overriding a super
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.
28
//Method Overriding class Room { void Room_Super() System.out.println("The Room Base is Displayed"); } class HallRoom extends Room 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();
29
Output E:\Programs\javapgm\RUN>javac moMainRoom
Output E:\Programs\javapgm\RUN>javac moMainRoom.java E:\Programs\javapgm\RUN>java moMainRoom The Sub Class Room Base is Displayed
30
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 System.out.println("The Sub Class Room Base is Displayed"); super.Room_Super();
31
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
32
Inheritance with Abstract Class
33
abstract type name (parameter – list)
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.
34
//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( );
35
Output E:\Programs\javapgm\RUN>javac AbsMainRoom
Output E:\Programs\javapgm\RUN>javac AbsMainRoom.java E:\Programs\javapgm\RUN>java AbsMainRoom B's Implementation of Callme This is a Concrete method
36
Inheritance with final Keyword
37
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
38
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();
39
Output E:\Programs\javapgm\RUN>javac Final2. java Final2
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>
40
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 System.out.println("This is Sub Method"); class Final3 public static void main(String args[]) Sub s = new Sub(); s.Super_Method();
41
Output E:\Programs\javapgm\RUN>javac Final3. java Final3
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>
42
Interface
43
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, 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. class A extends B extends C { }
44
An interface is a blueprint of a class
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.
46
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(); }
47
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);
48
Abstract classes Interfaces
Difference between Abstract Classes and Interfaces Abstract classes Interfaces Abstract classes are used only when there is a “is-a” type of relationship between the classes. Interfaces can be implemented by classes that are not related to one another. You cannot extend more than one abstract class. You can implement more than one interface. it contains both abstract methods and non Abstract Methods Interface contains all abstract methods Abstract class can implemented some methods also. Interfaces can not implement methods.
49
Difference between Classes and Interfaces
Interface is little bit like a class... but interface is lack in instance variables....that's can't create object for it. 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 Interfaces contain only the method declarations.... no definitions 6. In Class the variable declaration as well as initialization, but interface only for initializing.
52
Example
55
Types of Interfaces A B C A B C D E A B C Interface Implementation
Class Extension A B C D E Class Extension Interface Implementation A B C Interface Implementation Class
56
A B C D Interface Implementation Class Extension
57
// HIERARICHICAL INHERITANCE USING INTERFACE interface Area {
final static float pi = 3.14F; float compute (float x,float y); } class Rectangle implements Area public float compute(float x,float y) return (x * y); class Circle implements Area return (pi * x * x); A B C Interface Implementation Class
58
public static void main(String args[])
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>
59
D //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); A B C Interface Implementation Class Extension D
60
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);
61
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>
62
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
63
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
64
EXCEPTION HANDLING
65
- Error means mistakes or bugs - Error is classified into types
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 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 Missing Semicolon Missing brackets in classes and methods 3. Use of undeclared variables Dividing an integer by zero Accessing an element that is out of the bounds of an array
66
Exception is an abnormal condition.
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
67
Exception Types Throwable Exception (or) RuntimeException Error
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
72
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 Asynchronous Exception Synchronous Exception Keyboard Interrupt Mouse Interrupt Division by Zero
73
Catches and handles the
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 Catches and handles the exception Exception object
75
Using try and catch //Block of statements which detects and
try { } catch(Exception_Type e) //Block of statements which detects and //throws an exception //Catches exception //Block of statements that handles the //exception
78
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; System.out.println("The addition of the K2 Value is: " + k2); There is an Exception Catches the exception Output: Division by Zero, The addition of the K2 Value is:10
79
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) catch(Exception-Type-2 e) catch(Exception-Type-N e)
80
public static void main(String args[]) int a[ ] = {5,10}; int b = 5;
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
81
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");
82
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
83
Using finally Statement
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. finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch block. try { //statements } catch(Exception-Type-1 e) catch(Exception-Type-2 e) catch(Exception-Type-N e) finally try { //statements } finally
87
throw You have only been catching exceptions that are thrown by the java run – time system. However, it is possible for your program to throw an exception explicitly. Using throw statement. Syntax: throw ThrowableInstance; Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or char, as well as non – Throwable classes, such as String and Object, cannot be used as exception. There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator.
88
class Error_Handling5 { static void display() try throw new NullPointerException("Demo"); } catch(NullPointerException e) throw e; public static void main(String args[]) display(); 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 Z:\Programs\javapgm\RUN>
89
throws 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. 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. 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. 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
90
static void throwdemo() throws IllegalAccessException
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
91
Java’s Built – in Exceptions
The standard package java.lang, Java defines several exception classes. A few have been used by the preceding examples. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all java programs, most exceptions derived from RuntimeException are automatically available. Furthermore, they 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 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.
92
Java’s Unchecked RuntimeException Subclasses
Meaning ArithmeticException Arithmetic error, such as divde – by – zero ArrayIndexOutOfBoundsException Array index is out – of – bounds. ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid Cast. IllegalArgumentException Illegal argument used to invoke a method IllegalMonitoStateException 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.
93
Exception Meaning NullPointerException Invalid use of a null reference. NumberFormatException Invalid conversion of a string to a numeric format. SecurityException Attempt to violate security StringIndexOutOfBounds Attempt to index outside the bounds of a string. UnsupportedOperationException An unsupported Operation was encountered.
94
Java’s Checked Exception Defined in java.lang
Meaning ClassNotFoundException Class not found CloneNotSupportedException Attempt to clone an object that does not implement the cloneable interface. IllegalAccessException Access to a class is denied InstantiationException Attempt to create an object of an abstract class or interface InterruptedException One thread has been interrupted by another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist.
95
throw new Throwable_subclass;
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: Exception is subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught
96
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");
97
catch(MyException e) { System.out.println("Caught my exception"); System.out.println(e.getMessage()); } finally System.out.println("I am always here");
98
Using Exceptions Exception handling provides a powerful mechanism for controlling complex programs that have many dynamic run – time characteristics. 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. If you are like most programmers, then you probably are used to returning an error code when a method fails. When you are programming in Java, you should break this habit. When a method can fail, have it throw an exception. This is a cleaner way to handle failure modes. One last point: Java’s Exception – handling statements should not be considered a general mechanism for nonlocal branching. If you do so, it will only confuse your code and make it hard to maintain.
99
THREADS
120
MULTI-THREADING IN JAVA
catch(InterruptedException e) PROGRAM: System.out.println("Exception in Thread"); class MultiThread15 extends Thread { String msg; MultiThread15(String str) msg = str; public class MThread15 start(); } public static void main(String arg[]) public void run() MultiThread15 t1 = new MultiThread15("First"); for(int i=1;i<=5;i++) MultiThread15 t2 = new MultiThread15("Second"); System.out.println(msg); try Thread.sleep(1000);
121
STREAMS
122
STREAMS A Stream is a sequence of data. It is composed of bytes. It is basically a channel on which the data flow from sender to receiver. An input object that reads the stream of data from a file is called input stream and the output object that writes the stream of data to a file is called output stream. Java implements streams within the classes that are defined in java.io package. Types of streams Character Stream Byte Stream The two super classes in character stream are Reader and Writer. The two super clasess in byte stream are InputStream and OutputStream from which most of the other classes are derived.
123
I/O HANDLING USING CHARACTER STREAM
Reading Console Input: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Reading Characters from Console: int read( ) throws IOException Example import java.io.*; public class BRRead { public static void main(String args[]) throws IOException char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter characters, 'q' to quit."); // read characters do c = (char) br.read(); System.out.println(c); } while(c != 'q');
124
OUTPUT: Z:\Programs\javapgm\RUN\STREAMS>javac BRRead
OUTPUT: Z:\Programs\javapgm\RUN\STREAMS>javac BRRead.java Z:\Programs\javapgm\RUN\STREAMS>java BRRead Enter characters, 'q' to quit. EEE 2013q E q Z:\Programs\javapgm\RUN\STREAMS>
125
Reading Strings from Console: String readLine( ) throws IOException Example import java.io.*; public class BRReadLines { public static void main(String args[]) throws IOException BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'end' to quit."); do str = br.readLine(); System.out.println(str); } while(!str.equals("end"));
126
OUTPUT: Z:\Programs\javapgm\RUN\STREAMS>javac BRReadLines
OUTPUT: Z:\Programs\javapgm\RUN\STREAMS>javac BRReadLines.java Z:\Programs\javapgm\RUN\STREAMS>java BRReadLines Enter lines of text. Enter 'end' to quit. WELCOME EEE 2013 end hi end Z:\Programs\javapgm\RUN\STREAMS>
127
Writing Console Output: void write(int byteval) Example import java.io.*; // Demonstrate System.out.write(). public class WriteDemo { public static void main(String args[]) int b; b = 'A'; System.out.write(b); System.out.write('\n'); } Output: Z:\Programs\javapgm\RUN\STREAMS>javac WriteDemo.java Z:\Programs\javapgm\RUN\STREAMS>java WriteDemo A
128
READING AND WRITING FILES
OUTPUT STREAM
129
INPUT STREAM
130
I/O HANDLING USING BYTE STREAM
FileInputStream: InputStream f = new FileInputStream(“Z://java//hello"); File f = new File(“Z://java//hello"); InputStream f = new FileInputStream(f); FileOutputStream: OutputStream f = new FileOutputStream(“Z://java//hello") OutputStream f = new FileOutputStream(f);
131
FILEINPUTSTREAM Example 1 import java.io.*; class FileStreamProg { public static void main (String args[]) throws IOException int n; InputStream fobj=new FileInputStream("Z:\\Programs\\javapgm\\RUN\\MThread22.java"); System.out.println("Total Bytes: "+(n=fobj.available())); int m = n-400; System.out.println("\nReading first" +m+ " bytes at a time"); for(int i=0;i<m;i++) System.out.print((char)fobj.read()); System.out.println("\n Skippint some text"); fobj.skip(n/2); System.out.println("\n Still Available: " +fobj.available()); fobj.close(); }
132
Output Z:\Programs\javapgm\RUN\STREAMS>javac FileStreamProg.java
Z:\Programs\javapgm\RUN\STREAMS>java FileStreamProg Total Bytes: 602 Reading first 202 bytes at a time class MultiThread22 extends Thread { String msg; MultiThread22(String str) msg = str; start(); } public void run() for(int i=1;i<=5;i++) Sy Skipping some text Still Available: 99 Z:\Programs\javapgm\RUN\STREAMS>
133
FILEOUTPUTSTREAM Example 1 import java.io.*; class FileOutStreamProg { public static void main (String args[]) throws Exception String text="Welcome to Chettinad \n "+"and Welcome to III EEE"; byte b[] = text.getBytes(); OutputStream fobj = new FileOutputStream("Z:\\Programs\\javapgm\\RUN\\STREAMS\\output.txt"); for(int i=0;i<b.length;i++) fobj.write(b[i]); System.out.println("\n The data is written to the file"); fobj.close(); }
134
Output Z:\Programs\javapgm\RUN\STREAMS>javac FileOutStreamProg
Output Z:\Programs\javapgm\RUN\STREAMS>javac FileOutStreamProg.java Z:\Programs\javapgm\RUN\STREAMS>java FileOutStreamProg The data is written to the file Z:\Programs\javapgm\RUN\STREAMS>type output.txt Welcome to Chettinad and Welcome to III EEE Z:\Programs\javapgm\RUN\STREAMS>
135
FILEOUTPUTSTREAM Example 2 import java.io.*; class FileOutStreamProg2 { public static void main(String args[]) throws Exception FileOutputStream fout = new FileOutputStream("Z:\\Programs\\javapgm\\RUN\\STREAMS\\OOP.txt"); String s = "OBJECT ORIENTED PROGRAMMING"; byte b[] = s.getBytes(); fout.write(b); fout.close(); System.out.println("Success...."); }
136
Output Z:\Programs\javapgm\RUN\STREAMS>javac FileOutStreamProg2
Output Z:\Programs\javapgm\RUN\STREAMS>javac FileOutStreamProg2.java Z:\Programs\javapgm\RUN\STREAMS>java FileOutStreamProg2 Success.... Z:\Programs\javapgm\RUN\STREAMS>type OOP.txt OBJECT ORIENTED PROGRAMMING Z:\Programs\javapgm\RUN\STREAMS>
137
FILEINPUTSTREAM Example 2 import java.io.*; class FileStreamProg2 { public static void main(String args[]) throws Exception FileInputStream fn = new FileInputStream("Z:\\Programs\\javapgm\\RUN\\STREAMS\\OOP.txt"); int i; while((i=fn.read())!= -1) System.out.println((char)i); fn.close(); }
138
Output Z:\Programs\javapgm\RUN\STREAMS>javac FileStreamProg2.java
Z:\Programs\javapgm\RUN\STREAMS>java FileStreamProg2 O B J E C T R I N D P G A M Z:\Programs\javapgm\RUN\STREAMS>
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.