Oops Module 3
Oops Module 3
Exception Handling:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
ExceptionType is the type of exception that has occurred.
class Excep1
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero,
it constructs a new exception object and then throws this exception.
The resulting stack trace from the default exception handler shows
how the entire call stack is displayed:
try
{ //int y = 25/0;
double avg = sum/n;
System.out.println("The average of the student is "+avg);
m[10] =25;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Accessing out of array");
System.out.println("Exception is " +e);
}
catch (ArithmeticException e)
{
System.out.println("No of Subjects must not be Zero");
System.out.println(e);
}
} //outer try
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e+ "outer");
}
}
}
perform();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e+ "main");
}
class ThrowsDemo
{
static void method() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try {
method();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
System.out.println("Exception caught in main");
}
}
}
//finally demonstration
public class FinallyDemo
{
public static void main(String args[])
{
try{
perform();
}
catch (ArithmeticException ae)
{
System.out.println("Exception caught in main");
System.out.println(ae);
}
finally
{
System.out.println("Finally executed in main");
}
}
public static void perform()
{
try{
int x= 25;
int d = x/0;
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae);
}
finally
{
System.out.println("Finally executed in method");
}
}
}
//Userdefined Exceptions
class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
class UserExcepDemo
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException(" not valid ");
else
System.out.println(" welcome to vote " +age);
}
public static void main(String args[])
{
try{
validate(23);
validate(17);
}
catch(InvalidAgeException m)
{
System.out.println("Exception occured: ");
System.out.println( m); // Description of Message
}
System.out.println("rest of the code...");
}
}
static key word in Java
The keyword static is used in java for a variable, a block or a method.
The static keyword belongs to a class but not to an object.
1. Java static variables.
Static keyword is used to define a class member that will be used
independently of any object of that class.
A variable declared as static, then it is called static variable.
Instance variables declared as static are global variables.
When an object of such class is created no copy of the static variable
will exist. All instances of class share same variables.
A static variable can be used to refer to common property of all
objects.
Eg: Company Name, College Name etc.
The static variables gets memory only once in a class area at the
time of class is loading in to memory.
Static variables make the program memory efficient. i.e. it saves
memory.
A static variable can be accessed using class name with out
instantiating it.
class Student
{
int rollno;
String name;
static String college ="VCE";
static int count=0;
Student(int r,String n)
{
rollno = r;
name = n;
count++;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
System.out.println("count "+count);
}
}
public class StaticDemo1
{
public static void main(String args[])
{
Student s1 = new Student(501,"Karan");
s1.display();
Student s2 = new Student(545,"Aryan");
s2.display();
Student s3 = new Student(546,"Rajan");
s3.display();
System.out.println("The number of students " +Student.count);
}
}
2. Java static block
A block of code in a class, used to initialize the static data member.
The static block is executed before main method at the time of class is
loading.
A class can have any number of static blocks , executes them in the
order they defined.
Can access only static data.
int a;
static int b;
static {
// a=10; //CTE
b=0;
b=b+12;
System.out.println("Static block 1 - " +b);
}
static {
b=b-5;
System.out.println("Static block 2 - " +b);
}
static {
System.out.println("Second Static Block ");
x = x+20;
System.out.println("x is "+x);
}
class Test
{
static int cube(int x)
{
return x*x*x;
}
static void display()
{
int x ;
x = cube(6);
System.out.println(x);
}
Advantages of MultiThreading
Allows to write very efficient program that makes
maximum use of CPU.(Idle time can be kept minimum).
Eg: During I/O operation , CPU switch to another thread.
Threads are independent
Throughput – Amount of work done in unit time increase.
Thread class
Java provides Thread class to achieve thread programming.
Thread class provides constructors and methods to create and
perform operations on a thread.
Thread class extends Object class and implements Runnable
interface.
Session -26
After the completion of the session student will be able to
Create Threads using Thread class and Runnable
Interface
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.
Thread t = Thread.currentThread();
System.out.println("The current thread is "+t);
// [Thread Name , Priority ,ThreadGroupName]
System.out.println("The name of Thread is "+ t.getName());
t.setName("Demo Thread");
System.out.println("The name of Thread is "+ t.getName());
System.out.println("The priority of Thread is "+ t.getPriority());
try{
for(int i=1; i<=5;i++)
{
System.out.println(i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
When a Java program executes, the first thread starts is main thread.
The Main thread is important for
o It is the thread from which other child threads re created.
o It must be the last thread to finish execution, because it
performs various shutdown actions.
The main thread is created automatically when a program started.
Creating Thread – Extending Thread Class
Step-1: Create a new class that extends Thread, and then create an instance
of that class.
Step-2: The extending class must override the run () method, which is the
entry point of the new thread created. The actual code for the thread to
execute is provided. Once the run () method completes, the thread will die
and terminate.
Step-3: Calls start () method to begin execution of new thread.
Step-4: Invoke the Thread class constructor using super keyword if necessary.
System.out.println("Main Thread");
System.out.println(Thread.currentThread());
MyThread t1 = new MyThread("One");
t1.start();
System.out.println("The child Thread -> "+t1);
}
Creating Thread – Implementing Runnable Interface
Step-1: To create a new Thread, the class must implements Runnable
interface.
Step-2: Provide implementation for the only one method run (), which is the
entry point of newly created thread. The actual code for the thread to
execute is provided. Once the run () method completes, the thread will die
and terminate.
Step-3: Instantiate an object of type Thread within the newly created thread
class.
Thread(Runnable obj , String name)
Step-4: call the start () method explicitly to start the thread. It makes a call to
run() method to start the execution.
System.out.println(Thread.currentThread());
DemoThread d = new DemoThread();
}
}
Session -27
After the completion of the session student will be able to
Create Multiple Threads Using Thread class and
Runnable interface.
JAM Session:
class MultiThread1
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Name is --->" +t.getName());
System.out.println("Main ---> " +t);
try {
// wait for other threads to end -give long time
for(int n=1;n<=5;n++){
System.out.println("Main Thread->" +n);
Thread.sleep(500);
}
catch (InterruptedException e){
System.out.println("Main thread Interrupted");
}
try{
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e){
System.out.println("Main thread interrupted.");
}
}
}
Creating Threads of Multiple Classes
import java.lang.*;
class FactThread extends Thread
{
FactThread(String name) {
super(name);
System.out.println("The child is " +this);
}
t1.start();
t2.start();
System.out.println("Main completed");
}
}
//Similarly Using Runnable Interface
The two methods of Thread class are
isAlive( ) method returns true if the thread upon which it is called is
still running, otherwise it returns false.
final boolean isAlive( )
class JoinDemo1
{
public static void main(String args[])
{
System.out.println("The main Thread Started");
NewThread t1 = new NewThread("One");
NewThread t2 = new NewThread("Two");
NewThread t3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ t1.isAlive());
System.out.println("Thread Two is alive: "+ t2.isAlive());
System.out.println("ThreadThree is alive: "+ t3.isAlive());
try {
t1.join();
t2.join();
t3.join();
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
Thread t = Thread.currentThread();
System.out.println("The main thread priority is " +
t.getPriority());
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(5);
t1.start();
t2.start();
t3.start();
}
}
Session -29
After the completion of the session student will be able to
Provide synchronization among threads.
Synchronizing Threads
When two or more threads need access to a shared
resource, they need some way to ensure that the
resource will be used by only one thread at a time. The
process by which this is achieved is called
synchronization.
Java provides unique, language-level support for it.
Synchronization allows only one thread to access a
shared resource.
The advantages of Synchronization is
o To prevent thread interferences.
o To prevent inconsistency of data.
Thread Synchronization can be of two forms
1. Mutual Exclusion
2. Inter Thread communication.
1. Mutual Exclusion
Keeps threads from interfering with one another while
sharing data.
Allows only one thread to access shared data
Mutual exclusive threads can be implemented using
i) Synchronized Method
ii) Synchronized Block
i) Synchronized Method
A method defines as synchronized, and then the
method is a synchronized method.
Synchronized method is used to lock an object for
any shared resource.
When a thread invokes a synchronized method, it
automatically acquires lock for that object and
releases it when the thread completes its task.
class Table
{
synchronized void printTable(int n)
{
try{
for(int i=1;i<=10;i++) {
System.out.println(n*i);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
System.out.println(e);
}
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) {
this.t=t;
}
public void run() {
t.printTable(8);
}
}
}
}
The form of synchronized block is
synchronized(object) {
//Statements to be synchronized
}
item =x;
System.out.println("Producer - Produced-->" +item);
produced =true;
notify();
}
Buffer b;
Producer( Buffer b)
{
this.b = b;
start();
}
}
}
class Consumer extends Thread
{
Buffer b;
Consumer(Buffer b)
{
this.b = b;
start();
}
}
}