UNIT - III
1. JAVA ARRAY
Array is a collection of similar type of data. It is fixed in size means that you can't increase
the size of array at run time
It stores the value on the basis of the index value.
Advantage of Array
One variable can store multiple value: The main advantage of the array is we can
represent multiple value under the same name.
Code Optimization: No, need to declare a lot of variable of same type data, We can retrieve
and sort data easily.
Random access: We can retrieve any data from array with the help of the index value.
Disadvantage of Array
The main limitation of the array is Size Limit when once we declare array there is no chance
to increase and decrease the size of an array according to our requirement, Hence memory
point of view array concept is not recommended to use.
Array creation
58
Prepared by: [Link], [Link]-BCA SNMV CAS
Every array in a Java is an object, Hence we can create array by using new keyword.
Note: At the time of array creation we must be specify the size of array otherwise get an
compile time error.
For Example
int[] a=new int[]; Invalid (some times).
int[] a=new int[5]; Valid
If we specify the array size as negative int value, then we will get run-time error,
The maximum allowed size of array in Java is 2147483647 (It is the maximum value of int
data type)
Difference Between Length and Length() in Java
length: It is a final variable and only applicable for array. It represent size of array.
59
Prepared by: [Link], [Link]-BCA SNMV CAS
length(): It is the final method applicable only for String objects. It represents the number of
characters present in the String.
Types Of Array
Single Dimensional Array
Multidimensional Array
2. JAVA STRING
Strings represents sequence of char values. An array of characters works same as java string.
60
Prepared by: [Link], [Link]-BCA SNMV CAS
In Java programming language, strings are treated as objects.
The [Link] class is used to create string object.
How to create String object
There are two ways to create String object:
String literal
New keyword
String literal
Java String literal is created by using double quotes.
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't
exist in the pool, a new string instance is created and placed in the pool. For example:
new keyword
61
Prepared by: [Link], [Link]-BCA SNMV CAS
In such case, JVM will create a new string object in normal(non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non pool).
3. Vector in Java
Vector implements a dynamic array. It is similar to ArrayList
Vector class object organizes the data in the form of cells
Vector proves to be very useful if you don't know the size of the array in advance or you just
need one that can change sizes over the lifetime of a program
The default capacity of the Vector v=10 cells
Vector are Synchronized
Vector uses Enumeration interface to traverse the elements
Vector class object organizes the data in the form of cells
The default size of the Vector=0 (size is nothing but number of values available in the cells)
In Vector cell values are storing in Heap Memory and cell address
62
Prepared by: [Link], [Link]-BCA SNMV CAS
4. JAVA INTERFACE
An interface is similar to class. It is a collection of abstract methods (function) and variables
with major differences.
The difference is that interface define only abstract methods and final fields, This means that
interfaces do not specify any code to implement these methods and data fiedls contain only
constants.
Therefore, it is the responsibility of the class that implements an interface to define the code
for implementation these methods.
Java Interface also represents IS-A relationship.
It is used to achieve abstraction and multiple inheritance in Java.
All the methods of an interface are by default public. So, it is not required to use the keyword
public when declaring a method in an interface.
How interface is different from class?
63
Prepared by: [Link], [Link]-BCA SNMV CAS
An interface can contain any number of methods
All methods in an interface are abstract (only declaration of method).
Interface is cannot extended by a class; it is implemented by a class.
Interface can extend multiple interfaces. It means interface support multiple inheritance
Understanding relationship between Classes and Interface
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
Creating interface:
The interface keyword is used to declare an interface.
64
Prepared by: [Link], [Link]-BCA SNMV CAS
In the above syntax Interface is a keyword interface name can be user defined name the
default signature of variable is public static final and for method is public abstract.
Extending interface
An interface can extend another
interface in the same way that a class
can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface, this means an interface can be sub-interface from other
interfaces, the new sub-interface will inherit all the members of the super-interface in the
manner similar to subclass
Implementing Interface:
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
65
Prepared by: [Link], [Link]-BCA SNMV CAS
66
Prepared by: [Link], [Link]-BCA SNMV CAS
Rules for implementation interface
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a class can extend
another class.
67
Prepared by: [Link], [Link]-BCA SNMV CAS
5. JAVA PACKAGES
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces.
The purpose of package concept is to provide common classes and interfaces for any
program separately. In other words if we want to develop any class or interface which is
common for most of the java programs than such common classes and interfaces must be
place in a package.
Advantage of Java Package
Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Java package provides access protection.
Java package removes naming collision.
Application development time is less, because reuse the code
Package in java can be Categorized in two form
Built-in package
User-defined package
Built-in package
68
Prepared by: [Link], [Link]-BCA SNMV CAS
These packages consist of a large number of classes which are a part of Java [Link] of the
commonly used built-in packages are:
[Link]: Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
[Link]: Contains classed for supporting input / output operations.
[Link]: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.
[Link]: Contains classes for creating Applets.
[Link]: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
[Link]: Contain classes for supporting networking operations.
User-defined packages
If any package is design by the user is known as user defined package.
Any package program can be compile but cannot be execute or run. These program can be
executed through user defined program which are importing package program.
Rules to create user defined package
Package statement should be the first statement of any package program.
Choose an appropriate class name or interface name and whose modifier must be public.
Any package program can contain only one public class or only one public interface
Package program should not contain any main class (that means it should not contain any
main())
Every package program should be save either with public class name or public Interface
name
Compile package programs - javac -d . [Link]
To Run: java mypack.a
69
Prepared by: [Link], [Link]-BCA SNMV CAS
Import above class in below program using import [Link]
Explanations: In above syntax "-d" is a specific tool which is tell to java compiler create a
separate folder for the given package in given path. When we give specific path then it create
a new folder at that location and when we use . (dot) then it crate a folder at current working
directory.
Explanations: In the above program first we create Package program which is save with
[Link] and compiled by "javac -d . [Link]". Again we import class "A" in class Hello
using "import mypack.A;" statement.
Difference between package keyword and import keyword
Package keyword is always used for creating the undefined package and placing common
classes and interfaces.
Import Is A Keyword which is used for referring or using the classes and interfaces of a
specific package.
70
Prepared by: [Link], [Link]-BCA SNMV CAS
Access Package
There are Three ways to access the package from outside the package.
import package.*;
import [Link];
fully qualified name
Using Packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages (Package inside the package is called the subpackage).
The import keyword is used to make the classes and interface of another package accessible
to the current package.
Using [Link]
If you import [Link] then only declared class of this package will be accessible.
71
Prepared by: [Link], [Link]-BCA SNMV CAS
Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface. It is generally used when two packages have same
class name e.g. [Link] and [Link] packages contain Date class.
72
Prepared by: [Link], [Link]-BCA SNMV CAS
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
6. MULTITHREAD PROGRAMMING
A program can be divided into a number of small processes. Each small process can be
addressed as a single thread.
Multithreaded programs contain two or more threads that can run concurrently and each
thread defines a separate path of execution. This means that a single program can perform
two or more tasks simultaneously. For example, one thread is writing content on a file at the
same time another thread is performing spelling check.
In computer, multitasking is when multiple processes share common processing resources
such as a CPU, hard disk etc... Multi-threading extends the idea of multitasking into
applications where you can subdivide specific operations within a single application into
individual threads.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
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.
Thread is a lightweight components and it is a flow of control. In other words a flow of
control is known as thread, Threads share the same address space.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
Advantages of Java Multithreading
73
Prepared by: [Link], [Link]-BCA SNMV CAS
It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
You can perform many operations together so it saves time.
Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
7. Life cycle of thread
State of a thread are Classified into five types they are
New State
Ready State
Running State
Waiting State
Halted or dead State
New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
74
Prepared by: [Link], [Link]-BCA SNMV CAS
Runnable − After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
Timed Waiting(Blocked) − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable state when
that time interval expires or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
8. Creating Threads
In java language multithreading can be achieve in two different ways.
Using Extending Thread class
Using Runnable interface
Using Extending Thread class
75
Prepared by: [Link], [Link]-BCA SNMV CAS
In java language Rules to be followed to creating multithreading program
Create any user defined class and make that one as a derived class of thread class.
Override run() method of Thread class (It contains the logic of perform any operation)
Create an object for user-defined thread class and attached that object to predefined thread
class object.
Object Creation for Thread Class_Name obj=new Class_Name Thread t=new Thread(obj);
Call start() method of thread class
to execute run() method.
Save the program with
[Link]
Using Runnable interface
The easiest way to create a thread is to create a class that implements the runnable
interface. After implementing runnable interface , the class needs to implement the run()
method,
Rules to create the thread using Runnable interface
76
Prepared by: [Link], [Link]-BCA SNMV CAS
Create any user defined class and implements runnable interface within that
Override run() method within the user defined class.
all start() method to execute run() method of thread class
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
[Link]("Creating " + threadName );
public void run() {
[Link]("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
[Link]("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
[Link](50);
} catch (InterruptedException e) {
[Link]("Thread " + threadName + " interrupted.");
[Link]("Thread " + threadName + " exiting.");
public void start () {
[Link]("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
[Link] ();
77
Prepared by: [Link], [Link]-BCA SNMV CAS
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
[Link]();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
[Link]();
} }
Output
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Stopping thread
When ever we want to stop a thread from running further, we may do so by calling its stop()
method, ex. [Link]();
This statement causes the thread to move to the dead state.
A thread will also move to the dead state automatically when it reaches the end of its
method.
78
Prepared by: [Link], [Link]-BCA SNMV CAS
Blocking thread
A thread can also be temporarily suspended or blocked from entering into the runnable and
subsequently running state by using either following thread methods.
sleep() - block for a specified time
suspend() - blocked until further order
wait() - blocked until certain condition occurs
What is the difference between sleep() and suspend()
Sleep() can be used to convert running state to waiting state and automatically thread
convert from waiting state to running state once the given time period is completed.
Where as suspend() can be used to convert running state thread to waiting state but it will
never return back to running state automatically.
9. Thread Priority
Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread scheduler schedules the threads according to their priority (known as
preemptive scheduling).
Three types of Thread Priority
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
The following are the methods of thread
class
getPriority() - This method is used to get the current priority of thread.
setPriority() - This method is used to set the current priority of thread.
getName() - This method is used to get the current executing thread name.
setName() - This method is used to set the user-defined name for the thread.
run() - Which contains the main business logic that can be executed by multiple
threads simultaneously in every user defined thread class run method should be
overridden.
79
Prepared by: [Link], [Link]-BCA SNMV CAS
start() - Used to convert ready state thread to running state.
sleep() - Used to change running state thread to ready state based on time period it is
a static method should be called with class reference.
suspend() - used to convert running state thread to waiting state, which will never
come back to running state automatically.
resume() - Used to change the suspended thread state(waiting state) to ready state.
stop() - This method is used to convert running state thread to dead state.
getState() - This method is used to get the current state of thread.
10. Synchronization
Multithreading introduces asynchronous behavior to the programs. If a thread is writing some
data another thread may be reading the same data at that time. This may bring inconsistency.
When two or more threads need access to a shared resource there should be some way that
the resource will be used only by one resource at a time. The process to achieve this is called
synchronization.
o implement the synchronous behavior java has synchronous method. Once a thread is inside
a synchronized method, no other thread can call any other synchronized method on the same
object. All the other threads then wait until the first thread come out of the synchronized
block.
80
Prepared by: [Link], [Link]-BCA SNMV CAS
When we want to synchronize access to objects of a class which was not designed for the
multithreaded access and the code of the method which needs to be accessed synchronously
is not available with us, in this case we cannot add the synchronized to the appropriate
methods. In java we have the solution for this, put the calls to the methods (which needs to
be synchronized) defined by this class inside a synchronized block in following manner.
If we do not use syncronization, and let two or more threads access a shared resource at the
same time, it will lead to distorted results.
synchronized (object)
// statement to be synchronized
Example:
import [Link].*;
class callme
{
synchronized void call(int t)
{
[Link]("The"+t+"th table");
[Link]("*****************");
for(int i=1;i<=5;i++)
{
[Link](i+"*"+t+"="+i*t);
} } }
class caller implements Runnable
{
int tno;
callme target;
Thread th;
caller (callme c,int t,int p)
{
target=c;
tno=t;
th=new Thread(this);
81
Prepared by: [Link], [Link]-BCA SNMV CAS
[Link]();
}
public void run()
{
[Link](tno);
}
}
class soniya6
{
public static void main(String args[])
{
callme target=new callme();
caller five=new caller(target,5,Thread.MAX_PRIORITY);
caller seven=new caller(target,7,Thread.MIN_PRIORITY);
caller nine=new caller(target,9,Thread.NORM_PRIORITY);
}
}
Output:
1*5=5 1*9=9 1*7=7
2*5=10 2*9=18 2*7=14
3*5=15 3*9=27 3*7=21
4*5=20 4*9=36 4*7=28
5*5=25 5*9=45 5*7=35
82
Prepared by: [Link], [Link]-BCA SNMV CAS