0% found this document useful (0 votes)
10 views

Java (Chap-2)

Uploaded by

huzaifmanzoor988
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java (Chap-2)

Uploaded by

huzaifmanzoor988
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Java Programming

Course Code: MCA-302-CR


Credits: 4
Scheme: 3 Lectures + 2 Practical per week
Evaluation: Final (80) + Internal (20)
Instructor: Wasim Bhat
Course Objectives
• Chapter 1 [10 Lectures]
– Introduction to Java
– Java language overview
– Java data types, variables and arrays
– Operators, expressions and control statements
• Chapter 2 [10 Lectures]
– Class fundamentals
– Inheritance
– Exception handling
• Chapter 3 [10 Lectures]
– Packages
– Strings
– Threads
– Applets
• Chapter 4 [10 Lectures]
– Event driven programming
– I/O Streams
– Networking classes and interfaces
Chapter - 2
Class Fundamentals
1. Components of class declaration
2. Components of variable declaration
3. Components of method declaration
4. Method overloading and variable hiding
5. Components of constructor declaration
6. Order of execution
Inheritance
7. Inheritance in Java
8. Shadowing & overriding
9. this & super
10. Interfaces
11. Inner classes
Exception Handling
12. Exceptions in Java – Exception object, and catch or specify
13. Checked vs unchecked exceptions
14. Catching an exception - try...catch...finally
15. Nesting
16. Specifying an exception - throws
17. Throwing an exception and custom exceptions
18. Chained exceptions
Study Material
Chapter 2
Class Fundamentals
Components of class declaration
<Access-control modifiers> [Non-access modifiers] class <ClassName>
{
// Body of the class
// Data members
// Member functions or methods
}
Modifiers can be classified into two categories:
1) Access-control modifiers
a) public
i) Any class can instantiate it or inherit it
ii) There can only be one public class per source file and must be named as the name of
the class
b) default
i) The class is public within the package
ii) All classes of the same package can instantiate it or inherit it
c) private
i) Allowed for nested classes only
d) protected
i) Allowed for nested classes only

1 public class MyClass { 1 class MyClass { 1 private class MyClass { 1 protected class MyClass {
2 // Body of the class 2 // Body of the class 2 // Body of the class 2 // Body of the class
3 } 3 } 3 } 3 }
Components of class declaration
1) Access-control modifiers
2) Non-access control modifiers
a) abstract
i) Used to create abstract classes
(a)Defines general structure/skeleton at the top in class hierarchy
(b)Hence, many definitions of data and methods can be skipped
(c)Thus, no objects can be created
(d)May contain one or more declarations of an abstract methods.
(e)Must be sub-classed/extended and then the child class can be instantiated.
(f)Can have abstract methods:
1) If extended, definition of every abstract method be provided
2) If extended by another abstract class, the definition is not required though can
exist.
3) abstract methods can not be private

1 abstract class MyClass { 1 abstract class MyClass {


1 abstract class MyClass {
2 abstract void foo(); 2 abstract void foo();
2 // Body of the class
3 // Body of the class 3 void bar() {}
3 }
4 } 4 }
Components of class declaration
1) Access-control modifiers
2) Non-access control modifiers
a) abstract
b) final
i) Used to declare a class that can not be extended/inherited/sub-classed
(a)Thus, abstract classes can not be final
c) static
i) Nested classes can be static or non-static (inner classes)
ii) static classes can be final
iii) Outer class instance is not needed to instantiate static class

1 public class MyClass1 { 1 public class MyClass2 { 1 final class MyClass {


2 static class YourClass1 {} 2 public static void main(String arg[]) { 2 // Body of the class
3 class YourClass2 {} 3 MyClass1.YourClass objYourClass; 3 }
4 } 4
5 MyClass1 objMyClass = new MyClass1();
6 ObjMyClass.YourClass2 objYourClass2;
7 }
8 }
Components of variable declaration
<Access-control modifiers> [Non-access modifiers] data-type [= <value>];
Modifiers can be classified into two categories:
1) Access-control modifiers
a) public
i) Any class can access or inherit it provided that class can access/inherit its class.
b) default
i) Any class from the same package can access or inherit it provided that class can
access/inherit its class.
c) private
i) Only the methods of the same class can access it.
d) protected
i) Any class that extends its class can access it provided that class can inherit its class.
ii) Any class from the same package can access it provided that class can access its class.

1 public class MyClass1 { 1 class MyClass2 {


2 public int x; 2 public int x;
3 private int y; 3 private int y;
4 protected int z; 4 protected int z;
5 int k; 5 int k;
6 } 6 }
Components of variable declaration
1) Access-control modifiers
2) Non-access control modifiers
a) static
i) Creates one data member for all the instances of the class
1) Hence, it is called Class Variable.
2) Non-static data members are called Instance Variables as each instance of the class
gets its own variable.
3) static data members can also be accessed using class name apart from using objects.
4) Instance variables can only be accessed using objects.
b) final
i) Creates a data member with a constant value.
ii) It should be initialised at the time of declaration
iii) The value can not be changed later on.
iv) Initialisation can also be done in initialisation block or constructors – blank finals
c) transient
i) Skips the data member for persistence during serialisation
d) volatile
i) In multi-threaded and multi-processing systems, the data member avoided from being
cached.
ii) final members can not be volatile.
Components of variable declaration
1 public class MyClass{
2 static int i;
3 final int j=10;
4 transient int k;
5 volatile int l;
6
7 static final int a=10;
8 static final transient int b;
9 static volatile int c;
10 static transient volatile int d;
11 transient volatile int e;
12
13 private static int i;
14 private final int j=10;
15 private transient int k;
16 private volatile int l;
17
18 public static final int aa=10;
19 public static final transient int bb;
20 public static volatile int cc;
21 public static transient volatile int dd;
22 public transient volatile int ee;
23 };
Components of variable declaration
Class Variables Instance Variables Local Variables

a) Default value a) Default value a) Default value


i) 0 for numeric and i) 0 for numeric and i) none
character types character types ii) To be initialised before
ii) Null for rest ii) Null for rest use; otherwise, error
b) Access b) Access b) Access
i) Using class name inside i) Using object inside static i) Only accessible within
non-static method of the method of the same class. block.
same class. ii) directly inside non-static c) Modifiers
ii) directly inside static method of the same class i) NO modifiers apply
method of the same class iii)Using object inside any d) Created when the block or
iii)Using class name inside method of other class. method is executed or called.
any method of other class. c) Modifiers
c) Modifiers i) All modifiers apply
i) All modifiers apply d) Created when the object is 1 public class MyClass1 {
d) Created when the program is created. 2 void foo() {
loaded 1 public class MyClass1 { 3 int i;
2 public int i; 4 }
1 public class MyClass1 { 5 }
3 }
2 static int i;
3 }
Components of method declaration
<Access-control modifiers> [Non-access modifiers] <return-type> <methodName> ([Parameter1]
[,Parameter2])
{
// Body of the method
}
Modifiers can be classified into two categories:
1) Access-control modifiers
a) public
i) Any class can access or inherit it provided that that-class
can access/inherit its class.
b) default
i) Any class from the same package can access or inherit it
provided that class can access/inherit its class.
c) private
1 public class MyClass1 {
i) Only the methods of the same class can access it.
2 public int foo() {
d) protected 3 return 0;
i) Any class that extends its class can access it provided that 4 }
that-class can inherit its class. 5 private void bar(int i) {}
ii) Any class from the same package can access it provided 6 }
that that-class can access its class.

Note:
1. Constructors can be private, default, protected or public.
Components of method declaration
1) Access-control modifiers
2) Non-access control modifiers
a) static
i) Can ONLY access other static methods or static variables of the same class
1) Hence, it is called Class Method.
ii) Can not access instance variables and non-static methods of the same class directly or
using this.
iii) Can not use this or super keyword.
iv) Can be accessed by other static and non-static methods of the same class directly or using
class name.
v) Can be accessed by static and non-static methods of other classes using class name or
object.
b) final
i) Creates a method that can not be over-ridden in sub-class.
ii) final methods are efficient (inline call) – compiler’s discretion.
iii) private methods are by default final.
c) native
i) Allows code written in non-Java language to be used in Java program.
ii) Use javah to compile java source that contains native method to produce c++ header file.
iii) Use javah –stubs to create c++ source template.
iv) Compile the c++ source to shared library and load in java program
I. System.loadLibrary(“LibraryName”);
Components of method declaration
1) Access-control modifiers
2) Non-access control modifiers
a) static
b) final
c) native
d) synchronized
i) A synchronized method blocks if same or other synchronized method of the class is
being executed by any object of the same class.
ii) “Limits the concurrent execution to one method by multiple objects of same class”
iii) static synchronized method blocks on the class while as non-static synchronized
method blocks on the object.
e) abstract
i) abstract method can only be defined in an abstract class.
ii) However, abstract class declaration is enough to declare a class as abstract.
iii)Any combination of non-access modifiers can be used to declare a method except
abstract.
Note:
1. Constructors can not be static or final or native or synchronized or abstract or any
combination of these.
Components of method declaration
1 public class MyClass{
2 static int foo1() {}
3 final int foo2(){}
4 native int foo3(){}
5 synchronized int foo4(){}
6 abstract int foo5();
7
8 static final native synchronized int bar1(){}
9 static final native int bar2(){}
10 static final synchronized int bar3(){}
11 static native synchronized int bar4(){}
12 static synchronized int bar5(){}
13
14 private static final native synchronized int foobar1(){}
15 private static final native int foobar2(){}
16 private static final synchronized int foobar3(){}
17 private static native synchronized int foobar4(){}
18 private static synchronized int foobar5(){}
19 };
Components of method declaration
<Access-control modifiers> [Non-access modifiers] <return-type> <methodName> ([Parameter1]
[,Parameter2])
{// Body of the method}
1) Access-control modifiers
2) Non-access control modifiers
3) Return type
a) Primitive – int, char, boolean, etc.
b) Derived - arrays
c) Object
d) void
4) Parameters
a) Comma separated list of variables with their types 1 public class MyClass1 {
b) No default values 2 public int foo(int a, int… b) {
3 int sum = 0, count = b.length;
c) Type can be
4 for (int i = 0; i < count; i+/))
a) Primitive, which is passed by value 5 sum = sum + p[i];
b) Derived and Object, which are passed by reference 6 return sum;
d) Can be final – value assigned by caller can not be changed.7 }
e) Automatic type-conversion in method-overloading 8 }
a) If the actual parameter type (say int) does not match the
formal parameter type (say float), the actual parameter
is automatically converted
b) Widening conversion
f) Variable number of parameters of same type
a) Should be last parameter
b) (<type> <parameter>, <type>… <parameter>)
Method overloading & variable hiding
1) Method overloading
1) 2 or more methods of same class having
1) same name, and
2) different number of parameters, or
3) same number of parameters but different types, or both 2) and 3).
2) Modifiers and return-type have no role to play in overloading methods.
2) Variable hiding
a) When instance or class variable has same name as that of local variable or parameter, the
instance or class variable is kept hidden by local variable or parameter.
b) To access instance variable in method, use this keyword.
c) To access class variable in method, use super keyword.

1 public class MyClass1 {


2 int a;
3 static int b;
4 public void foo(int a, int b) {
5 a = 10; // access parameter
6 this.a = 10; // access instance variable
7 b = 10; // access parameter
8 MyClass1.b = 10; // access class variable
9 }
10 }
Components of constructor declaration
<Access-control modifiers> <ClassName> ([Parameter1][,Parameter2])
{// Body of the constructor}
1) Method with no return type and same name as name of class
2) Access-control modifiers
a) public
b) default
c) private
d) Protected
3) Overloading
a) Same rules of method overloading apply.
b) Any of the specific overloaded constructor can be called during
instantiation.
4)Can not be overridden.
5) Chaining 1 public class MyClass1 {
a) Calling one constructor from another constructor of the same class. 2 MyClass1() {
3 this(1);
a) Provided multiple overloaded constructors exist.
4 }
b) Calling another constructor should be the first statement of the caller. 5
c) this() is used to call the other constructor. 6 MyClass1(int a) {
d) super() can be used to call any specific constructor of parent class. 7 super();
a) It should be the first statement of the caller. 8 }
b) Thus, either this() or super() can exist in a constructor. 9 };
Components of constructor declaration
<Access-control modifiers> <ClassName> ([Parameter1][,Parameter2])
{// Body of the constructor}
1) Method with no return type and same name as name of class
2) Access-control modifiers
3) Overloading
4) Chaining
5)Default constructor
a) If no constructor is provided then 0-parameter constructor is called by
JVM which calls super().
b) If overloaded constructors are provided and 0-parameter is also
required, it should be explicitly provided.
6)finalize method
a) Approximates destructor
b) Called when the object is to be removed
c) Can not be overloaded
d) Can be overridden
7)Garbage collection 1 public class MyClass1 {
a) Object is not referenced anymore either 2 MyClass1() {}
a) Reference variable is set to null, or 3 protected void finalize() {}
4 };
b) Reference variable goes out of scope
Order of Execution
1) static and non-static blocks
1) Multiple blocks of static and non-static code
can exist in a class
2) Local variables can be defined in both
blocks
3) Textual order of appearance decides the 1 public class MyClass1 {
order of execution for each class of block 2 int a;
3 static int b;
2) Order of execution 4
1) static variables of class, its super class, and 5 static {
6 b = 10;
so on are created.
7 // access only static variables and methods
2) static blocks of class, its super class, and so 8 }
on are executed. 9
3) main() method is executed. 10 {
4) instance variables of class, its super class, 11 a = 10;
12 // access both static and non-static
and so on are created.
13 // variables and methods
5) non-static blocks of class, its super class, 14 }
and so on are executed. 15 MyClass1() {}
6) constructor of class, its super class, and so 16 };
on are executed
Chapter 2
Inheritance
Chapter - 2
Class Fundamentals
1. Components of class declaration
2. Components of variable declaration
3. Components of method declaration
4. Method overloading and variable hiding
5. Components of constructor declaration
6. Order of execution
Inheritance
7. Inheritance in Java
8. Shadowing & overriding
9. this & super
10. Interfaces
11. Inner classes
Exception Handling
12. Exceptions in Java – Exception object, and catch or specify
13. Checked vs unchecked exceptions
14. Catching an exception - try...catch...finally
15. Nesting
16. Specifying an exception - throws
17. Throwing an exception and custom exceptions
18. Chained exceptions
Inheritance in Java
1) Inheritance fundamentals
1) Parent class or super/base-class or inherited class
2) Child class or sub-class or inheriting class
2) Java inheritance principle
a) All visible members are inherited by sub-class
b) This implies:
i) In sub-class, they can be accessed as they were accessed in base-class
ii) In sub-class, they are accessed as if they are its own members
iii)In sub-class, they retain their inherited modifiers
3)Visibility criteria
a) Class
i) public
A. Visible to all classes
ii) default
A. Visible to all classes of same package
b) Member
i) public
A. Visible to all classes
ii) default
A. Visible to all classes of same package
iii)protected
A. Visible to all classes of same package and to other which inherit its class.
iv)private
A. Not visible
Inheritance in Java
<Modifiers> class <ClassName> extends <ClassName>
{
// Body of the class
}

1) Inheritance fundamentals
1 public class MyClass { 1 class MyClass {
2) Java inheritance principle 2 public int a; 2 public int a;
3)Visibility criteria 3 int b; 3 int b;
a) Class 4 protected int c; 4 protected int c;
b) Member 5 private int d; 5 private int d;
4)Keyword 6 }; 6 };
7 7
a) extends
8 // same package class 8 // same package class
9 class MyClass1 extends MyClass { 9 class MyClass1 extends MyClass {
10 //public int a; 10 //public int a;
11 //int b; 11 //int b;
12 //protected int c; 12 //protected int c;
13 }; 13 };
14 14
15 // another package class 15 // another package class can not extend
16 class MyClass2 extends MyClass {
17 //public int a;
18 //protected int c;
19 };
Shadowing & Overriding
1) Inheritance fundamentals
1 public class MyClass {
2) Java inheritance principle 2 public int a;
3)Visibility criteria 3 };
a) Class 4
b) Member 5 // same package class
6 class MyClass1 extends MyClass {
4)Keyword
7 int a;
a) extends 8 void foo() {
5)Shadowing 9 a = 10;
a) Instance or class variables of sub-class can have 10 this.a = 10;
same name as that of inherited variables. 11 super.a = 10;
b) Any direct reference/access to such a name results 12 }
13 };
in access to instance/class variable of sub-class.
a) a=10;
b) this.a=10;
c) To access shadowed variables,
a) super.a=10;
Shadowing & Overriding
1) Inheritance fundamentals
2) Java inheritance principle
3)Visibility criteria
a) Class
b) Member 1 public class MyClass {
4)Keyword 2 void foo() {}
3 void foo(int i) {}
a) extends
4 };
5)Shadowing 5
6) Overriding 6 // same package class
a) Methods of sub-class can have same name and signature as 7 class MyClass1 extends MyClass {
that of inherited methods. 8 void foo() {}
9 public void foo(int i) {}
b) Any direct call to such a name results in access to method of
10 void bar() {
sub-class. 11 foo();
a) foo(); 12 this.foo();
b) this.foo(); 13 super.foo();
c) To access overridden methods, 14 }
a) super.foo(); 15 };
d) Overloaded methods are also overridden.
e) Return-type must match for overridden and overriding
methods.
f) Overriding methods can not be more restrictive than
overridden methods.
a) private -> default -> protected -> public
this & super
this super

1) To refer to current instance of the class 1) To refer to instance of the super class
2) Used in constructor chaining to call overloaded 2) Used in constructor chaining to call overloaded
constructor of the same class from the current constructor of the base class from the current
constructor. constructor.
1) this(1,2,3); 1) super(1,2,3);
3)Used to access instance/class variable hidden by 3)Used to access inherited instance/class variable
the local variable of a method. shadowed by the sub-class variable.
1) this.x=10; 1) super.x=10;
4)Used to call inherited method that is overridden by
the sub-class method.
1) super.foo();
Interfaces
<Modifiers> interface <InterfaceName> [extends <InterfaceName> [,<InterfaceName>]]
{
// Declaration of variables and methods
}
1) Interface basics
1) Interfaces can NOT be instantiated like abstract classes.
1) Pure abstract classes
2) The only applicable access-modifier for interface is either default or public
1) In case of public, source file should be named as that of interface name
3) The only applicable non-access modifier for interface is abstract
1) Interfaces are implicitly abstract
4) Method declarations are implicitly public
1) The only access-modifier applicable is public
2) The class that implements the interface, should provide definition for the
method with public visibility.
5) Variable declarations are implicitly public, final and static
1) Hence, only primitive data types are allowed.
2) Non-blank finals can be initialized by expressions.
6) Interfaces can extend many other interfaces
1) Multiple inheritance
7) A class can implement any number of interfaces and extend one class at the same
time.
Interfaces
<Modifiers> class <ClassName> implements <InterfaceName1> [,<InterfaceName2>]]
{
// Definition of methods declared in the interfaces
}

1) Interface basics
2) Interface implementation
1) An implementing class must provide definition for every method declaration provided by
the interfaces it implements.
2) Two or more interfaces implemented by a class and having multiple method declarations
of same signature need only one definition.
1) Same method declaration signature implies same name, number of parameters, types
of the parameters, and return type.
2) Definition can also be provided by the base-class of the implementing class.
3) Two or more interfaces implemented by a class and having multiple static finals of same
signature can cause ambiguity.
1) Same static final signature implies same name and type.
2) Full-qualification of static finals is needed to resolved the ambiguity in the class
1) Interface1.x=10;
2) Interface2.x=10;
4) Interfaces allow objects of the implementing class to be upcasted to any of its interfaces.
1) Extending a class allows its object to be upcasted to one of its base-classes.
1 interface A {
Interfaces
2 void funcA(); 1 interface A {
3 } 2 int a = 10;
4 interface B extends A { 3 }
5 void funcB(); 4 interface B extends A {
6 } 5 int a = 20;
7 class C implements B { 6 }
8 public void funcA() { 7 class C implements A, B {
9 System.out.println("This is funcA"); 8 void foo() {
10 } 9 System.out.println("A.a: " + A.a);
11 public void funcB() { 10 System.out.println("B.a: " + B.a);
1 interface A {
12 System.out.println("This is funcB"); 11 }
2 void funcA();
13 } 12 }
3 }
14 } 13 public class MyClass {
4 interface B extends A {
15 public class MyClass { 14 public static void main(String args[]) {
5 void funcB();
16 public static void main(String args[]) { 15 C obj = new C();
6 }
17 C obj = new C(); 16 obj.foo();
7 class C implements A, B {
18 obj.funcA(); 17 }
8 public void funcA() {
19 obj.funcB(); 18 }
9 System.out.println("This is funcA");
20 }
10 }
21 }
11 public void funcB() {
12 System.out.println("This is funcB");
13 }
14 }
15 public class MyClass {
16 public static void main(String args[]) {
17 C obj = new C();
18 obj.funcA();
19 obj.funcB();
20 }
21 }
Inner classes
1) Basics
1) A class definition can be placed within another class definition
1) The enclosing class is called Outer Class
2) The nested class is called Inner Class
2) They can be declared with the class body or code block.
3) They behave like normal classes, i.e., they can be instantiated, extended, implement
interface, and so on.
2) Access
1) They can access the members of outer class – including private members.
2) Inner classes can be private, default, protected or public.
3) Outer class can access members of inner class based on access-specifier of the inner class
4) Inner classes can be final, abstract or static.
1) Static inner classes can ONLY access members of outer class using an object
reference to outer class
2) Non-static inner classes can access members of outer class directly.
3) Anonymous inner classes
1) These are inner classes without name
2) They extend an existing class by overriding/adding a method or variable and create an
object of the new class
3) They are extensively used in event-driven programming.
1 class OuterClass {
1 class OuterClass {
2 int x = 10;
2 int x = 10;
3 private class InnerClass {
3 static class InnerClass {
4 int y = 5;
4 int y = 5;
5 }
5 }
6 }
6 }
7 public class Main {
7 public class Main {
8 public static void main(String[] args) {
8 public static void main(String[] args) {
9 OuterClass myOuter = new OuterClass();
9 OuterClass.InnerClass myInner = new OuterClass.InnerClass();
10 OuterClass.InnerClass myInner = myOuter.new InnerClass();
10 System.out.println(myInner.y);
11 System.out.println(myInner.y + myOuter.x);
11 }
12 }
12 }
13 }

1 interface Eatable { 1 abstract class Person {


2 void eat(); 2 abstract void eat();
3 } 3 }
4 class TestAnnonymousInner1 { 4 class TestAnonymousInner {
5 public static void main(String args[]) { 5 public static void main(String args[]) {
6 Eatable e = new Eatable() { 6 Person p = new Person() {
7 public void eat() { 7 void eat() {
8 System.out.println("nice fruits"); 8 System.out.println("nice fruits");
9 } 9 }
10 }; 10 };
11 e.eat(); 11 p.eat();
12 } 12 }
13 } 13 }
Chapter 2
Exception Handling
Chapter - 2
Class Fundamentals
1. Components of class declaration
2. Components of variable declaration
3. Components of method declaration
4. Method overloading and variable hiding
5. Components of constructor declaration
6. Order of execution
Inheritance
7. Inheritance in Java
8. Shadowing & overriding
9. this & super
10. Interfaces
11. Inner classes
Exception Handling
12. Exceptions in Java
13. Checked vs unchecked
14. Catching an exception - try...catch...finally
15. Nesting
16. Specifying an exception - throws
17. Throwing an exception and custom exceptions
18. Chained exceptions
Exceptions in Java
1) Basics
1) Exception is an event (internal or external) which occurs during execution and disrupts the
normal flow of the execution
2) When an exception occurs, the method responsible creates an exception object that
contains information about the type of exception, state of process, etc.
3) This exception object is then delegated to runtime for handling the error/disruption.
4) Creating and handing the exception object to the runtime is called throwing an exception.
5) The runtime attempts to find a handler to handle the exception called Exception Handler
in the call stack.
6) The runtime searches in the reverse order until an appropriate handler is found. This is
called catching an exception.
7) If no appropriate handler is found, JVM provides a default handler which displays the
stack trace BUT immediately exits the program.

2) Catch or Specify
1) Method that throws an exception must either:
1) Catch it by enclosing the statement that throws the exception in try block, and
provide the handler to catch it as catch block. OR
2) Specify that it can throw an exception by publishing a comma delimited list of
exceptions it throws in method declaration using throws so that the method that calls
this method can handle it.
Checked vs Unchecked
1) Checked Exception
1) The program anticipates the exception and can recover from it.
2) As an example, reading a file that does not exist
3) These exceptions are processed at compile time.
4) Therefore, they are subject to catch or specify
5) Examples: ClassNotFoundException, IOException
6) Java programs do not compile if checked exceptions are not either specified or handled.
1) Method should handle it, or
2) Method should specify it, and the caller should handle it.
2) Unchecked Exception
1) The program CANNOT anticipate the exception and CANNOT recover from it.
2) As an example,
3) They are of two types:
1) Error
1) External to application such as I/O device failed during reading/writing
2) Runtime Exception
1) Internal to application such as logical error like division by zero
4) These exceptions are processed at run time.
5) Therefore, they are NOT subject to catch or specify but can be specified and handled to
notify and fix bugs.
6) Examples: NullPointerException, IndexOutOfBoundsException
Checked vs Unchecked

https://www.javacodemonk.com/java-exception-class-hierarchy-92e8224e
Catching an Exception
1) try…catch…finally
1) Java uses try…catch…finally block to catch exceptions.
2) Statement that throws an exception is put in try block.
3) Associated with try block can be 1 or more catch blocks, which is followed by none or
one finally block, OR
4) Associated with try block can be NO catch block, but a mandatory finally block.
5) Associate with each catch block is a specified and unique Exception class of which type
exception object that catch block handles.
1) Therefore, two catch blocks can not specify same exception class.

1 try {
2 // block of code to monitor for errors
3 } catch (ExceptionType1 exOb) {
4 // exception handler for ExceptionType1
5 } catch (ExceptionType2 exOb) {
6 // exception handler for ExceptionType2
7 } finally {
8 // block of code to be executed after try block ends
9 }
Catching an Exception
1) try…catch…finally
2) When exception is raised
1) When an exception is raised in try block, the flow of execution is interrupted,
3) When catch blocks are present
1) The hunt for an appropriate handler begins from the first catch block associated with try
block,
2) The appropriate catch block (handler) is the one whose:
1) Exception class absolutely matches the class of the exception object, or
2) Exception class is super-class of the class of the exception object.
3) If appropriate catch block is found, then
1) A jump from the statement that threw the exception is made to that catch block,
2) The body of the catch block is executed,
3) The preceding and succeeding catch blocks are ignored and not executed,
4) The body of the finally block (if present) is executed,
5) The execution continues to the code that immediately follows the last catch block (if
finally not present) or the finally block (if present).
4) This implies that,
1) The statements in try block that follow the statement that raises exception are never
executed.
2) Only one catch block is executed for an exception.
Catching an Exception
1) try…catch…finally
2) When exception is raised
3) When catch blocks are present
1) If no appropriate catch block is found, then
1) The body of the finally block (if present) is executed,
2) The code following the finally block is not executed,
3) The hunt for appropriate handler continues in the method that called this method
until
1) a handler is found, executed and execution continues from the code that
immediately follows that handler or
2) the default handler is executed and the program terminates.
4) When no catch block is present
1) The hunt for an appropriate handler begins after the execution of finally block
1) In absence of catch block, finally is mandatory.
2) The code following the finally block is not executed,
3) The hunt for appropriate handler continues in the method that called this method until
1) a handler is found, executed and execution continues from the code that immediately
follows that handler or
2) the default handler is executed and the program terminates.
5) When no exception is raised
1) All statements of try block are executed
2) No catch block is executed
3) finally block is certainly executed
6) A return or break or continue in try block ensure that finally is executed before exiting.
Catching an Exception
1 public class MyClass {
2 public static void main(String[] args) {
3 try {
4 int data = 50 / 0; // throws exception
5 // the next statement will not execute
6 System.out.println("Will not execute!");
7 }
8 // Choosing appropriate handler
9 catch (IndexOutOfBoundsException e1) {
10 System.out.println("Not appropriate handler!");
11 } catch (ArithmeticException e2) {
12 System.out.println("Appropriate handler!");
13 } catch (IOException e3) {
14 System.out.println("Appropriate handler but not executed");
15 } finally {
16 System.out.println("Executed whether there is exception or not");
17 }
18 System.out.println("Executed!");
19 }
20 }
Catching an Exception
1 public class MyClass {
2 public static void main(String[] args) {
3 try {
4 int data = 50 / 0; // throws exception
5 // the next statement will not execute
6 System.out.println("Will not execute!");
7 }
8 // No handler
9 finally {
10 System.out.println("Executed whether there is exception or not");
11 }
12 System.out.println(“Not Executed!");
13 }
14 }
Nesting
1) Exceptions can be nested
2) This provides more fine-grained control on exception handling
3) Two possible ways of nesting exist:
1) A try-catch-finally block directly placed inside a try or catch block.
2) A try-catch-finally block in a method is called by another method from a statement in its
try-catch-finally block.
Nesting
1) A try-catch-finally block directly placed inside a try or catch block.

1 public class MyClass {


2 public static void main(String[] args) {
3 try {
4 System.out.println("Executed!");
5 try {
6 int data = 50 / 0; // throws exception
7 // the next statement will not execute
8 System.out.println("Will not execute!");
9 }
10 // Choosing appropriate handler
11 catch (ArithmeticException e1) {
12 System.out.println("Appropriate handler!");
13 } finally {
14 System.out.println("Executed!");
15 }
16 System.out.println("Executed!");
17 }
18 }
19 catch (Exception e2) {
20 System.out.println("Executed if no handler for nested try./catch found!");
21 }
22 System.out.println("Executed!");
23 }
Nesting
1) A try-catch-finally block in a method is called by another method from a statement in its try-
catch-finally block.
1 public class MyClass {
2 public static void main(String[] args) {
3 try {
4 System.out.println("Executed!");
5 foo();
6 System.out.println("Executed!");
7 } catch (Exception e2) {
8 System.out.println("Executed if no handler for nested try./catch found!");
9 }
10 System.out.println("Executed!");
11 }
12 public static void foo() {
13 try {
14 int data = 50 / 0; // throws exception
15 // the next statement will not execute
16 System.out.println("Will not execute!");
17 }
18 // Choosing appropriate handler
19 catch (ArithmeticException e1) {
20 System.out.println("Appropriate handler!");
21 } finally {
22 System.out.println("Executed!");
23 }
24 System.out.println("Executed!");
25 }
26 }
Specifying an exception
<Access-control modifiers> [Non-access modifiers] <return-type> <methodName> ([Parameter1]
[,Parameter2]) [throws <ExceptionName1> [, <ExceptionName2>]
{// Body of the method}
1) Exception need to specified if not handled inside a method.
2) Both checked and unchecked exceptions can be specified,
1) But it mandatory for checked exceptions if they are not handled by the method.
2) However, when such a method is called, caller must handle it.
3) In contrast, if unchecked exceptions are specified, they need not to be handled by caller.
3) A method must declare in its declaration the types of exception it throws.
4) A method can throw many exceptions,
1) A comma delimited list exception it throws appears in the declaration
2) Keyword throws is used to specify the list of exceptions
Specifying an exception
<Access-control modifiers> [Non-access modifiers] <return-type> <methodName> ([Parameter1]
[,Parameter2]) [throws <ExceptionName1> [, <ExceptionName2>]
{// Body of the method}
1 public class MyClass {
2 public static void main(String[] args) {
3 try {
4 System.out.println("Executed!");
5 foo();
6 System.out.println("Executed!");
7 } catch (ArithmeticException e) {
8 System.out.println("Executed!");
9 }
10 System.out.println("Executed!");
11 }
12 public static void foo() throws ArithmeticException {
13 int data = 50 / 0; // throws exception
14 // the next statement will not execute
15 System.out.println("Will not execute!");
16 }
17 }
Throwing an exception
1) An exception can be manually raised using throw keyword.

1 public class MyClass {


2 public static void main(String[] args) {
3 try {
4 //int data = 50 / 0; // throws exception
5 throw new ArithmeticException(); // throws exception
6 // the next statement will not execute
7 System.out.println("Will not execute!");
8 } catch (ArithmeticException e) {
9 System.out.println("Appropriate handler!");
10 } finally {
11 System.out.println("Executed whether there is exception or not");
12 }
13 System.out.println("Executed!");
14 }
15 }
Custom exception
1) Any Exception class can be extended to produced custom exception.
2) The custom exception can of any type depending upon what exception is extended
1) Checked
2) Unchecked
3) In general, toString() method of that the base class is overridden for custom description.
4) Custom exceptions can not be automatically raised, rather they need be thrown manually
1 Class MyException extends ArithmeticException {
2 public String toString() {
3 return "My Arithmetic Exception";
4 }
5
6 public class MyClass {
7 public static void main(String[] args) {
8 try {
9 //int data = 50 / 0; // throws exception
10 throw new MyException(); // throws exception
11 // the next statement will not execute
12 System.out.println("Will not execute!");
13 } catch (ArithmeticException e) {
14 System.out.println("Appropriate handler!/ " + e.toString());
15 }
16 finally {
17 System.out.println("Executed whether there is exception or not");
18 }
19 System.out.println("Executed!");
20 }
21 }
Chained exception
1 public class MyClass {
1) Handler of an exception can 2 public static void main(String[] args) {
throw another exception 3 try {
2) Same rules of hunting and 4 System.out.println("Executed!");
5 try {
control-transfer apply 6 int data = 50 / 0; // throws exception
7 // the next statement will not execute
8 System.out.println("Will not execute!");
9 }
10 // Choosing appropriate handler
11 catch (ArithmeticException e1) {
12 int another_data = 50 / 0; // throws exception
13 // the next statement will not execute
14 System.out.println("Will not execute!");
15 } finally {
16 System.out.println("Executed!");
17 }
18 System.out.println("Will not execute!/");
19 }
20 }
21 catch (ArithmeticException e2) {
22 System.out.println("Executed!");
23 }
24 System.out.println("Executed!");
25 }
Test - 1
Description: “Chapter-2”

Date of submission: 7 days from now

Maximum marks: 05

You might also like