[go: up one dir, main page]

0% found this document useful (0 votes)
11 views33 pages

Unit - V

The document covers various concepts in Java programming, focusing on strings, interfaces, nested classes, packages, and multithreading. It explains how to declare and manipulate strings using the String and StringBuffer classes, and details the implementation of interfaces and nested classes. Additionally, it outlines the structure and usage of packages in Java, along with an introduction to multithreading, emphasizing its significance in executing multiple threads simultaneously.

Uploaded by

shanthkalai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views33 pages

Unit - V

The document covers various concepts in Java programming, focusing on strings, interfaces, nested classes, packages, and multithreading. It explains how to declare and manipulate strings using the String and StringBuffer classes, and details the implementation of interfaces and nested classes. Additionally, it outlines the structure and usage of packages in Java, along with an introduction to multithreading, emphasizing its significance in executing multiple threads simultaneously.

Uploaded by

shanthkalai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 33

CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

UNIT V

STRINGS
• Sequence of characters
• Declared as char array
or
• Java has 2 classes named as String and StringBuffer. Create object for that class.
Declared as char array :
Syntax :
char arrayname[ ] = new char[size];
Example :
Char name[ ] = new char[4];
name[0] = ‘G’;
name[1] = ‘o’;
name[2] = ‘o’;
name[3] = ‘d’;
Using String class
Syntax :
String stringname;
stringname = new String ();
stringname=new String(“conststring”);
Example :
String name;
name = new String(“Good”);
(or)
String name = new String(“Good”);
(or)
String name = br.readLine();

Length of the string :


 Using length() method.
Syntax :
stringname.length();
Example :
int n = name.length();

Concatenation of strings :
• In Java the 2 string are concatenated using + operator.
Examples :

String fullname = name1 + name2;


String city = “New” + “Delhi”;
System.out.println(name1 + “Kumar”);

1 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

String arrays :
• Possible to declare string arrays
Example :
 String name [ ] = new String[3];
 name holds 3 string constants

String Methods :

• The String class defines many methods that allows us to accomplish a variety of
tasks.

S. No Method Call Task Performed


1 s2 = s1.toLowerCase; Converts the string s1 to all Lowercase
2 S2 = s1.toUpperCase; Converts the string s1 to all Uppercase
3 S2 = s1.replace(‘x’,’y’);
Replace all appearances of x with y
4 S2 = s1.trim(); Remove white spaces at the beginning
and end of the string s1
5 S1.equals(s2); Returns ‘true’ if s1 equals s2
6 S1.equalsIgnoreCase(s2); Returns ‘true’ if s1 = s2, ignoring the
case of characters
7 S1.length(); Gives the length of s1
8 S1.ChartAt(n); Gives nth character of s1
9 S1.compareTo(s2); Returns negative is s1<s2, positive is
s1>s2, and zero if s1 = s2
10 S1.concat(s2); Concatenates s1 and s2
11 S1.substring(n); Gives substring starting from nth
character
12 S1.substring(n,m); Gives substring starting from nth
character up to mth
13 String.ValueOf(Variable); Converts the variable value to string
representation
14 p.toString(); Creates a string representation of the
object p
15 S1.indexOf(‘x’); Gives the position of the first occurrence
of ‘x’ in the string s1
16 S1.indexOf(‘x’,n); Gives the position of ‘x’ that occurs after
nth position in the string s1

StringBuffer Class :

• While String class creates strings of fixed length, StringBuffer class creates
strings of flexible length that can be modified in terms of both length and content.
We can insert characters and substrings in the middle of a string or append string
to the end.

2 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

• The StringBuffer class defines many methods that allows us to accomplish a


variety of tasks.

Syntax for creating object for StringBuffer class:


 StringBuffer stringname;
 stringname = new StringBuffer (); (or)
 stringname=new StringBuffer(“conststring”);

The StringBuffer class defines many methods that allows us to accomplish a variety of
tasks.

S.No Method Task

1 S1.setChartAt(n, ‘x’); Modifies the nth character to x

2 S1.append(s2); Appends the string s2 to s1 at the end

3 S1.insert(n, s2); Inserts the strings s2 at the position n of


the string s1

4 S1.setLength(n); Sets the length of the string s1 to n. If


n<s1.length() s1 is truncated. If
n>s1.length() zeros are added to s1.

INTERFACES
 Java does not support multiple inheritance

3 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

 We cannot derive a new class from more than one super classes
 Multiple inheritance can be implemented using interfaces in Java
 Declaration of interface is similar to class declaration
 Like classes, interfaces are also members of package
 Interfaces only consists of abstract methods and final variables
 But the keyword abstract and final are optional

Definition :

“An interface is a collection of abstract behavior that individual classes can


implement”

 One class can implement any no. of interfaces


 The class that can implement an interface can define the methods in the
interface

Defining Interface :
Syntax :
interface name
{
data-type var = value;
returntype methodname(args);
}

Example :
interface Measure
{
int a = 10;
void area();
void display();
}
Extending Interface :
 Deriving a new interface from existing interface(s)
Syntax :

interface name3 extends name1,name2


{
// Declaration of variables
// Declaration of methods
}
name1,name2 - Existing Interface
name3 - New Interface

Example :
interface Measure

4 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

{
int a = 10;
void area();
void display();
}

interface Measure1 extends Measure


{
String name = “polygon”;
void volume();
}

Implementing Interfaces:

 The class can implement the interface


 One class can implement any no. of interfaces.
 All the variables and methods are inherited from interface to class
 The class must define all the methods available in the interface
Syntax :
class name implements interface-name1,interface-name2,..
{
//body of the class
}

Combine extending classes and Implementing Interfaces :

 Possible to combine extending the classes with interface implementation.


Syntax :

class sub extends super implements interface-name1,interface-name2,..


{
//body of the class
}

Example :
interface Name
{
void nam(String n);
}

interface Address
{
void add(String a);
}

class A implements Name,Address

5 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

{
void name(String n)
{
System.out.println(“Name”+n);
}
void add(String a)
{
System.out.println(“Address”+a);
}

void display()
{
System.out.println(“Method in class A”);
}
}
class Test
{
public static void main(String args[])
{
A a = new A();
System.out.println(“Calling a method in class A”);
a.display();
System.out.println(“Calling a method in Interface Name”);
a.name(“Rama”);
System.out.println(“Calling a method in Interface Address”);
a.add(“Madurai”);
}
}

Difference Between Class and Interface :


Class Interface
All methods are defined All methods in the interface are abstract
within the class by default
Allows to create object Do not allow to create object directly
directly
Do not support multiple Support multiple inheritance
inheritance

Various Forms of Interface Implementation :

6 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

Interface A
Class A
D Interface
Implementation
Extension Extension Interfac
Class B e
Class B E Interface
Extensi
Extension on
Implementation
Extension Interfac
Class C e
Class C

Interface B
Interface A
Interface A
Extension Extension
Implementation Implementation

C Interface
Extensi
B Class on
C Class Implementation

D Class

NESTED CLASSES

 Definition of a class inside another class


 Outer class, Inner class
 Instance for a inner class can be created inside the outer class or inside any
method in the outer class
Syntax :
class outerclass
{
class innerclass
{
//body of the class
}

7 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

innerclass i = new innerclass();


}

Example :

class Outer
{
class Inner
{
private int a = 10;
int value()
{
return a;
}
}
void display(int a)
{
int b;
b=a;
System.out.println(“b=“+b);
Inner i = new Inner();
System.out.println(“value of inner class=“+i.value());
}
}
class Test
{
public static void main(String args[])
{
Outer o = new Outer();
o.display(100);
}
}

Output :

b=100
value of inner class 10

PACKAGES

8 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

PUTTING CLASSES TOGETHER


TYPES
2 Types
 Java API Packages
 User Defined Packages

Java API Packages :

 Language support package : To implement basic features of Java - java.lang


 Utilities Package : To provide functions such as date and time - java.util
 Input/Output Package : For I/p and o/p manipulation - java.io
 Networking Package : To communicate with other system via internet - java.net
 AWT Package : Abstract Window Toolkit that implements platform independent
GUI –java.awt
 Applet Package : To create Java applets - java.applet

Importing a Package :
Syntax :
 •import packagename.*; //Includes all classes in the package
or
import packagename.classname; //Include only that class specified

Example :
import java.io.*; //Includes all I/O classes
import java.lang.*; //Includes all math and string classes
import java.lang.String; //Include String class only in the lang package

User Defined Packages

Creating Packages:
Syntax :
package packagename; //Package Declaration
public class classname // Class Definition
{
body of the class;
}

Creating Packages :
Involves the following steps

 Declare the package at the beginning of the file


 Define the class that is to be put in the package and declare it public.
 Create a subdirectory with same name as that of package name under the
directory where the programs are stored
 Save the file with the same name as that of classname.java under the subdirectory
created.

9 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

 Compile the file. This creates the file classname.class in the subdirectory.
 Accessing A Package

Syntax :

import packagename.*;//Accessing all classes in the package


(or)
import packagename.classname; //Access the specified class
in the package
Example :
package pack1;
public class A
{
public void displayA()
{
System.out.println(“class A”);
}
}
 Create a directory with name pack1
 Save the file as A.java inside pack1.
 Compile the file
 Compiler automatically create the file A.class under pack1.

Create another package pack2.


package pack2;
public class B
{
public void displayB()
{
System.out.println(“class B”);
}
}
 Create a directory with name pack2
 Save the file as B.java inside pack2
 Compile the file
 Compiler automatically create the file B.class under pack2

Importing Packages :

import pack1.A;
import pack2.*;
class Test
{
public static void main(String args[])
{

10 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

A obja = new A();


B objb = new B();
obja.displayA();
objb.displayB();
}
}
 Save the file as Test.java and compile and run the program and get the output as
class A
class B

Subclassing(Extending) an Imported Class :

import pack1.A;
class C extends A
{
void displayC()
{
System.out.println(“class C”);
}
}
class Test
{
public static void main(String args[])
{
c objc = new C();
objc.displayA();
objc.displayC();
}
}
Output :
class A
class C

Adding more Classes to a Package :

 Decide the name of the package and create a subdirectory with that name under
the directory where the programs are stored.
 Define the classes that is to be put in the package and declare it public in separate
files and declare the package statement
package packagename; at beginning of each file.
 Save the files with the same name as that of classname.java under the
subdirectory created.
 Compile all the files. This creates classname.class files for all the files in the
subdirectory.
Note : It is not possible to define more than one public class in a .java file.
Example :

11 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

package pack1;
public class A
{
public void displayA()
{
System.out.println(“class A”);
}
}
 Create a directory with name pack1
 Save the file as A.java inside pack1.
 Compile the file
 Compiler automatically create the file A.class under pack1.

package pack1;
public class B
{
public void displayB()
{
System.out.println(“class B”);
}
}
 Save the file as B.java inside pack1
 Compile the file
 Compiler automatically create the file B.class under pack1
 Now package pack1 contains 2 classes A and B

Hiding classes :

 import packagename.*; import all public classes in the class


 To hide a class in the package from external access declare a class as not
public class

Example :

package pack1;
public class A
{
public void displayA()
{
System.out.println(“class A”);
}
}

class B

12 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

{
public void displayA()
{
System.out.println(“class B”);
}
}

MULTITHREADED PROGRAMMING

INTRODUCTION
:

 Multithreading is a concept by which the program is divided into 2 or more


subprograms, which can be executed parallel and simultaneously.
 A thread is similar to a program that has a single flow of control. It has a
beginning, a body, and an end, and executes commands sequentially.
 That programs are called as single-threaded programs. Every program will
have at least one thread.

Multithreading :
 Java supports multithreading.
 Mean that allows multiple flow of control in developing programs
 Each flow of control may be thought of as a separate tiny program known as a
thread that runs in parallel to others.
 A program that contains multiple flows of control is known as multithreaded
program.
 Multithreading is a powerful tool that makes Java distinct from other
programming languages.

CREATING THREADS :
 Threads are implemented using a method run().
Syntax :

public void run()


{
statements for implementing thread
}
 The run() method should be invoked by an object of the concerned thread.
This can be achieved by creating the thread and initiating it with the help of
another thread method called start().

A new thread can be created in two ways.


By creating a thread class : Define a class that extends Thread class and override its
run() method with the code required by the thread.

13 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

By converting a class to a thread : Define a class that implements Runnable interface.


The Runnable interface has only one method, run(), that is to be defined in the method
with the code to be executed by the thread.

Extending a Thread Class :


Extending Thread class in the package java.lang. Then
import java.lang.Thread; (or)
import java.lang.*;

and it includes the following steps:

1. Declare the class which extends the Thread class.


2. Implement the run() method that is responsible for executing the sequence of code
that the thread will execute.
3. Create a object for that class and call the start() method to initiate the thread
execution.

Declaring the class :

class MyThread extends Thread


{
//body of the thread
}

Implementing the run() method :

 The run() method has been inherited by the class MyThread.


 Override the method run() to implement the code to be executed by our
thread.
public run()
{
//Thread code
}
 When we start the new thread, it calls the thread’s run() method.
Starting New Thread :

MyThread obj = new MyThread(); //Creating object for MyThread class


obj.start(); //Invokes run() method

is equivalent to new MyThread().start();

Example Program :

14 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

class A extends Thread


{
public void run()
{
for(int i=1; i<5 ; i++)
{
System.out.println(“Thread A: i = “+i);
}
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<5 ; j++)
{
System.out.println(“Thread B: j = “+j);
}
System.out.println(“Exit from B”);
}
}
class C extends Thread
{
public void run()
{
for(int k=1; k<5 ; k++)
{
System.out.println(“Thread C: k = “+k);
}
System.out.println(“Exit from C”);
}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}

Output :
First Run :

15 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

Thread A : i = 1
Thread A : i = 2
Thread B : j = 1
Thread B : j = 2
Thread C : k = 1
Thread C : k = 2
Thread A : i = 3
Thread A : i = 4
Thread B : j = 3
Thread B : j = 4
Thread C : k = 3
Thread C : k = 4
Thread A : i = 5
Exit from A
Thread B : j = 5
Exit from B
Thread C : k = 5
Exit from C
Output :
Second Run :
Thread A : i = 1
Thread A : i = 2
Thread C : k = 1
Thread C : k = 2
Thread A : i = 3
Thread A : i = 4
Thread B : j = 1
Thread B : j = 2
Thread C : k = 3
Thread C : k = 4
Thread A : i = 5
Exit from A
Thread B : j = 3
Thread B : j = 4
Thread C : k = 5
Exit from C
Thread B : j = 5
Exit from B

 Once the threads are starts executing , we cannot decide the order in which
they may execute statements.
 Eg : Previous two runs give different outputs

Stopping a Thread :

To stop a thread from running further then call stop() method

16 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

obj.stop();
This causes the thread to move to the dead state.
The thread will move to the dead state automatically when it reaches the end of its
method.

Blocking a Thread :

A thread can also be temporarily suspended or blocked from entering into the runnable
and running state by calling any one of the methods
sleep() //Blocked for a specified time
suspend() //Blocked until further orders
wait() //Blocked until certain condition occurs

These methodscause the thread to go into the blocked state.


Thread will return to runnable state when
1.Specified time is elapsed in the case of sleep(),
2.resume() method is invoked in the case of suspend()
3.notify()method is invoked in the case of wait()
Implementing The “Runnable Interface” :
We can also create the threads by implementing Runnable interface which declares run()
method. We must perform the following :
1.Declare the class as implementing the Runnable Interface
2.Implement (Define) the run() method.
3.Create a thread by defining an object that is instantiated from this
“runnable” class as the target of the thread
4.Call the thread’s start() method to run the thread.
Syntax :
class sample implements Runnable
{
public void run()
{
//body of the thread
}
}

Starting New Thread :

sample objrunnable = new sample(); //Creating object for class which implements
runnable interface
Thread objthread = new Thread(objrunnable); //Creating object for Thread class
objthread.start(); //Invokes run() method
Example Program :

class sample implements Runnable


{
public void run()

17 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

{
for(int i=1;i<10;i++)
{
System.out.println(“Threadsample :”+i);
}
System.out.println(“End of Threadsample”);
}
}
class RunnableTest
{
public static void main(String args[])
{
sample objrunnable=new sample();
Thread objthread = new Thread(objrunnable);
objthread.start();
System.out.println(“End of main Thread”);
}
}
Output :
End of main Thread
Threadsample : 1
Threadsample : 2
Threadsample : 3
Threadsample : 4
Threadsample : 5
Threadsample : 6
Threadsample : 7
Threadsample : 8
Threadsample : 9
Threadsample : 10
End of Threadsample

Life Cycle of a Thread :


During the life time of a thread, there are many states it can enter.
1.Newborn state
2.Runnable state
3.Running state
4.Blocked State
5.Dead State
A thread is always in one of these 5 states.

Newborn state :
 When we create a thread object, the thread is born and is said to be in
newborn state. Then the thread go to the state depends on the schedule
 Schedule it for running using start() method - runnable state.
 Kill it using stop() method – dead state

18 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

NewBorn

Stop
Start

Runnable Dead

Runnable state :

 Means that the thread is ready for execution and is waiting for the availability
of the processor.
 The thread has joined the queue of threads that are waiting for execution.
 All the threads have equal priority then they are given time slots for execution
in round robin fashion.
 The process of assigning time to threads is known as time-slicing

Running State :
 The processor has given its time to the thread for its execution then the thread
goes to running state.
 The thread moves between running and runnable state in one of the following
situations
yield() method :
After the thread completes its first slot it will wait for completion of other threads turn
then it will go to runnable state using the method yield().
yield

Running
Thread … …
Runnable threads

suspend() and resume() method :

19 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

 The thread has been suspended using suspend() method.

suspend

resume

Running Runnable Suspended

sleep(t) method :

 We can put a thread to sleep for a specified time using the method sleep(time)
where time in milliseconds. The thread is out of queue during this period and
re enters the runnable state as soon as time period is elapsed.

sleep(t)

after t

Running Runnable Sleeping


wait() and notify() method :

 The thread has been told to wait until some event occurs using wait() method. It
can be again scheduled to run using notify() method.

wait
notify

Running Runnable Waiting

Blocked State :

20 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

 A thread is said to be blocked when it is prevented from entering into the runnable
state.
 A thread is in blocked state when the thread is suspended, sleeping or waiting in
order to satisfy certain requirements.
 A blocked thread is considered “not runnable” but not dead and fully qualified to
run again.

Dead State :
 Every thread has a life cycle.
 A running thread ends its life when it has completed executing its run() method.
The thread goes to dead state.
 Otherwise we can also kill the thread using stop() method.

State Transition Diagram of a Thread :

New Thread Newborn


stop
start

stop
Active Dead
Running Runnable
Thread
yield Killed
Thread

suspend resume stop


sleep notify
wait

Idle Thread
Blocked
(Not Runnable)

Thread Methods :

21 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

 Thread methods are used to control the behaviour of a thread. Various thread
methods are
1.Start()
2.Run()
3.Yield()
4.Sleep()
5.Stop()
6.Suspend()
7.Resume()
8.Wait()
9.Notify()
Example Program :
class A extends Thread
{
public void run()
{
for(int i = 1;i<=5;i++)
{
if(i==1) yield();
System.out.println(“Thread A :i=“+i);
}
System.out.println(“Exit from A”):
}
class B extends Thread
{
public void run()
{
for(int j = 1;j<=5;j++)
{
System.out.println(“Thread B :j=“+j);
if(j==3) stop();
}
System.out.println(“Exit from B”):
}
class c extends Thread
{
public void run()
{
for(int k = 1;k<=5;k++)
{
System.out.println(“Thread C :k=“+k);

if(k==1)
try
{

22 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

sleep(1000);
}
catch(Exception e)
{
}
}
System.out.println(“Exit from C”):
}
}
class ThreadMethods
{
public static void main(String args[])
{
A threadA = new A();
B threadB = new B();
C threadC = new C();
System.out.println(“Start thread A”);
threadA.start();
System.out.println(“Start thread B”);
threadB.start();
System.out.println(“Start thread C”);
threadC.start();
System.out.println(“End of main thread”);
}
}

Output :
start thread A
start thread B
start thread C
Thread B : j = 1
Thread B : j = 2
Thread A : i = 1
End of main thread
Thread C : k = 1
Thread B : j = 3
Thread A : i = 3
Thread A : i = 4
Thread A : i = 5
Exit from A
Thread C : k = 2
Thread C : k = 3

Thread C : k = 4
Thread C : k = 5

23 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

Exit from C

Thread Exception :

It is necessary to put sleep() method inside try block and followed by a catch block.
Because the sleep() method throws an exception, which should be caught.
If we fail to catch the exception, program will not compile. Any exception
Catch(Exception e)
{
}

Thread Priority :
 Each thread is assigned a priority, which affects the order in which it is scheduled
for running.
 The threads discussed earlier have equal priority, then Java scheduler share the
processor on a first come, first serve basis.

Set Priority of a Thread :


Syntax :
ThreadName.setPriority(intNumber);

 Where intNumber is an integer value to which the thread’s priority is set.


 Thread class defines several priority constants
1.MIN_PRIORITY = 1
2.NORM_PRIORITY = 5
3.MAX_PRIORITY = 10
 intNumber may assume any value from 1 To 10.
 Default setting is NORM_PRIORITY

The lower priority threads gain control if


1.The higher priority thread stops running at the end of run().
2.The higher priority thread is made to sleep using sleep()
3.The higher priority thread is told to wait using wait.

Example Program :
class A extends Thread
{
public void run()
{
System.out.println(“threadA started”);

for(int i=1; i<=4 ; i++)


{

24 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

System.out.println(“Thread A: i = “+i);
}
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run()
{
System.out.println(“threadB started”);
for(int j=1; j<=4 ; j++)
{
System.out.println(“Thread B: j = “+j);
}
System.out.println(“Exit from B”);
}
}
class C extends Thread
{
public void run()
{
System.out.println(“threadC started”);
for(int k=1; k<=4 ; k++)
{
System.out.println(“Thread C: k = “+k);
}
System.out.println(“Exit from C”);
}
}

class ThreadPriority
{
public static void main(String args[])
{
A threadA = new A();
B threadB = new B();
C threadC = new C();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);

System.out.println(“Start thread A”);


threadA.start();

25 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

System.out.println(“Start thread B”);


threadB.start();
System.out.println(“Start thread C”);
threadC.start();
System.out.println(“End of main thread”);
}
}

Output :

start thread A
start thread B
start thread C
threadB started
Thread B : j = 1
Thread B : j = 2
threadC started
Thread C : k = 1
Thread C : k = 2
Thread C : k = 3
Thread C : k = 4
Exit from C
End of main thread
Thread B : j = 3
Thread B : j = 4
Exit from B
threadA started
Thread A : i = 1
Thread A : i = 2
Thread A : i = 3
Thread A : i = 4
Exit from A

EXCEPTION HANDLING

INTRODUCTION :

• An exception refers to unexpected condition in a program


• The unexpected condition could be faults, causing an error which in turn causes
the program to fail
• Java provides error handling mechanism called as Exception handling
Errors :
- Compile-time error
- Run-time error
Compile time :

26 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

 At the compilation time it is reported e.g. syntax error


Runtime :
 At the execution time it is reported – divide by zero error, overflow error
 Java provides mechanism to handle run time errors

• Exception Handling Mechanism suggests that error handling code must


perform the following tasks:
• Detect the problem causing exception (hit the exception)
• Inform that an error has occurred (throw the exception)
• Receive the error information (catch the exception)
• Take corrective actions (Handle the exception)

Exception Handling Mechanism :

Try Block Exception object


creator
Statement that causes an exception
Throws
exception
object

catch Block
Exception
handler
Statement that handles the exception

Java provide two types of exception handling mechanism

1. Java has many inbuilt exceptions then it automatically throw the exception
2. Throwing our own exceptions – using throw keyword.
Automatically throw the exception :
Syntax :
try

27 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

{
statements; //generates an exception
}

catch(Exception-type e)
{
statement; //processes the exception
}
Exception Type Cause of Exception
ArithmeticException Caused my math errors such as division by zero
ArrayIndexOutOfBoundsException Caused by bad array indexes
ArrayStoreException Caused when a program tries to store the wrong
type of data in an array.
FileNotFoundException Caused by an attempt to access a nonexistent file
IOException Caused by general I/O failures, such as inability
to read from a file
NumberFormatException Caused when a conversion between strings and
number fails
OutOfMemoryException Caused when there’s not enough memory to
allocate a new object
StringIndexOutOfBoundException Caused when a program attempts to access a
nonexistent character position in a string

Example Program :
import java.lang.Exception;
class ErrorTest
{
public static void main(String args[])
{
int a = 10; int b = 5;
int c = 5; int x,y;
try
{
x = a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
y = a/(b+c);
System.out.println(“y=“+y);
}
}

Output :
Division by zero

28 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

Y=1

Multiple Catch Statements:


Syntax :
try
{
statements; //generates an exception
}
catch(Exception-type1 e)
{
statement; //processes the exception type 1
}
catch(Exception-type2 e)
{
statement; //processes the exception type 2
}
.
.
.
catch(Exception-typen e)
{
statement; //processes the exception type n
}
Example Program :
import java.lang.Exception;
class ErrorTest
{
public static void main(String args[])
{
int a[] = {5,10};
int b = 5;
try
{
int x = a[2] / (b – a[1]);
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
catch(ArrayIndexOutOfBoundException e)
{
System.out.println(“Array index error”);
}

catch(ArrayStoreException e)
{

29 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

System.out.println(“Wrong data type”);


}
int y = a[1] / a[0];
System.out.println(“y=“+y);
}
}
Output :
Array index error
Y=2
finally statement :

 Finally block can be placed immediately after try block or after all catch
blocks.
 Execute this block after executing catch block then place the statements if no
exception is caught by any catch block.
Syntax :
try
{
statements; //generates an exception
}
catch(Exception-type1 e)
{
statement; //processes the exception type 1
}
catch(Exception-type2 e)
{
statement; //processes the exception type 2
}
.
.
.
catch(Exception-typen e)
{
statement; //processes the exception type n
}
finally
{
statement;
}

Example Program :
import java.lang.Exception;
class ErrorTest
{
public static void main(String args[])
{

30 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

int a[] = {5,10};


try
{
int x = a[1] / a[0];
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error”);
}
catch(ArrayStoreException e)
{
System.out.println(“Wrong data type”);
}
finally
{
System.out.println(“No Exception“);
}
}

Output :
No Exception

Throwing our Own Exceptions :

Syntax :
throw new myException();

Example :

import java.lang.Exception;
class MyException extends Exception
{
Myexception(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{

31 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

int x = 5, y = 1000;
try
{
float z = (float) x/ (float) y;
if(z < 0.01)
{
throw new MyException(“Number is too small”);
}
}
catch(MyException e)
{
System.out.println(“Caught my exception”);
System.out.println(e.getMessage());
}
finally
{
System.out.println(“I am always here”);
}
}
}

Output :
Caught my exception
Number is too small
I am always here

C++ Vs JAVA

C++ JAVA
Platform dependent Platform independent
Character set –Unicode Character set –Unicode
Support Pointers Does not support Pointers
Support Operator overloading Does not support Operator overloading
Directly support multiple inheritance Not directly support multiple inheritance
Dynamically allocated Memory to be Automatic memory management
reallocated by the programmer
Arrays are not dynamic type Arrays are dynamic type
Support structures & Union Does not support structures & Union
Supports Templates Does not support Templates
System programming language Internet programming language
Primitive types do not have equivalent Primitive types have equivalent classes
classes called as wrapper classes

32 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE

Support Multithreaded Programming Does not Support Multithreaded


Programming

33 Prepared By Ms M.Ramya.

You might also like