Cos 201- Comp Programming Class Ii_101042
Cos 201- Comp Programming Class Ii_101042
COMPUTER
PROGRAMMING
II
MISS OYEWOLE C.B
PACKAGE
A Package can be defined as a grouping of related types(classes, interfaces). Java provides many
classes grouped into different packages based on their functionality.
The classes contained in the packages of other programs/applications can be reused. There are
two types of packages in Java namely;
1. Pre-defined Packages(built-in): these packages consist of include classes which are a
part of Java API (Application Program Interface).
2. User defined packages
Pre-defined package include java.lang, java.io, java.util, java.applet, java.awt, java.net,
javax.swing and java.sql
Java.lang: Contains language support classes (for e.g classes which defines primitive data
types, math operations, etc.). This package is automatically imported.
Java.io: Contains classes for supporting input / output operations.
Java.util: Contains utility classes which implement data structures like Linked List, Hash
Table, Dictionary, etc and support for Date / Time operations. This package is also called as
Collections.
PRE-DEFINED PACKAGE-
CONT’D
Java.applet: Contains classes for creating Applets.
Java.awt: Contains classes for implementing the components of graphical user interface
( like buttons, menus, etc. ).
Java.net: Contains classes for supporting networking operations.
Javax.swing: This package helps to develop GUI Applications. The ‘x’ in javax represents
that it is an extended package which means it is a package developed from another package
by adding new features to it. In fact, javax.swing is an extended package of java.awt.
Java.sql: This package helps to connect to databases like Oracle/Sybase/Microsoft Access to
perform different operations.
JAVA FOUNDATION
PACKAGES
HOW TO ACCESS PACKAGE
FROM ANOTHER PACKAGE
To use a class or a package from the Java API, the keyword import should be used. The
import keyword is used to make the classes and interface of another package accessible to the
current package.
There are three ways to access the package from outside the package;
Using packagename*: To import a whole package, end the sentence with an asterisk sign
(*). The following example will import all the classes and interfaces in the java.util
package but not subpackages:
To import. java.util. *;
ACCESSING CLASSES INSIDE
A PACKAGE
Import/calling a specific class by using packagename.classname: which means only declared
class of this package will be accessible. E.g
Import java.util.Vector;
This imports only the vector class from the java.util package
Using fully qualified name
If you use fully qualified name, then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
USER-DEFINED PACKAGE
These are packages defined by the user.
User defined package is achieved by including a package command as the first statement in a
Java source file. Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored. If you omit the
package statement, the class names are put into the default /package, which has no name.
General form of defining a package;
package pkg;
package major;
HOW TO DEFINE A USER-DEFINED PACKAGE
package p1;
class c1
{
public void m1()
{
System.out.println("m1 of c1");
}
public static void main(string
args[])
{
c1 obj = new c1();
obj.m1();
}
}
ASSIGNMENT
Write out 10 classes in pre-defined package
Write on Recursive algorithm
EXCEPTION 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 terminates abnormally, which is not recommended, therefore,
these exceptions are to be handled.
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO,
SQL, Remote etc.
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is why
we use exception handling. Let's take a scenario:
1. Code 1;
2. Code 2;
3. Code 3;
4. Code 4; // exception occurs
5. Code 5;
6. Code 6;
7. Code 7;
EXCEPTION HANDLING
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is
why we use exception handling. Let's take a scenario:
1. Code 1;
2. Code 2;
3. Code 3;
4. Code 4; // exception occurs
5. Code 5;
6. Code 6;
7. Code 7;
It is an unexcepted problem that happens while your program is running. For example;
Trying to divide a number by zero
When such problems occur, java creates an exception object that contains
information about the error.
TYPES OF EXCEPTION
There are mainly two types of exceptions which includes:
Checked
Unchecked exception
Checked Exception: These are exceptions that are checked at compile-time. Examples
include `IOException` and `SQLException`. They are problems that java forces you to
handle before your program can run. The java complier checks at compile time whether
you’ve handled these exceptions. It can be handled by using try-catch block to handle
the exception and by declaring the exception using the throws keyword in the method
signature. Example such: Trying to read a file that doesn’t exsit (FileNotFoundException)
Unchecked Exception: they are problems that occur due to logical errors in your code.
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
TYPES OF EXCEPTION
Error: Error is irrecoverable i.e they are usually beyond your control and
cannot be handled by your program. They often occur at the ystem level
and are not meant to be caught or handled by your code. e.g. Running out
of memory (OutOfMemoryError) , VirtualMachineError, AssertionError etc
SUMMARY OF EXCEPTION
TYPE
TYPES CHECKED/ CAUSED BY EXAMPLE
UNCHECKED
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
HIERARCHY OF JAVA
EXCEPTION CLASSES
HIERARCHY OF JAVA
EXCEPTION CLASSES
In Java, exceptions are events that disrupt the normal flow of a program's instructions. The
hierarchy of Java exception classes is rooted in the `Throwable` class, which is the superclass
of all errors and exceptions in the Java language. Here's a detailed explanation of the
hierarchy:
Throwable: This is the root class for all exceptions and errors in Java. It provides a way to
capture the state of the program when an exception or error occurs, including a stack trace
and a message.
Exception: This class and its subclasses represent conditions that a reasonable application
might want to catch. Exceptions are divided into two main categories.
Checked Exceptions: These are exceptions that are checked at compile-time. They must be
either caught or declared to be thrown. Examples include `IOException` and `SQLException`.
Error: This class and its subclasses represent serious problems that a reasonable
application should not try to catch. Errors are typically used to indicate issues with
the Java Virtual Machine (JVM) itself or the environment in which the application is
running. Examples include `VirtualMachineError` and `AssertionError`.
VirtualMachineError: This indicates that the JVM is broken or has run out of
resources necessary for it to continue operating.
try
{
statement 1;
statement 2;
try
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{}
.....
JAVA NESTED TRY EXAMPLE
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
JAVA FINALLY BLOCK
Java finally block is a block that is used to execute important code such as
closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block
JAVA FINALLY BLOCK
USAGE OF JAVA FINALLY
Let’s see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
USAGE OF JAVA FINALLY
Case 2 Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
USAGE OF JAVA FINALLY
Case 3: Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
JAVA THROW EXCEPTION
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom exception. We
will see custom exceptions later.
The syntax of java throw keyword is given below.