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

Size: px
Start display at page:

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

Transcription

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

2 INHERITANCE 2

3 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

4 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

5 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

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; B b; // a is contained in b 6

7 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

8 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

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

10 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

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

12 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

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(); 13

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

15 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

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:

17 INHERITANCE WITH super KEYWORD 17

18 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

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)); 19

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:

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)); 21

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(); 22

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

24 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

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 25

26 Inheritance with Method Overriding 26

27 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

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

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

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 void Room_Super() System.out.println("The Sub Class Room Base is Displayed"); super.room_super(); 30

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 31

32 Inheritance with Abstract Class 32

33 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

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( ); 34

35 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

36 Inheritance with final Keyword 36

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 37

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(); 38

39 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

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

41 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

42 Interface 42

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, class A extends B extends C 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

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

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(); 46

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); 47

48 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

49 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 In Class the variable declaration as well as initialization, but interface only for initializing. 49

50 50

51 51

52 Example 52

53 53

54 54

55 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

56 Interface A B Interface Extension C Interface Implementation D Class 56

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

58 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 = Area of Circle = E:\Programs\javapgm\RUN> 58

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

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); 60

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

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 62

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 63

64 EXCEPTION HANDLING 64

65 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

66 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

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

69 69

70 70

71 71

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

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

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

77 77

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

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) //statements catch(exception-type-2 e) //statements catch(exception-type-n e) //statements 79

80 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

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"); 81

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 82

83 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

84 84

85 85

86 86

87 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

88 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

89 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

90 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

91 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

92 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

93 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

94 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

95 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

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"); 96

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

98 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

99 THREADS 99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120 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

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

UNIT - II Object Oriented Programming - Inheritance

UNIT - II Object Oriented Programming - Inheritance UNIT - II Object Oriented Programming - Inheritance Topics to be Covered: 1. Inheritance 2. Class Hierarchy 3. Polymorphism 4. Dynamic Binding 5. Final Keyword 6. Abstract Classes 7. Object Class 8. Reflection

More information

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

Here is a hierarchy of classes to deal with Input and Output streams. PART 15 15. Files and I/O 15.1 Reading and Writing Files A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data

More information

Unit 5 - Exception Handling & Multithreaded

Unit 5 - Exception Handling & Multithreaded Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

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

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1 Exceptions: An OO Way for Handling Errors Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

More information

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

Unit 4. Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage. Unit 4 Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage. exceptions An exception is an abnormal condition that arises in a code sequence at run time. an

More information

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

ANNA UNIVERSITY OF TECHNOLOGY COIMBATORE B.E./B.TECH DEGREE EXAMINATIONS: NOV/DEC JAVA PROGRAMMING ANNA UNIVERSITY OF TECHNOLOGY COIMBATORE B.E./B.TECH DEGREE EXAMINATIONS: NOV/DEC 2010 080230021-JAVA PROGRAMMING 1. What are the Java Features? 1. Compiled and Interpreted 2. Platform Independent and

More information

Unit III Exception Handling and I/O Exceptions-exception hierarchy-throwing and catching exceptions-built-in exceptions, creating own exceptions, Stack Trace Elements. Input /Output Basics-Streams-Byte

More information

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

C16b: Exception Handling

C16b: Exception Handling CISC 3120 C16b: Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/28/2018 CUNY Brooklyn College 1 Outline Exceptions Catch and handle exceptions (try/catch)

More information

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

INDEX SL.NO NAME OF PROGRAMS PAGE NO REMARKS PROGRAM TO FIND FACTORIAL OF THREE INDEX SL.NO NAME OF PROGRAMS PAGE NO REMARKS PROGRAM TO FIND FACTORIAL OF THREE 1 NUMBERS PROGRAM FOR SUM OF SERIES USING 2 MATHPOWER METHOD 3 PROGRAM ON COMMAND LINE ARGUMENT 4 PROGRAM TO PRINT FIBONACI

More information

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

POLYTECHNIC OF NAMIBIA SCHOOL OF COMPUTING AND INFORMATICS DEPARTMENT OF COMPUTER SCIENCE POLYTECHNIC OF NAMIBIA SCHOOL OF COMPUTING AND INFORMATICS DEPARTMENT OF COMPUTER SCIENCE COURSE NAME: OBJECT ORIENTED PROGRAMMING COURSE CODE: OOP521S NQF LEVEL: 6 DATE: NOVEMBER 2015 DURATION: 2 HOURS

More information

Exceptions Questions https://www.journaldev.com/2167/java-exception-interview-questionsand-answers https://www.baeldung.com/java-exceptions-interview-questions https://javaconceptoftheday.com/java-exception-handling-interviewquestions-and-answers/

More information

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COE318 Lecture Notes Week 10 (Nov 7, 2011) COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.2) Exception Handling 1 Outline Throw Throws Finally 2 Throw we have only been catching exceptions that are thrown by the Java run-time system. However, it

More information

Full file at Chapter 2 - Inheritance and Exception Handling

Full file at   Chapter 2 - Inheritance and Exception Handling Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Data Structures. 02 Exception Handling

Data Structures. 02 Exception Handling David Drohan Data Structures 02 Exception Handling JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.

More information

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

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 Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

More information

Std 12 Lesson-10 Exception Handling in Java ( 1

Std 12 Lesson-10 Exception Handling in Java (  1 Ch-10 : Exception Handling in Java 1) It is usually understood that a compiled program is error free and will always successfully. (a) complete (b) execute (c) perform (d) accomplish 2) In few cases a

More information

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

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling CS115 Pi Principles i of fcomputer Science Chapter 17 Exception Handling Prof. Joe X. Zhou Department of Computer Science CS115 ExceptionHandling.1 Objectives in Exception Handling To know what is exception

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

17. Handling Runtime Problems

17. Handling Runtime Problems Handling Runtime Problems 17.1 17. Handling Runtime Problems What are exceptions? Using the try structure Creating your own exceptions Methods that throw exceptions SKILLBUILDERS Handling Runtime Problems

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions Overview Problem: Can we detect run-time errors and take corrective action? Try-catch Test for a variety of different program situations

More information

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

National University. Faculty of Computer Since and Technology Object Oriented Programming National University Faculty of Computer Since and Technology Object Oriented Programming Lec (8) Exceptions in Java Exceptions in Java What is an exception? An exception is an error condition that changes

More information

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

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING QUESTION BANK DEPARTMENT:EEE SEMESTER: V SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING UNIT V PART - A (2 Marks) 1. What is the difference between super class and sub class? (AUC MAY 2013) The

More information

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

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the Description Exception Handling in Java An Exception is a compile time / runtime error that breaks off the program s execution flow. These exceptions are accompanied with a system generated error message.

More information

Chapter 12 Exception Handling

Chapter 12 Exception Handling Chapter 12 Exception Handling 1 Motivations Goal: Robust code. When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can

More information

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

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition Exceptions, try - catch - finally, throws keyword JAVA Standard Edition Java - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception

More information

Exception-Handling Overview

Exception-Handling Overview م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the

More information

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

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

CSCI 261 Computer Science II

CSCI 261 Computer Science II CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design -

More information

Software Practice 1 - Error Handling

Software Practice 1 - Error Handling Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee 1

More information

Unit III Rupali Sherekar 2017

Unit III Rupali Sherekar 2017 Unit III Exceptions An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception

More information

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

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed 1 1 COMP200 EXCEPTIONS OOP using Java, based on slides by Shayan Javed Exception Handling 2 3 Errors Syntax Errors Logic Errors Runtime Errors 4 Syntax Errors Arise because language rules weren t followed.

More information

6.Introducing Classes 9. Exceptions

6.Introducing Classes 9. Exceptions 6.Introducing Classes 9. Exceptions Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning

More information

Lecture 19 Programming Exceptions CSE11 Fall 2013

Lecture 19 Programming Exceptions CSE11 Fall 2013 Lecture 19 Programming Exceptions CSE11 Fall 2013 When Things go Wrong We've seen a number of run time errors Array Index out of Bounds e.g., Exception in thread "main" java.lang.arrayindexoutofboundsexception:

More information

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

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories Objectives Define exceptions 8 EXCEPTIONS Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions 271 272 Exceptions

More information

Chapter 13 Exception Handling

Chapter 13 Exception Handling Chapter 13 Exception Handling 1 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Interfaces - An Instrument interface - Multiple Inheritance

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch

More information

EXCEPTIONS. Java Programming

EXCEPTIONS. Java Programming 8 EXCEPTIONS 271 Objectives Define exceptions Exceptions 8 Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

Exceptions. CSC207 Winter 2017

Exceptions. CSC207 Winter 2017 Exceptions CSC207 Winter 2017 What are exceptions? In Java, an exception is an object. Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment:

More information

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CSC207H: Software Design. Exceptions. CSC207 Winter 2018 Exceptions CSC207 Winter 2018 1 What are exceptions? Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment: not the usual go-tothe-next-step,

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Exception Handling in Java

Exception Handling in Java Exception Handling in Java The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the runtime errors so that normal flow of the application can be

More information

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Internal Examination 1 Answer Key DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Branch & Sec : CSE Date : 08.08.2014 Semester : V Sem Max Marks : 50 Marks Sub Code& Title : CS2305 Programming Paradigms

More information

Sri Vidya College of Engineering & Technology Question Bank

Sri Vidya College of Engineering & Technology Question Bank 1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.

More information

What are Exceptions?

What are Exceptions? Exception Handling What are Exceptions? The traditional approach Exception handing in Java Standard exceptions in Java Multiple catch handlers Catching multiple exceptions finally block Checked vs unchecked

More information

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

Note: Answer any five questions. Sun micro system officially describes java with a list of buzz words INTERNAL ASSESSMENT TEST I Date : 30-08-2015 Max Marks: 50 Subject & Code: JAVA & J2EE (10IS753) Section : A & B Name of faculty: M V Sreenath Time : 8.30-10.00 AM 1.List and Explain features of Java.

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

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

Exception in thread main java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling. Exceptions 1 Handling exceptions A program will sometimes inadvertently ask the machine to do something which it cannot reasonably do, such as dividing by zero, or attempting to access a non-existent array

More information

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

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

EXCEPTION-HANDLING INTRIVIEW QUESTIONS EXCEPTION-HANDLING INTRIVIEW QUESTIONS Q1.What is an Exception? Ans.An unwanted, unexpected event that disturbs normal flow of the program is called Exception.Example: FileNotFondException. Q2.What is

More information

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

Java Programming MCA 205 Unit - II. Learning Objectives. Introduction. 7/31/2013MCA-205 Java Programming Java Programming MCA 205 Unit - II UII. Learning Objectives Exception Handling: Fundamentals exception types, uncaught exceptions, throw, throw, final, built in exception, creating your own exceptions,

More information

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

F I N A L E X A M I N A T I O N Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student

More information

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

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

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 })); A student adds a JUnit test: To Think About @Test public void mogrifytest() { assertequals("mogrify fails", new int[] { 2, 4, 8, 12 }, MyClass.mogrify(new int[] { 1, 2, 4, 6 })); } The test always seems

More information

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

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University February 11, 2008 / Lecture 4 Outline Course Status Course Information & Schedule

More information

Object Oriented Programming Exception Handling

Object Oriented Programming Exception Handling Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

More information

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)

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) CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers

More information

Chapter 11 Classes Continued

Chapter 11 Classes Continued Chapter 11 Classes Continued The real power of object-oriented programming comes from its capacity to reduce code and to distribute responsibilities for such things as error handling in a software system.

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************

More information

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

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved. Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Chapter 14. Exception Handling and Event Handling ISBN

Chapter 14. Exception Handling and Event Handling ISBN Chapter 14 Exception Handling and Event Handling ISBN 0-321-49362-1 Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction

More information

Selected Java Topics

Selected Java Topics Selected Java Topics Introduction Basic Types, Objects and Pointers Modifiers Abstract Classes and Interfaces Exceptions and Runtime Exceptions Static Variables and Static Methods Type Safe Constants Swings

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

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

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

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

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every

More information

JAVA. Lab-9 : Inheritance

JAVA. Lab-9 : Inheritance JAVA Prof. Navrati Saxena TA- Rochak Sachan Lab-9 : Inheritance Chapter Outline: 2 Inheritance Basic: Introduction Member Access and Inheritance Using super Creating a Multilevel Hierarchy Method Overriding

More information

1 - Basics of Java. Explain features of JAVA.

1 - Basics of Java. Explain features of JAVA. 1 - Basics of Java Explain features of JAVA. Features of java is discussed below: Simple Java was designed to be easy for the professional programmer to learn and use effectively. Java is easy to master.

More information

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

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

16-Dec-10. Consider the following method:

16-Dec-10. Consider the following method: Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to

More information

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

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 7 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 7 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Essential

More information

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?

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? CS6501 - Internet programming Unit- I Part - A 1 Define Java. Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look

More information

CMSC 331 Second Midterm Exam

CMSC 331 Second Midterm Exam 1 20/ 2 80/ 331 First Midterm Exam 11 November 2003 3 20/ 4 40/ 5 10/ CMSC 331 Second Midterm Exam 6 15/ 7 15/ Name: Student ID#: 200/ You will have seventy-five (75) minutes to complete this closed book

More information

Java Programming Language Mr.Rungrote Phonkam

Java Programming Language Mr.Rungrote Phonkam 9 Java Programming Language Mr.Rungrote Phonkam rungrote@it.kmitl.ac.th Contents 1 Exception Handling 1.1. Implicitly Exception 1.2. Explicitly Exception 2. Handle Exception 3. Threads 1 Exception Handling

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract

More information

20 Most Important Java Programming Interview Questions. Powered by

20 Most Important Java Programming Interview Questions. Powered by 20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Ah Lecture Note 29 Streams and Exceptions We saw back in Lecture Note 9 how to design and implement our own Java classes. An object such as a Student4 object contains related fields such as surname,

More information

EXCEPTION HANDLING. Summer 2018

EXCEPTION HANDLING. Summer 2018 EXCEPTION HANDLING Summer 2018 EXCEPTIONS An exception is an object that represents an error or exceptional event that has occurred. These events are usually errors that occur because the run-time environment

More information

Object Oriented Java

Object Oriented Java Object Oriented Java I. Object based programming II. Object oriented programing M. Carmen Fernández Panadero Raquel M. Crespo García Contents Polymorphism Dynamic binding Casting.

More information

Hierarchical abstractions & Concept of Inheritance:

Hierarchical abstractions & Concept of Inheritance: UNIT-II Inheritance Inheritance hierarchies- super and subclasses- member access rules- super keyword- preventing inheritance: final classes and methods- the object class and its methods Polymorphism dynamic

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED

More information

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

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance

More information

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

2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don t have to throw, you can but isn t necessary EXCEPTIONS... 3 3 categories of exceptions:...3 1- Checked exception: thrown at the time of compilation....3 2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don

More information