Professional Documents
Culture Documents
This work is created by N.Senthil madasamy, Dr. A.Noble Mary Juliet, Dr. M. Senthilkumar and is licensed under a
Creative Commons Attribution-ShareAlike 4.0 International License
Exception
• An exception is a problem that arises during the
execution of a program.
• An exception can occur for many different reasons,
Number
Format including the following: End of file exception.
exception – Access a file beyond its limit
Illegal AccessExcepti
– Convert a alpha numeric string to integer
NullPointer
– try to access variable or method out of scope Exception
– Try to access member of any object, but object is null-
– Try to access array element beyond the limit –
– Try divide a Variable by zero errors- ArrayIndexOutof
bounds
Exception
Arithmetic Exception
What is an Exception?
An exception is an unexpected event that occurs
during runtime and causes normal program flow
to be disrupted.
• Errors: These are not exceptions at all, but problems that arise
beyond the control of the user or the programmer. Errors are
typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an
error will arise. They are also ignored at the time of compilation.
Exception Handling
The way of handling anomalous situations in a program-run is known
as Exception Handling.
Its advantages are:
Exception handling separates error-handling code
from normal code
It clarifies the code and enhances readability
Introduction
1 •Write code such that it raises an error flag every time something goes wrong [throw exception]
try
Wherever the code may trigger an
{
exception, the normal code logic is placed
//Protected code inside a block of code starting with the
} “try” keyword:
catch(ExceptionType1 e1)
After the try block, the code to handle
{
the exception should it arise is placed in a
//Catch block block of code starting with the “catch”
} keyword.
finally
The finally keyword is used to create a
{
block of code that follows a try block. A
//The finally block always finally block of code always executes,
executes. whether or not an exception has
} occurred. protected code.
Exception Types
Super Class
SubClasses of “Throwable”
SubClass of “Exception”
12
Java Exception Hierarchy
class excep
{
public static void main(String arg[])
{ The exception is handled by
int d=0; “default exception handler” of
int a=58/d; JVM
System.out.println("a="+a);
System.out.println("After exception");
}
}
14
Using try and catch
class excep
{
public static void main(String arg[])
{
int d=0;
int a=0;
try
{
a=58/d;
System.out.println("a="+a);
}
catch(ArithmeticException e)
{
System.out.println("Exception!! Divide by zero");
}
System.out.println(“After exception”);
}
}
15
Displaying a Description of an Exception
class excep
{
public static void main(String arg[])
{
int d=0;
int a=0;
try
{
a=58/d;
System.out.println("a="+a);
}
catch(ArithmeticException e)
{
System.out.println("Exception!! “ +e);
}
System.out.println(“After exception”);
}
}
16
Multiple Catch Blocks
Syntax: try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
Syntax Exception Stack
try {
// try1 block generating excep1
try
{
TOS try1 catch
//try2 block generating excep2 Excep2 handler
}
try2 catch
catch (Excep1 ex1) { Excep1 handler
// exception handler for Type1
} try2 block
} generating excep2
catch (Excep2 ex2) { try1 block
// exception handler for Type2 generating excep1
} JVM Default Handler will handle this
18
class excep
{
public static void main(String args[])
{
try
{ int a = args[0];
System.out.println("a = " + a);
int b = 42 / a;
try
{ int c[] = new int[a];
c[42] = 99;
} catch(ArrayIndexOutOfBoundsException e)
{System.out.println("Array Index Exception!!! " + e); }
}catch(ArithmeticException e)
{ System.out.println("Divide By Zero!!!! " + e); }
}
catch(ArithmeticException e)
{
System.out.println("Inside main() catch " + e);
}
System.out.println("After try/catch blocks.");
}
}
21
throws
• Methods that cannot/will not handle the
exceptions thrown, may use “throws” clause
to handle it in some other way.
• Throws clause lists the types of exceptions
that a method might throw
return-type method-name (params) throws Exception-List
{…}
public static void main(String args[]) throws Exception
22
class mythrows
{
23
}
finally
• The finally block will execute whether or not an exception is
thrown, whether or not catch matches
• This can be useful for closing file handles and freeing up any
other resources that might have been allocated at the
beginning of a method
• However, each try statement requires at least one catch or a
finally clause.
• finally => block of code that is executed after a try /catch
block has completed and before the code following the
try/catch block.
24
Finally
public class ExcepTest
{
public static void main(String args[])
{
int a[] = new int[2];
try
{
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
finally
{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}
Declaring Your Own Exception
You can create your own exceptions in Java. Keep the following
points in mind when writing your own exception classes:
Example
public InvalidDept_codeException(String s)
{
System.out.println("Department Exception : "+s);
}
}
Step 2: Identifying an exception raising situation in this example
Character.isDigit()
1. When user enter more than 2 characters.
Character.isLetter()
2. When user enter digits
}catch(InvalidDept_codeException e){}
Chained Exceptions
• A feature that allows to associate an exception
with another exception
• The second exception describes the cause of
the first one.
• 2 new methods:
– Throwable getCause()
– Throwable initCause(Throwable CauseExcep)
31
Example
try {
} catch (IOException e)
{
throw new SampleException("Other IOException", e);
}
PACKAGE
• Packages in java are like directories in our
existing file system.
• It contains our class files.
• A java package is a group of similar types of
classes, interfaces and sub-packages.
– built-in package
– user-defined package.
• Advantage of Java Package
– 1) Java package is used to categorize the classes
and interfaces so that they can be easily
maintained.
– 2) Java package provides access protection.
– 3) Java package removes naming collision.
Build-in Package
• There are many built-in packages such as
java, lang, awt, javax, swing, net, io, util, sql
etc.
• These packages consists of a large number
of classes which are a part of Java API.
• For e.g, we have used java.io package
previously which contain classes to support
input / output operations in Java.
• Similarly, there are other packages which
provides different functionality.
Build-in Package
Importing of Packages
• In a Java source file, import statements occur
immediately following the package statement (if it
exists) and before any class definitions.
– import java.util.Date;
– import java.io.*;
• Consider the following statements :
1 ) import java.util.Vector; // import the Vector
class from util package
2 ) import java.util.*; // import all the class from
util package
First statement imports Vector class
from util package which is contained
inside java package.
Second statement imports all the classes from util
package
User defined Package
• Now, we will see how to create packages and use
them.
• Suppose, we want to create a package
named MyPack which contains a class named C1.
• First, we will create a directory named MyPack
( the name should be same as the name of the package ).
• Then create the C1 class with the first statement
being package Mypack;.
• Now, the package is ready to be imported.
Defining a Package
A package is both a naming and a visibility control
mechanism:
1) divides the name space into disjoint subsets.
It is possible to define classes within a package
that are not accessible by code outside the package.
2) controls the visibility of classes and their members.
It is possible to define class members that are only
exposed to other members of the same package.
Same-package classes may have an intimate knowledge of
each other, but not expose that knowledge to other
packages
Creating a Package
• A package statement inserted as the first line of
the source file:
package myPackage;
class C1 { … }
Current
Pack
P1
P2
A.Java
B.Java
C.Java
Test.java A.class B.class C.class
Test.Java
Package P1; import P1.A;
A.Java
public class A
import P1.B;
{
import P2.C;
public void display()
{System.out.println(“I am A in P1”);} public class Test
} {
public static void main(String s[])
Package P1; B.Java
public class B {
{ A aa=new A();
public void display() B bb=new B();
{System.out.println(“I am B in P1”);} C cc=new C();
}
aa.display();
Package P2; bb.display();
public class C C.Java
cc.display();
{
public void display() }}
{System.out.println(“I am C in P2”);} Class , constructor
} and methods should
be public in package
How to compile this example
>javac -d <path> filename.java
javac Test.java
Class A Class B
void get()
{
SOP(“Should be printed”); void get()
} {
SOP(“Should not be printed”);
Class C }
C cc = new C ();
cc.get();
Syntax
The Declaration of Interface consists of a keyword interface, its name, and the
members.
interface InterfaceName {
// constant declaration
static final type variableName = value;
// method declaration
returntype methodname (argumentlist);
}
The Class that Implements Interface called as Implementation Class uses keyword
implements:
class classname implements InterfaceName {
... }
54
Semantic Rules for Interfaces
• Instantiation
Does not make sense on an interface. Interfaces are not classes. You can
never use the new operator to instantiate an interface.
public interface Comparable {. . . }
55
Semantic Rules for Interfaces
• Access modifiers
• Suppose you declare a method as a public in interface ,then you cant declare that
56
interface inter
{
void display();
int i=10;
}
} }
interface outer
{ class interdemo
void display(); {
interface inner public static void main(String
{ args[])
void fun(); {
}
sam1 s1=new sam1();
} s1.display();
class sam1 implements outer sam2 s2=new sam2();
{ s2.fun();
public void display()
{ }
System.out.println("Inside sam1; display"); }
}
}
class sam2 implements outer.inner
{
public void fun()
{
System.out.println("Inside sam2; fun");
}
}
class sam1
class interdemo
{
{
interface inner
public static void main(String
{
args[])
void display();
{
}
sam1 s1=new sam1();
s1.get();
void get()
sam2 s2=new sam2();
{
s2.display();
System.out.println("Inside sam1; get");
}
}
}
}
OS
Test
License
Open source
Test
Mac Ubundo
Stack Implementation
3.Implement “STACK” using interface, class and array.
• Create an interface with 2 method declarations:
– void push(int item);
– int pop();
• Class 1: FixedStack
– Stack size=5
– Items to be pushed and popped: 10,20,30,40,50
• Class2:DynamicStack
– Stack size & items to be pushed and popped – entered by user
Multithreading
Multitasking
Multitasking
Multitasking is a process of executing multiple
tasks simultaneously.
{ A();
{ A(); A1(); A2(); A3(); newThreads {
B1(); B2(); } { A1(); A2(); A3() };
{B1(); B2() }
}
}
Multithreading
Multithreading
• Multithreading in java is a process of executing multiple
threads simultaneously.
• Thread is basically a lightweight sub-process, a smallest unit
of processing.
• Multiprocessing and multithreading, both are used to
achieve multitasking.
• But we use multithreading than multiprocessing because
threads share a common 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.
Why do we need threads?
• To enhance parallel processing
• To increase response to the user
• To utilize the idle time of the CPU
• Prioritize your work depending on priority
Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the
requests processing would be in a queue, thus
increasing the response time and also might hang
the server if there was a bad request.
• By implementing in a multithreaded environment,
the web server can serve multiple request
simultaneously thus improving response time
Advantages of Java Multithreading
1) It doesn't block the
user because threads are
independent and you can
perform multiple operations
at same time.
2) You can perform many
operations together so it
saves time.
3) Threads are independent so it
doesn't affect other threads if
exception occur in a single
thread.
Life cycle of a Thread
• A thread can be in one of the six states. The java thread
states are as follows:
• BLOCKED
• A thread that has suspended execution because it is waiting to acquire
a lock.
• NEW
• A thread that has not begun execution.
• RUNNABLE
• A thread that either is currently executing or will execute when it gains
access to the CPU.
• TERMINATED
• A thread that has completed execution.
Life cycle of a Thread
• TIMED_WAITING
• A thread that has suspended execution for a specified
period of time, such as when it has called sleep( ).
• This state is also entered when a timeout version of wait( )
or join( ) is called.
• WAITING
• A thread that has suspended execution because it is
waiting for some action to occur. For example, it is waiting
because of a call to a non-timeout version of wait( ) or
join( ).
Life cycle of a Thread
Start()
run()
1. sleep(ms)
2. Wait()
1. Suspend()*
1. resume()*
1. Come to running state after
specified time
2. resume()*
1. outof run() 3. notify() & notifyall()
2. stop()*
commonly used methods of Thread class:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM
calls the run() method on the thread.
• public void sleep(long miliseconds): Causes the currently
executing thread to sleep (temporarily cease execution) for
the specified number of milliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the
thread.
– All Java threads have a priority in the range 1-10.
– Top priority is 10, lowest priority is 1.
– Normal priority ie. priority by default is 5.
– Thread.MIN_PRIORITY - minimum thread priority
– Thread.MAX_PRIORITY - maximum thread priority
– Thread.NORM_PRIORITY - maximum thread priority
• commonly used methods of Thread class:
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the
thread.
• public Thread currentThread(): returns the reference of currently
executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object
to temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended
thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon
Thread ecology in a java program
started by java from main(String[])
started by B thread
lifetime of C thread
How to create thread
• Each Java Run time thread is encapsulated in
a java.lang.Thread instance.
• Two ways to define a thread:
1. Extend the Thread class
2. Implement the Runnable interface
How to create thread
• Steps for extending the Thread class:
1. Subclass the Thread class;
2. Override the default Thread method run(), which is the
entry point of the thread,
like the main(String[]) method in a java program.
3. Create a instance of the above thread class
4. Start the thread
}
Output:t
hread is running...
Create a thread named as phone. When thread starts print “Ring…
Ring” five times
class phone extends Thread{
public void run(){
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(1000);
System.out.println("Ring ....Ring...");
}catch(Exception e){}
}
}
public static void main(String args[]){
phone t1=new phone();
t1.start();
}
}
Runnable interface:
• The Runnable interface should be implemented by any class
whose instances are intended to be executed by a thread.
Runnable interface have only one method named run().
Runnable interface :
package java.lang;
public interface Runnable { public void run() ; }
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
Output:r
m2.setPriority(Thread.MAX_PRIORITY); Running thread name is:Thread-0
m1.start(); running thread priority is:10
m2.start(); running thread name is:Thread-1
running thread priority is:1
}
Priority of a Thread (Thread Priority):
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+
Thread.currentThread().getName());
System.out.println("running thread priority is:"+
Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(10);
Output:r
m2.setPriority(Thread.MAX_PRIORITY); Running thread name is:Thread-0
m1.start(); running thread priority is:10
m2.start(); running thread name is:Thread-1
running thread priority is:1
}
Everyone talking at the same time
Intertwine Conversations
Two Independent Groups
Synchronization
Thread Scheduler in Java
My Thread
run()
MyThread T1 MyThread T2