0% found this document useful (0 votes)
2 views39 pages

Unit 4

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

Unit 4

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

Hindusthan

HindusthanCollege
Collegeof
ofEngineering
Engineering and Technology
Technology
An Autonomous Institution Affiliated to Anna University | Approved by AICTE, New Delhi
(An Autonomous
Accredited with ‘A’ GradeInstitution, Affiliated to
by NAAC | Accredited by Anna University,
NBA (ECE, MECH, Chennai)
EEE, IT & CSE)
ValleyValley
Campus,Campus,
PollachiPollachi
Highway,Highway, Coimbatore
Coimbatore 641 032.| –www.hicet.ac.in
641032

22CS3251 / OBJECT ORIENTED PROGRAMMING


USING JAVA

UNIT 4 - MULTITHREADING, PACKAGES AND COLLECTIONS


Threads-lifecycle and stages of a Thread-Thread priority-main Thread-Runnable interface-naming
thread-start () method-Java packages-built in packages-user defined packages-Collections-List
interface-Queue interface-Map interface-Set-Iterator Comparator-JDBC-connectivity with JDBC-
DriverManager-Statement-JDBC Exceptions.

1.1 MULTITHREADING
Multithreading in java is a process of executing multiple threads simultaneously. A multithreaded
program contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form
of multitasking.
Multiprocessing and multithreading, both are used to achieve multitasking. However, we use
multithreading than multiprocessing because threads use a shared 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.

What is a Thread?
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution. Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

As shown in the above figure, a thread is executed inside the process. There is context-switching
betweenthe threads. There can be multiple processes inside the OS, and one process can have
multiple threads.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the 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 an exception occurs in a single
thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize
the CPU. Multitasking can be achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
 A process-based multitasking is the feature that allows our computer to run two or more
programs concurrently. For example, process-based multitasking enables us to run the Java
compiler at the same time that we are using a music player.
 Each process has an address in memory. In other words, each process allocates a separate
memoryarea.
 A process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
 In a thread-based multitasking environment, the thread is the smallest unit of dispatchable
code. This means that a single program can perform two or more tasks simultaneously.
 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.

1.2 JAVA THREAD MODEL


One thread can pause without stopping other parts of your program. For example, the idle time created
when a thread reads data from a network or waits for user input can be utilized else where. When a
thread blocks in a Java program, only the single thread that is blocked pauses. All other threads
continue to run.
Life Cycle of a Thread
A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM.
The java thread states are as follows:
1) New
2) Active
3) Blocked / Waiting
4) Timed Waiting
5) Terminated
New: Whenever a new thread is created, it is always in the new state. For a thread in the new state,
the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active state. The
active state contains two states within it: one is runnable, and the other is running.
 Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state,
the thread may be running or may be ready to run at any given instant of time. It is the duty of the
thread scheduler to provide the thread time to run, i.e., moving the thread the running state. A
program implementing multithreading acquires a fixed slice of time to each individual thread.
Each thread runs for a short span of time and when that allocated time slice is over, the thread
voluntarily gives up the CPU to the other thread, so that the other threads can also run for their
slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting
for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the
threads lie.

 Running: When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to running and again
back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the
thread is in the blocked state or is in the waiting state.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has
entered the critical section of a code and is not willing to leave that critical section. In such a scenario,
another thread (its name is B) has to wait forever, which leads to starvation. To avoid such scenario, a timed
waiting state is given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. The
sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start
its execution from when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
 When a thread has finished its job, then it exists or terminates normally.
 Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there
is no way one can respawn (active after kill) the dead thread.
1.3 THREAD PRIORITY
 Java assigns to each thread a priority that determines how that thread should be treated with
respect to the others.
 Priorities are represented by a number between 1 and 10.
 In most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses
 Java priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
 Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in whichthreads execute and very much platform dependent.
 A thread’s priority is used to decide when to switch from one running thread to the next. This
is called a context switch.
The rules that determine when a context switch takes place are simple:
 A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping,
or blocking on pending I/O. In this scenario, all other threads are examined, and the highest
priority thread that is ready to run is given the CPU.
 A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread
that does not yield the processor is simply preempted—no matter what it is doing— by a
higher- priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This
is called preemptive multitasking.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its
general form:
final void setPriority(int level)
Here, level specifies the new priority setting for the calling thread. The value of level must be within
the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively.
To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These
priorities are defined as static final variables within Thread. You can obtain the current priority setting
by calling the getPriority() method of Thread, shown here:
final int getPriority( )
Program

class Main
{
public static void main(String[] args) throws InterruptedException
{
Thread t1 = new Thread(() -> {
System.out.println("Thread in execution");
System.out.println("Current state of the thread - " + Thread.currentThread().getState());
});
System.out.println("State of the thread - " + t1.getState());
System.out.println("Priority of the thread t1 is : " + t1.getPriority());
t1.setPriority(6);
t1.start();
t1.join();
System.out.println("Priority of the thread t1 is : " + t1.getPriority());
System.out.println("State of the thread - " + t1.getState());
Thread t2 = new Thread(() -> {
System.out.println("Thread in execution");
System.out.println("Current state of the thread - " + Thread.currentThread().getState());
});
System.out.println("State of the thread - " + t2.getState());
System.out.println("Priority of the thread t1 is : " + t2.getPriority());
t2.setPriority(9);
t2.start();
t2.join();
System.out.println("State of the thread - " + t2.getState());
System.out.println("Priority of the thread t2 is : " + t2.getPriority());
}
}
Output
State of the thread - NEW
Priority of the thread t1 is : 5
Thread in execution
Current state of the thread - RUNNABLE
Priority of the thread t1 is : 6
State of the thread - TERMINATED
State of the thread - NEW
Priority of the thread t1 is : 5
Thread in execution
Current state of the thread - RUNNABLE
State of the thread – TERMINATED
Priority of the thread t2 is : 9

1.4 THE THREAD CLASS AND THE RUNNABLE INTERFACE


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Creating Thread by extending Thread class:
To create a thread is to create a new class that extends Thread, and then to create an instance of that
class. The extending class must override the run ( ) method, which is the entry point for the new
thread. It must also call start ( ) to begin execution of the new thread.
Thread class provide constructors and methods to create and perform operations on a thread. Thread
class extends Object class and implements Runnable interface.
The Thread class defines several methods that help manage threads.

Method Meaning

getName Obtain a thread’s name.

getPriority Obtain a thread’s priority.

isAlive Determine if a thread is still running.

join Wait for a thread to terminate.

run Entry point for the thread.


sleep Suspend a thread for a period of time.

start Start a thread by calling its run method.

Example:
class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new
Multi(); t1.start();
}
}
Output: thread is running...

Creating Thread by Implementing Runnable interface


The easiest way to create a thread is to create a class that implements the Runnable interface.

 To implement Runnable, a class need only implement a single method called run( ),
which is declared like this:
public void run( )
We will define the code that constitutes the new thread inside run() method. It is important to
understand that run() can call other methods, use other classes, and declare variables, just like the
main thread can.

 After we create a class that implements Runnable, you will instantiate an object of type Thread
from within that class. Thread defines several constructors. The one that we will use is shown
here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the
new thread is specified by threadName.
 After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. The start( ) method is shown here:
void start( );
Here is an example that creates a new thread and starts it running:
Example:
class Multi implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi obj=new Multi();
Thread t1 =new
Thread(obj); t1.start();
}
}
Output: thread is running...

1.5 CREATING MULTIPLE THREADS


We have been using only two threads: the main thread and one child thread. However, our program
canspawn as many threads as it needs. For example, the following program creates three child
threads:
If you have to perform single task by many threads, have only one run() method. For example:
Program for generating four threads to perform following operations:

 Getting N numbers as input


 Printing even numbers
 Printing odd numbers
 Computing average

import java.util.Scanner;
class MyThread1 extends Thread
{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
int nums[] = new int[n];
System.out.println("Enter " + n + " numbers");
for(int i = 0; i < n; i++)
{
nums[i] = in.nextInt();
}
}
}
class MyThread2 extends Thread
{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
System.out.println("Even numbers in the range 1 - " + n);
for(int i = 2; i <= n; i = i + 2)
System.out.println(i + " ");
}
}

class MyThread3 extends Thread


{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
System.out.println("Odd numbers in the range 1 - " + n);
for(int i = 1; i <= n; i = i + 2)
System.out.println(i + " ");
}
}

class MyThread4 extends Thread


{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
int sum = 0;
float avg = 0.0f;
for(int i = 0; i < n; i++)
sum = sum + i;
avg = (float) sum / n;
System.out.println("Average is : " + avg);
}
}
public class Main
{
public static void main(String[] args) throws InterruptedException
{
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
MyThread4 t4 = new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example:
Program of performing two tasks by two threads
Example:
class A implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("A = "+i);
}
}
}
class B implements Runnable
{
synchronized public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("B = "+i);
}
}
}
class C implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("C = "+i);
}
}
}
class ExampleThread
{
public static void main(String[] args)
{
A obj1 = new A();
B obj2 = new B();
C obj3 = new C();
Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2);
Thread t3 = new Thread(obj3); t3.setPriority(7);
t2.setPriority(Thread.MAX_PRIORITY);
int n = t3.getPriority();
System.out.println("Priority of Thread t3 is " + n); t1.start();
t2.start();
t3.start();
}
}
OUTPUT:
Priority of Thread t3
is 7 A = 1
B=1
A=2
B=2
B=3
A=3
B=4
C=1
B=5
A=4
C=2
A=5
C=3
C=4
C=5
Using isAlive( ) and join( )
Two ways exist to determine whether a thread has finished. First, we can call isAlive( ) on the thread.
This method is defined by Thread, and its general form is shown here:
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false
otherwise. While isAlive( ) is occasionally useful, the method that you will more commonly use to
wait for a thread to finish is called join( ), shown here:
final void join ( ) throws InterruptedException
This method waits until the thread on which it is called terminates. Its name comes from the concept
of the calling thread waiting until the specified thread joins it. Additional forms of join ( ) allow you
to specify a maximum amount of time that you want to wait for the specified thread to terminate.
Example program
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try{wait();}
catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Main
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run(){c.withdraw(15000);}
}.start();

new Thread()
{
public void run(){c.deposit(10000);}
}.start();
}
}

1.6 SYNCHRONIZATION
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.
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an object
that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given
time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting
to enter the locked monitor will be suspended until the first thread exits the monitor. These other
threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same
monitor if it so desires.

Using Synchronized Methods:


Synchronization is easy in Java, because all objects have their own implicit monitor associated
with them. To enter an object’s monitor, just call a method that has been modified with the
synchronizedkeyword. While a thread is inside a synchronized method, all other threads that try to
call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and
relinquish control of the object to the next waiting thread, the owner of the monitor simply returns
from the synchronized method.
Example 1:
class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*
i); try
{
Thread.sleep(400);
}
catch(Exception e)
{ System.out.println(e); }
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Tab
le t)
{ this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Tab
le t)
{ this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table();//only one
object MyThread1 t1=new
MyThread1(obj); MyThread2 t2=new
MyThread2(obj); t1.start();
t2.start();

}
}
Output:
5
10
15
20
25
100
200
300
400
500

Using synchronized Statement:


The general form of the synchronized statement:
synchronized (object)
{
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block ensures that a call
to a method that is a member of object occurs only after the current thread has successfully entered
object’s monitor.
class Table
{
void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*
i); try
{
Thread.sleep(400);
}
catch(Exception e)
{System.out.println(e);}
}
}
}
class MyThread1 extends Thread
{
Table t ; int N; MyThread1(Table t,int n)
{
this.t = t;
N = n;
}
public void run()
{
synchronized(t) //synchronized block
{
t.printTable(n);
}
}
}
public class Test
{
public static void main(String args[])
{
Table obj = new Table();//only one
object MyThread1 t1=new
MyThread1(obj); MyThread1 t2=new
MyThread1(obj); t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
1.7 INTER THREAD COMMUNICATION USING wait, notify and notifyAll
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()
wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters
the same monitor and calls notify( ). notify( ) wakes up the first thread that called wait( ) on the same
object. notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority
thread will run first. These methods are declared within Object, as shown here:
final void wait( ) throws
InterruptedExceptionfinal void notify( )
final void notifyAll( )
Steps for Inter thread communication:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.

class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount)


{
System.out.println("going to
deposit..."); this.amount+=amount;
System.out.println("deposit
completed... ");notify();
}
}
class Samp1
{
public static void main(String args[])
{
final Customer c=new
Customer();new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}
Output:
going to withdraw...
Less balance; waiting for
deposit...going to deposit...
deposit
completed...
withdraw
completed
1.8 PACKAGE
 A Java package is a set of classes, interfaces, and sub-packages that are similar.
 Packages are divided into two categories:
o Built-in Packages (packages from the Java API)
o User-defined Packages (create your own packages)
 Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
o Preventing naming conflicts. For example there can be two classes with name Employee
in two packages, college.staff.cse.Employee and college.staff.ee.Employee
o Making searching/locating and usage of classes, interfaces, enumerations and annotations
easier
o Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A
default member (without any access specifier) is accessible by classes in the same
package only.
o Packages can be considered as data encapsulation (or data-hiding).
Built-in Packages
These packages consist of many classes which are a part of Java API. Some of the commonly used built-
in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

To use a class or a package from the library, you need to use the import keyword:
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Import a Class
If a class want to be used from a package, for example, the Scanner class, which is used to get user input,
write the following code:
import java.util.Scanner;

User-defined packages
 To create a package, include a package command as the first statement in a Java source file. Any
classes declared within that file will belong to the specified package.
 The package statement defines a name space in which classes are stored. If the package statement
is omitted, the class names are put into the default package, which has no name.
 While the default package is fine for short, sample programs, it is inadequate for real applications.
 This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package called
MyPackage.
package MyPackage;

Example
package MyPack;
class Balance
{
String name; double bal;
Balance(String n, double b)
{
name = n; bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> "); JAVA LANGUAGE System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3]; current[0] = new Balance("Sanjib", 123.23); current[1] = new
Balance("Chandan", 157.02); current[2] = new Balance("Palak", -12.33); for(int i=0; i<3; i++)
current[i].show();
}
}

Call this file AccountBalance.java, and put it in a directory called MyPack. Next, compile the file. Make
sure that the resulting .class file is also in the MyPack directory. Then try executing the AccountBalance
class, using the following command line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this command, or to
have your CLASSPATH environmental variable set appropriately. As explained, AccountBalance is
now part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot
use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.

1.9 ACCESS PROTECTION


In Java, access specifiers are used to defining the visibility and accessibility of class members such as
variables, methods, and inner classes. Java has four access specifiers: public, private, protected, and
default (also known as package-private). The following table shows the scope of each access specifier
in Java
Importing Packages
 Given that packages exist and are a good mechanism for compartmentalizing diverse classes
from each other, it is easy to see why all of the built-in Java classes are stored in packages.
 In a Java source file, import statements occur immediately following the package statement (if
it exists) and before any class definitions. This is the general form of the import statement:
import pkg1 [.pkg2].(classname|*);

package MyPack;
public class Balance
{
String name; double bal;
public Balance(String n, double b)
{
name = n; bal = b;
}
public void show()
{
if(bal<0) System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
As we can see, the Balance class is now public. Also, its constructor and its show( ) method are public,
too. This means that they can be accessed by any type of code outside the MyPack package. For example,
here TestBalance imports MyPack and is then able to make use of the Balance class:

import MyPack.*; class TestBalance


{
public static void main(String args[])
{
Balance test = new Balance("J. J. Jaspers", 99.88); test.show(); // you may also call show()
}
}

1.10 COLLECTION
In general terms a collection is a “group of objects”

Collection is a container object. It is used for storing homogeneous and heterogeneous, unique and duplicate
objects without size limitation and further it is used for sending objects at a time from one class methods to
other class methods as method arguments and return type with single name across multiple layers of the project.

 Before java 1.2 it is called simply Java.util package


 From java 1.2 onwards its all classes together called as Collections Framework
 From java 5 onwards they have added new concepts called Collections and Generics
Java Collections Framework all classes are divided into following 3 different types of classes:
1. Container Objects classes
2. Cursor Objects classes
3. Utility Objects classes

Container Objects classes:


Following 4 Interfaces are called container objects
1. List <T> HashSet <T>, LinkedHashSet<T>
2. Set <T> Stack <T>, LinkedList<T>, ArrayList<T>, Vector<T>
3. Map <K,V> HashMap <K,V>, Hashtable<K,V>
4. Queue <T> LinkedList <T>
<T> Represents generic type parameter, i.e which type of elements are being stored.

Cursor objects are retrieving objects


5. Enumeration
6. Iterator
7. ListIterator

Utility Objects: it is nothing but a class that is given to perform different operations on container
objects are called utility objects i.e two classes
8. Collections class
9. Arrays

The Collection in Java is a framework that provides architecture to store and manipulate thegroup of objects.
1. Collections are the containers that groups multiple items in a single unit
2. It provides architecture to store and manipulate a group of objects
3. Using collections various operations can be performed on the data like
 searching,
 sorting,
 insertion,
 manipulation,
 deletion etc.
4. Java collection framework provide many Interfaces and classes
Collection Interfaces and class hierarchy

Iterable is the root interface of the Java collection classes. The Collection interface extends
Iterable interface, so all subtypes of Collection implement the Iterable interface. This interface stands
to represent data-structures whose value can be traversed one by one. This is an important property.
Choosing the Right Collection

SETS:
A set represents a group of elements arranged just like an array. The set will grow dynamically when the
elements are stored into it. A set will not allow duplicate elements. If we try to pass for same element that is
already available in the set, then it is not stored into the set.

LIST:
Lists are like sets. They store a group of elements. But lists allow duplicate values to be stored.
QUEUES:
A Queue represents arrangement of elements in FIFO (First In First Out) order. This means that an element
that is stored as a first element into the queue will be removed first from the queue.

MAPS:
Maps store elements in the form of key and value pairs. If the key is provided then
it’scorrespond value can be obtained. Of course, the keys should have unique values.
In the hierarchy we can divided into two groups
1. If your requirement is to group key-value pair, then choose MAP
2. If your requirement (operations are on only values) is to have only the values, then choose
collection interfaces

Retrieving Elements from Collections


Following 4 ways to retrieve any element from a collection object
1. Using for-each loop.
2. Using Iterator interface.
3. Using Listlterator interface.
4. Using Enumeration interface.
1. For-each loop:
This is like for loop which repeatedly executes a group of statements for each element of the collection. The
format is:

for(variable : collection-object)
{
Statements:
}

Here, the variable assumes each element of the collection-object and the loop is executed as many times as there
are number of elements in the collection-object. If collection-object has n elements the loop is executed exactly
n times and the variable stores each element in each step.
Example using for-each loop

class ForEachDemo{
public static void main(String args[]){
int arr[] = {12,13,14,44}; //declaring an array for(int i : arr){
//traversing the array with for-each
loopSystem.out.println(i);

}
}
}
Output: 12

13
14
44

2. Iterator Interface: Iterator is an interface that contains methods to retrieve the elements one by one
from a collection object. It retrieves elements only in forward direction. It has 3 methods:

3. ListIterator Interface: ListIterator is an interface that contains methods to retrieve the elements
from a collection object, both in forward and reverse directions. It can retrieve the elements in forward
and backward direction. It has the following important methods:
4. Enumeration Interface: This interface is useful to retrieve elements one by one like Iterator. It
has 2 methods.

HashSet Class
HashSet Class: HashSet represents a set of elements (objects). It does not guarantee the
order of elements. Also it does not allow the duplicate elements to be stored.
We can write the HashSet class as : class HashSet <T>
We can create the object as : HashSet <String> hs = new HashSet<String> ();

The following constructors are available in HashSet:

HashSet();
HashSet (int capacity); Here capacity represents how many elements can be stored into the HashSet
initially. This capacity may increase automatically when more number of elements is being stored.
Program : Write a program which shows the use of HashSet and Iterator. package
com.myPack;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetDemo
{
public static void main(String[] args)
{
HashSet <String> hs = new HashSet<String> ();
hs.add ("Anil"); hs.add ("Akshara");
hs.add ("Babji");
hs.add ("Charan");
hs.add ("Raman");
// hs.add("India");
System.out.println ("HashSet = " + hs);
Iterator<String> it = hs.iterator ();
//display element by element using Iterator
System.out.println ("Elements Using Iterator: ");
while (it.hasNext() )
{
String s = (String) it.next ();
System.out.println(s);
}
}
}

Output:
HashSet = [Akshara, Raman, Babji, Anil, Charan]Elements Using Iterator: Akshara
Raman Babji
Anil Charan
Program on Hashset

LinkedHashSet Class
LinkedHashSet Class: This is a subclass of HashSet class and does not contain any additional members
on its own. LinkedHashSet internally uses a linked list to store the elements. It is a generic class that has
the declaration:

class LinkedHashSet <T>


Stack Class: A stack represents a group of elements stored in LIFO (Last In First Out) order. This means
that the element which is stored as a last element into the stack will be the first element to be
removed from the stack. Inserting the elements (Objects) into the stack is called push operation and
removing the elements from stack is called pop operation.

Searching for an element in stack is called peep operation. Insertion and deletion of elements
take place only from one side of the stack, called top of the stack.
We can write a Stack class as:
class Stack<E>
e.g.: Stack<Integer> obj = new Stack<Integer> (); Stack
Class Methods:
Program : Write a program to perform different operations on a stack.
import java.util.*;
class Stack1
{
int top = -1, st[]=new int[5];
void push(int el)
{
st[++top]=el;
}
int pop()
{
return(st[top--]);
}
void display()
{
System.out.println("\nStack elements from top to bottom\n"); for(int
i=top;i>=0;i--)

System.out.println(st[i]);
}
boolean isFull()
{
return(top==5-1);
}
boolean isEmpty()
{
return(top==-1);
}
}
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); Stack1 s
= new Stack1();
int el = 0, ch=1;
while(ch != 4)
{
System.out.println("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT"); System.out.println("ENTER
YOUR CHOICE");
ch=sc.nextInt();
switch(ch)
{
case 1 :
if(s.isFull()) System.out.println("\nstack
is full"); else

{
System.out.println("Enter element");
el=sc.nextInt();
s.push(el);
}
break;
case 2:
if(s.isEmpty()) System.out.println("\nstack is
empty"); else

{
el=s.pop();
System.out.println("\nDeleted element = "+el);
}
break;
case 3:
if(s.isEmpty()) System.out.println("\nstack is
empty"); else
s.display(); break;
case 4:
break;
default:
System.out.println("\nEnter correct choice");
}
}
sc.close();
}
}

OUTPUT:
C:\Users\Anil\Desktop\2018 Java>javac Stack.java
C:\Users\Anil\Desktop\2018 Java>java Stack
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
10
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
20
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
30
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 3
Stack elements from top to bottom 30
20
10

PUSH
1. POP
2. DISPLAY
4.EXIT
ENTER YOUR CHOICE 1
Enter element
40
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 3
Stack elements from top to bottom 40
30
20
10

1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
50
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 3
Stack elements from top to bottom 50
40
30
20
10

1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 2
Deleted element = 50
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 4

ArrayList Class

ArrayList Class: An ArrayList is like an array, which can grow in memory dynamically. ArrayList is
not synchronized. This means that when more than one thread acts simultaneously on the ArrayList
object, the results may be incorrect in some cases.

ArrayList class can be written as:


class ArrayList <E>
We can create an object to ArrayList as:
ArrayList <String> arl = new ArrayList<String> ();
Program : Write a program that shows the use of ArrayList class.

package com.myPack;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListDemo {


public static void main(String[] args) {
ArrayList <String> al = new ArrayList<String>();al.add ("Asia");
al.add ("North America Carona");al.add ("South America"); al.add
("Africa");

al.add ("Europe");

al.add (1,"Australia");
al.add (2, "Antarctica");
al.add (4, "Carona");
System.out.print ("Size of the Array List is: \n" +al.size ()); System.out.print
("\nRetrieving elements inArrayList using Iterator :\n"); Iterator<String> it =
al.iterator ();
while (it.hasNext () ) System.out.print
("\n" +it.next ());
}
}
Output:
Size of the Array List is:
8
Retrieving elements in ArrayList using Iterator : Asia
Australia Antarctica
North Ameria CaronaCarona
South AmericaAfrica Europe
Program on ArrayList

LinkedList Class: A linked list contains a group of elements in the form of nodes. Each node will
have three fields- the data field contatins data and the link fields contain references to previous and
next nodes.A linked list is written in the form of:

class LinkedList<E>
we can create an empty linked list for storing String type elements (objects) as:
LinkedList <String> ll = new LinkedList<String> ();
LinkedList Class methods:

Note: In case of LinkedList counting starts from 0 and we start counting from 1.

Program : Write a program that shows the use of LinkedList class.


import java.util.LinkedList;
public class LinkedListDemo {

public static void main(String[] args) {


LinkedList <String> ll = new LinkedList<String>(); ll.add
("Anil");
ll.add ("Bharathi");
ll.add ("Charan"); ll.add
("Chiranjeevi");
ll.addFirst ("Eega");
ll.add (1,"Abishai");

ll.add (2,"Abhimanyu");
System.out.println ("Elements in Linked List is :\n "+ ll);System.out.println ("Size of the
Linked List is : \n" + ll.size() );
}
}

Output:
Elements in Linked List is:
[Eega, Abishai, Abhimanyu, Anil, Bharathi, Charan,Chiranjeevi]

Size of the Linked List is:7

Program on linked List

Java Database Connectivity (JDBC)


JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a specification from Sun Microsystems that provides a standard
abstraction (API or Protocol) for Java applications to communicate with various databases. It
provides the language with Java database connectivity standards. It is used to write programs
required to access databases. JDBC, along with the database driver, can access databases and
spreadsheets. The enterprise data stored in a relational database(RDB) can be accessed with the
help of JDBC APIs.

Definition of JDBC (Java Database Connectivity)


JDBC is an API (Application programming interface) used in Java programming to interact with
databases. The classes and interfaces of JDBC allow the application to send requests made by
users to the specified database.

Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to interact with databases to
store application-specific information. So, interacting with a database requires efficient database
connectivity, which can be achieved by using the ODBC (Open database connectivity) driver. This
driver is used with JDBC to interact or communicate with various kinds of databases such as
Oracle, MS Access, Mysql, and SQL server database.

Components of JDBC
There are generally four main components of JDBC through which it can interact with a database.
1. JDBC API: It provides various methods and interfaces for easy communication with the
database. It provides two packages as follows, which contain the java SE and Java EE
platforms to exhibit WORA (write once run anywhere) capabilities. The java.sql package
contains interfaces and classes of JDBC API.
2. JDBC Driver manager: It loads a database-specific driver in an application to establish
a connection with a database. It is used to make a database-specific call to the database to
process the user request.
3. JDBC Test suite: It is used to test the operation (such as insertion, deletion, updation)
being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge
translates the JDBC method call to the ODBC function call. It makes use of the
sun.jdbc.odbc package which includes a native library to access ODBC characteristics.

JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand. There are 4
types of JDBC drivers:
Type-1 driver or JDBC-ODBC bridge driver
Type-2 driver or Native-API driver (partially java driver)
Type-3 driver or Network Protocol driver (fully java driver)
Type-4 driver or Thin driver (fully java driver)
a. JDBC CRUD (Create, Read, Update and Delete) example
Step 1: Establish connection with database
Step 2: Create following table in MySQL database server
use test;
create table Emp(
code varchar(10) primary key,
name varchar(40) null,
city varchar(20),
salary int
);
Step3 : Following code to insert record in the above table -
public void insertEmp(String code, String name, String city, int sal) {
try {
ps = con.prepareStatement(“insert into Emp values(?,?,?,?)”);
ps.setString(1, code);
ps.setString(2, name);
ps.setString(3, city);
ps.setInt(4, sal);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“Inserted”);
} else {
System.out.println(“not Inserted”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Step4 : Following source code is to update employee city and salary based on employee code -
public void updateEmp(String code, String city, int salary) {
try {
ps = con.prepareStatement(“update emp set city=?,salary=salary+? where code=?”);
ps.setString(1, city);
ps.setInt(2, salary);
ps.setString(3, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“updated”);
} else {
System.out.println(“not updated”);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Step5 : Following source code is to delete an employee record based on employee code -
public void deleteEmp(String code) {
try {
ps = con.prepareStatement(“delete from emp where code=?”);
ps.setString(1, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“deleted”);
} else {
System.out.println(“not deleted”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Step6 : Following source code is to display an employee record based on employee code -
public void dispAnEmp(String s) {
try {
ps = con.prepareStatement(“select * from Emp where code=?”);
ps.setString(1, s);
ResultSet res = ps.executeQuery();
if (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Step7 : Following source code is to display whole records from employee table -
public void dispAll() {
try {
Statement st = con.createStatement();
ResultSet res = st.executeQuery(“select * from Emp”);
while (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}

You might also like