Chapter 3
Chapter 3
Package,
Multithreading,
Exception Handling
Prepared by : Asst. Prof Priya Patel
Packages
A package as the name suggests is a pack(group) of classes,
interfaces and other packages. In java we use packages to
organize our classes and interfaces.
A package in Java is used to group related classes. Think of it
as a folder in a file directory. We use packages to avoid name
conflicts, and to write a better maintainable code. Packages
are divided into two categories:
✔ Built-in Packages (packages from the Java API)
✔ User-defined Packages (create your own packages)
Packages
Packages-Built-in Packages (packages from the Java API) :
✔The Java API is a library of prewritten classes, that are free to use,
included in the Java Development Environment.
✔The library contains components for managing input, database
programming, and much much more.
✔The library is divided into packages and classes. Meaning you can
either import a single class (along with its methods and attributes), or a
whole package that contain all the classes that belong to the specified
package.
✔To use a class or a package from the library, you need to use
the import keyword:
Packages
Syntax
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Example:
Import a Class
√ If you find a class you want to use, for example,
the Scanner class, which is used to get user input, write the following
code:
import java.util.Scanner;
Example
Using the Scanner class to get user input:
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}
Packages
Import a Package
✔ There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package
also contains date and time facilities, random-number generator and other utility classes.
✔ To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in
the java.util package:
Syntax:
import java.util.*;
Example:
import java.util.*; // import the java.util package
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
These are the reasons why you should use packages in Java:
✔ Reusability: While developing a project in java, we often feel
that there are few things that we are writing again and again in
our code. Using packages, you can create such things in form of
classes inside a package and whenever you need to perform that
same task, just import that package and use the class.
✔ Name Conflicts: We can define two classes with the same name
in different packages so to avoid name collision, we can use
packages
How to access package from another package?
class A
{
private A()
{}//private constructor
void msg()
{
System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Access Modifier
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Exception Handling in Java
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.
In this page, we will learn about Java exceptions, its type and the
difference between checked and unchecked exceptions.
What is Exception in Java
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Exception Handling
Advantage of Exception Handling
in Java
The core advantage of exception handling is to maintain the normal flow of
the application. An exception normally disrupts the normal flow of the
application that is why we use exception handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an
exception at statement 5, the rest of the code will not be executed i.e.
statement 6 to 10 will not be executed. If we perform exception handling,
the rest of the statement will be executed. That is why we use exception
handling in Java.
Hierarchy of java
exception classes
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an
error is considered as the unchecked exception. According to Oracle, there
are three types of exceptions:
✔ Checked Exception
✔ Unchecked Exception
✔ Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
✔ The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
✔ The classes which inherit RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
3) Error
✔ Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
Java Exception Keywords
Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally.
It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed
by finally block later.
finally The "finally" block is used to execute the important code of the program.
It is executed whether an exception is handled or not.
OUTPUT :
OUTPUT :
OUTPUT :
OUTPUT :
synchronized(mutex)
{
System.out.println("synchronized block");
}
}
NumberFormatException
A Java NumberFormatException usually occurs when you try to do
something like convert a String to a numeric value, like an int, float, double,
long, etc
NumberFormatException example
package com.devdaily.javasamples;
public class ConvertStringToNumber
{
public static void main(String[] args)
{
try
{
// intentional error String s = "FOOBAR";
int i = Integer.parseInt(s);
catch(NumberFormatException nfe)
{
nfe.printStackTrace();
}
}
}
Array IndexOutOfBound Exception
• ArrayIndexOutOfBoundsException is thrown to indicate
that we are trying to access array element with an illegal
index.
•This exception is thrown when the index is either negative
or greater than or equal to the size of the array.
ArrayIndexOutOfBounds Exception Example
package com.journaldev.exceptions;
import java.util.Scanner;
public class ArrayIndexOutOfBoundsExceptionExample
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of int array:");
int size = sc.nextInt();
int[] intArray = new int[size];
for (int i = 0; i < size; i++)
{
System.out.println("Please enter int value at index " + i + ":");
intArray[i] = sc.nextInt();
}
System.out.println("Enter array index to get the value:");
int index = sc.nextInt();
sc.close();
System.out.println("Value at " + index + " = " + intArray[index]);
}
}
OUTPUT :
• The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
public class TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
Output:
Output:
java.lang.ArithmeticException: / by zero rest of the code
Example 3
In this example, we also kept the code in a try block that will not throw an
exception.
public class TryCatchExample3
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
// if exception occurs,
//the remaining statement will not exceute
}
}
}
catch multiple exceptions
A try block can be followed by one or more catch blocks. Each catch
block must contain a different exception handler. So, if you have to
perform different tasks at the occurrence of different exceptions,
use java multi-catch block.
Points to remember
At a time only one exception occurs and at a time only one catch
block is executed.
All catch blocks must be ordered from most specific to most
general, i.e. catch for ArithmeticException must come before catch
for Exception.
Example
public class MultipleCatchBlock1 1 Output:
{
public static void main(String[] args)
{
try{ Arithmetic Exception occurs
int a[]=new int[5]; rest of the code
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Example 2
public class MultipleCatchBlock2 { Output:
public static void main(String[] args) { ArrayIndexOutOfBounds Exception occurs
try{ rest of the code
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Example 3
In this example, try block contains two exceptions. But at a time only one
exception occurs and its corresponding catch block is invoked.
public class MultipleCatchBlock3 catch(Exception e)
{ {
public static void main(String[] args) { System.out.println("Parent Exception o
ccurs");
try{ }
int a[]=new int[5]; System.out.println("rest of the code");
a[5]=30/0;
System.out.println(a[10]); }
} }
catch(ArithmeticException e)
{ Output:
System.out.println("Arithmetic Excep
tion occurs"); Arithmetic Exception occurs rest of the
} code
catch(ArrayIndexOutOfBoundsException
e){
System.out.println("ArrayIndexOutOfBo
unds Exception occurs");
}
Java Nested try block
The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and
the entire block itself may cause another error. In such cases, exception handlers
have to be nested.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Java
class Excep6{
nested try example
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 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.
throw exception;
Output:
import java.io.*;
class M{ Output: device operation
void method()throws IOException{ performed normal flow...
System.out.println("device operation per
formed");
}
}
class Testthrows3{
public static void main(String args[])thr
ows IOException
{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
} }
B)Program if exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])thro
ws IOException
{ //declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:Runtime Exception
Difference between throw and throws in Java
No. throw throws
1) Java throw keyword is used to explicitly Java throws keyword is used to
throw an exception. declare an exception.
4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple exceptions. You can declare multiple
exceptions e.g.
public void method()throws
IOException,SQLException.
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.
Why use java finally
Finally block in java can be used to put "cleanup" code such as
closing a file, closing connection etc.
Usage of Java finally
Case 1: java finally example where exception doesn't occur
class TestFinallyBlock{
public static void main(String args[]){
try{
Output:5
int data=25/5;
finally block is always executed
System.out.println(data);
rest of the code...
}
catch(NullPointerException e)
{System.out.println(e);}
finally
{System.out.println("finally block is always ex
ecuted");}
System.out.println("rest of the code...");
}
}
Case 2: 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:
finally block is always executed Exception in thread main
java.lang.ArithmeticException:/ by zero
Case 3: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 execu
ted");}
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...
Multithreading
Multithreading in java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
I. 1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
II. 2) You can perform many operations together, so it saves time.
III. 3) Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:
1) Process-based Multitasking (Multiprocessing)
2) Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words, each process allocates a
separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.
Thread class:
Thread class provide constructors and methods to create and perform
operations on a thread.Thread class extends Object class and implements
Runnable interface.
Starting a thread: