Unit - V
Unit - V
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();
Concatenation of strings :
• In Java the 2 string are concatenated using + operator.
Examples :
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.
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.
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 :
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 :
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();
}
Implementing Interfaces:
Example :
interface Name
{
void nam(String n);
}
interface Address
{
void add(String a);
}
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”);
}
}
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
7 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE
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
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
Creating Packages:
Syntax :
package packagename; //Package Declaration
public class classname // Class Definition
{
body of the class;
}
Creating Packages :
Involves the following steps
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 :
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
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
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 :
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 :
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 :
13 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE
Example Program :
14 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE
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 :
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
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 :
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
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
19 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE
suspend
resume
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
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
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.
stop
Active Dead
Running Runnable
Thread
yield Killed
Thread
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.
Example Program :
class A extends Thread
{
public void run()
{
System.out.println(“threadA started”);
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);
25 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE
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 :
26 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE
catch Block
Exception
handler
Statement that handles the exception
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
catch(ArrayStoreException e)
{
29 Prepared By Ms M.Ramya.
CS1261/Object Oriented Programming Unit V/ Course Material//III EEE
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
Output :
No Exception
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
33 Prepared By Ms M.Ramya.