2. Multithreading in Java
•
•
•
•
Multithreading in Java is a process of executing multiple
threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of
processing. 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.
3. 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.
4. Process-based Multitasking (Multiprocessing)
•
•
•
•
Each process has an address in memory. In other
words, each process allocates a separate
memory area.
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.
6. Difference between Multitasking and Multithreading
Difference between Multitasking and Multithreading
S.N
O
Multitasking Multithreading
1.
In multitasking, users are allowed to perform many
tasks by CPU.
While in multithreading, many threads are created from a process
through which computer power is increased.
2.
Multitasking involves often CPU switching between
the tasks.
While in multithreading also, CPU switching is often involved
between the threads.
3.
In multitasking, the processes share separate
memory.
While in multithreading, processes are allocated same memory.
4. Multitasking component involves multiprocessing.
While multithreading component does not involve
multiprocessing.
5.
In multitasking, CPU is provided in order to execute
many tasks at a time.
While in multithreading also, CPU is provided in order to execute
many threads from a process at a time.
6.
In multitasking, processes don’t share same
resources, each process is allocated separate
resources.
While in multithreading, each process share same resources.
7. Multitasking is slow compared to multithreading. While multithreading is faster.
8.
In multitasking, termination of process takes more
While in multithreading, termination of thread takes less time.
7. Multitasking:
Multitasking is when a CPU is provided to execute multiple tasks at a time. Multitasking
involves often CPU switching between the tasks, so that users can collaborate with each
program together. Unlike multithreading, In multitasking, the processes share separate
memory and resources. As multitasking involves CPU switching between the tasks rapidly, So
the little time is needed in order to switch from the one user to next.
8. Multithreading:
Multithreading is a system in which many threads are created from a process through
which the computer power is increased. In multithreading, CPU is provided in order to
execute many threads from a process at a time, and in multithreading, process creation is
performed according to cost. Unlike multitasking, multithreading provides the same
memory and resources to the processes for execution.
9. What is Thread in java
•
•
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.
10. Life cycle of a Thread
• Like process, thread have its life cycle that includes various phases like: new,
running, terminated etc. we have described it using the below image.
11. Thread States
1.
2.
3.
4.
5.
New : A thread begins its life cycle in the new state. It remains in
this state until the start() method is called on it.
Runnable : After invocation of start() method on new thread, the
thread becomes runnable.
Running : A thread is in running state if the thread scheduler has
selected it.
Waiting : A thread is in waiting state if it waits for another thread
to perform a task. In this stage the thread is still alive.
Terminated : A thread enter the terminated state when it
complete its task.
12. Methods of Multithreading in Java
Methods Description
void start() Causes the Thread to begin execution
void run() Utilised to carry out a thread's action.
long getId() Returns the identifier of the thread
final String getName() Returns the threads name
final void setName(String name) Sets the name of the thread
final int getPriority() Returns thread’s priority
final void setPriority(int newPriority) Changes the priority if the thread
boolean isAlive() It checks to see if the Thread is alive.
void suspend() It is used to suspend the Thread.
void resume() The suspended Thread is resumed using it.
void stop() The Thread is stopped using it.
13. void destroy() The thread group and all of its subgroups are destroyed using it.
static void sleep(long millis) throws InterruptedException
Causes the currently executing Thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
static Thread currentThread() Returns a reference to the currently executing thread object.
static void yield()
A hint to the scheduler that the current Thread is willing to yield its
current use of a processor.
final void join() throws InterruptedException Waits for the Thread to die
boolean isDaemon() It checks to see if a thread is a daemon thread.
void setDaemon() It marks the Thread as daemon or user thread.
void interrupt() It interrupts the Thread.
boolean isinterrupted() It checks to see if the Thread has been interrupted.
static boolean interrupted() It checks to see whether the current Thread has been interrupted.
static int activeCount()
It gives back how many threads are currently active in the thread
group of the current Thread.
void checkAccess()
It determines if the currently running Thread has permission to
modify the Thread.
14. Thread Priorities
•
•
•
Java thread 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
which threads execute and are very much platform dependent.
15. Java Thread Methods
S.N. Modifier and Type Method Description
1) void start() It is used to start the execution of the thread.
2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread object.
5) void join() It waits for a thread to die.
16. 6) int getPriority() It returns the priority of the thread.
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
17. 12) s t a t i c
void
yield() It causes the currently executing thread object to pause and allow
other threads to execute temporarily.
13) void suspend() It is used to suspend the thread.
14) void resume() It is used to resume the suspended thread.
15) void stop() It is used to stop the thread.
16) void destroy() It is used to destroy the thread group and all of its subgroups.
17) boolean isDaemon() It tests if the thread is a daemon thread.
18) void setDaemon() It marks the thread as daemon or user thread.
19) void interrupt() It interrupts the thread.
20) boolean isinterrupted() It tests whether the thread
18. How to create a thread ?
•
•
In Java there are two ways to create a thread
1) By Extending the class
2) By Implementing the Runnable Interface
19. Program: Creating thread By Extending the
thread class
Program: Creating thread By Extending the
thread class
class Brother extends Thread{
public void run(){
for(int i=1;i=5;i++){
System.out.println( Hey, I am Elder and Boy i
will Eat this Pizza First : );
System.out.println( Drinking Water in Middle,
Just Wait);
System.out.println(---------------------------------------
--------------------- );
try {
Thread.sleep(1000);}
catch(Exception e) {}
}}}
class Sister extends Thread{
public void run(){
for(int i=1;i=5;i++){
System.out.println(Hey, Stupid I will Eat First
Beacuse I'm getting hungry !);
System.out.println( Govt Gave 33%
Reservations for us );
System.out.println(-----------------------------------------
-------------------- );
try {
Thread.sleep(1000);
}catch(Exception e) {
}}}}
public class MotherThread{
public static void main(String args[]){
Brother obj1=new Brother();
Sister obj2=new Sister();
obj1.start();
obj2.start();
}}
20. Program: Creating thread By
implementing the Runnable interface
Program: Creating thread By
implementing the Runnable interface
class Singer implements Runnable {
public void run(){
for(int i=1;i=5;i++){
System.out.println( Singer is Singing a Song );
System.out.println( -----------------------------);
try {
Thread.sleep(2000);}
catch(Exception e) {}
}}}
class Musician implements Runnable{
public void run(){
for(int i=1;i=5;i++){
System.out.println( Musician playing Drums, Gitar and
Piano );
try {
Thread.sleep(2000);
}
catch(Exception e) {}
}}}
public class MovieSong {
public static void main(String
args[]){
Runnable obj1=new Singer();
Runnable obj2=new Musician();
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
try {
Thread.sleep(2000);
} catch(Exception e) {}
t2.start();
}}
21. Synchronizing Threads in Java
Synchronizing Threads in Java
o
o
o
o
o
Multi-threaded programs may often come to a situation where multiple threads try
to access the same resources and finally produce erroneous and unforeseen results.
Synchronization is a process of handling resource accessibility by multiple thread
requests.
Synchronization is a process of handling resource accessibility by multiple thread
requests.
The main purpose of synchronization is to avoid thread interference.
The main purpose of synchronization is to avoid thread interference.
At times when more than one thread try to access a shared resource, we need to
ensure that resource will be used by only one thread at a time.
At times when more than one thread try to access a shared resource, we need to
ensure that resource will be used by only one thread at a time.
The process by which this is achieved is called synchronization.
The process by which this is achieved is called synchronization.
The synchronization keyword in java creates a block of code referred to as critical
section.
The synchronization keyword in java creates a block of code referred to as critical
section.
23. Java Synchronized Method
class Table{
synchronized void printTable(int n){
//synchronized method
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(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
} }
class MyThread2 extends Thread{
Table t;
MyThread2(Table 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();
} }
24. Synchronized method by using anonymous class
//Program of synchronized method by
using
anonymous class
class Table{
synchronized void printTable(int n){
//synchronized method
for(int i=1;i=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e){System.out.pri
ntln(e);}
} }
}
public class TestSynchronization3{
public static void main(String args[]){
f i
nal Table obj = new Table();//only
one object
Thread t1=new Thread(){
public void run(){
obj.printTable(5);
} };
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
} };
t1.start();
t2.start();
}
}
Output
5
10
15
20
25
100
200
300
400
500
25. Inter-thread Communication in Java
•
•
•
•
•
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()
wait()
notify()
notify()
notifyAll()
notifyAll()
26. wait() method
wait() method
•
•
The wait() method causes current thread to release the lock and
wait until either another thread invokes the notify() method or
the notifyAll() method for this object, or a specif i
ed amount of
time has elapsed.
The current thread must own this object's monitor, so it must be
called from the synchronized method only otherwise it will
throw exception.
Method Description
public final void wait()throws InterruptedException It waits until object is notified.
public f inal void wait(long timeout)throws
InterruptedException
It waits for the specified amount of time.
27. notify() method
notify() method
The notify() method wakes up a single thread that is waiting on
this object's monitor.
If any threads are waiting on this object, one of them is chosen to be
awakened.
The choice is arbitrary and occurs at the discretion of the
implementation.
Syntax:
public final void notify()
29. Understanding the process of inter-thread communication
Understanding the process of inter-thread communication
•
1.
2.
3.
4.
5.
6.
The point to point explanation of the above diagram is as follows:
Threads enter to acquire lock.
Lock is acquired by on thread.
Now thread goes to waiting state if you call wait()
method on the object. Otherwise it releases the
lock and exits.
If you call notify() or notifyAll() method, thread
moves to the notified state (runnable state).
Now thread is available to acquire lock.
After completion of the task, thread releases the
lock and exits the monitor state of the object.
30. Inter-Thread Communication Example1:
import java.lang.*;
import java.io.*;
public class ThreadA {
public static void main(String[] args) throws
InterruptedException {
ThreadB b = new ThreadB();
b.start();
synchronized (b) {
System.out.println(main thread calling wait()
method); // step 1
b.wait();
System.out.println(main thread got notification
call); // step 4
System.out.println(total balance +
b.totalBalance);
}}}
•
class ThreadB extends Thread {
int totalBalance = 0;
public void run() {
synchronized (this) {
System.out.println(child Thread starts
calculation for total balance); // step 2
for (int i = 0; i = 10; i++) {
totalBalance = totalBalance + i;}
System.out.println(child thread gives
notification call); // step 3
this.notify();
}}}
Output:
31. Inter-Thread Communication Example1:
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println(going to withdraw...);
if(this.amountamount){
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 Test{
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
32. ThreadGroup in Java
•
•
•
•
•
Java provides a convenient way to group multiple threads in a
single object. In such a way, we can suspend, resume or
interrupt a group of threads by a single method call.
Java thread group is implemented by java.lang.ThreadGroup
class.
A ThreadGroup represents a set of threads. A thread group can
also include the other thread group.
The thread group creates a tree in which every thread group
except the initial thread group has a parent.
A thread is allowed to access information about its own thread
group, but it cannot access the information about its thread
group's parent thread group or any other thread groups.
33. Constructors of ThreadGroup class
• There are only two constructors of ThreadGroup class.
No. Constructor
Constructor Description
Description
1) ThreadGroup(String name) creates a thread group with given name.
2) ThreadGroup(ThreadGroup parent, String
name)
creates a thread group with a given parent
group and name.
34. Methods of ThreadGroup class
• There are many methods in ThreadGroup class. A list of ThreadGroup methods is given
below
S.N. Modifier
and
Type
Method Description
1) void checkAccess() This method determines if the currently running thread has permission to modify the thread
group.
2) int activeCount() This method returns an estimate of the number of active threads in the thread group and its
subgroups.
3) int activeGroupCount() This method returns an estimate of the number of active groups in the thread group and its
subgroups.
4) void destroy() This method destroys the thread group and all of its subgroups.
5) int enumerate(Thread[] list) This method copies into the specif i
ed array every active thread in the thread group and its
subgroups.
6) int getMaxPriority() This method returns the maximum priority of the thread group.
7) String getName() This method returns the name of the thread group.
8) ThreadG
roup
getParent() This method returns the parent of the thread group.
9) void interrupt() This method interrupts all threads in the thread group.
10) boolean isDaemon() This method tests if the thread group is a daemon thread group.
35. Let's see a code to group multiple threads.
ThreadGroup tg1 = new ThreadGroup(Group A);
Thread t1 = new Thread(tg1,new MyRunnable(),one);
Thread t2 = new Thread(tg1,new MyRunnable(),two);
Thread t3 = new Thread(tg1,new MyRunnable(),three);
36. ThreadGroup Example
public class ThreadGroupDemo implements
Runnable{
public void run() {
System.out.println(Thread.currentThread().getNam
e());
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupD
emo();
ThreadGroup tg1 = new ThreadGroup(Parent Thre
adGroup);
Thread t1 = new Thread(tg1, runnable,one);
t1.start();
Thread t2 = new Thread(tg1, runnable,two);
t2.start();
Thread t3 = new Thread(tg1, runnable,three);
t3.start();
S y s t e m . o u t . pr i n t l n ( T h r e a d G r o u p N a m e
: +tg1.getName());
tg1.list();
} }
37. Daemon Thread in Java
•
•
•
Daemon thread in Java is a service provider thread that provides
services to the user thread. Its life depend on the mercy of user
threads i.e. when all the user threads dies, JVM terminates this
thread automatically.
There are many java daemon threads running automatically e.g.
gc, finalizer etc.
You can see all the detail by typing the jconsole in the command
prompt. The jconsole tool provides information about the
loaded classes, memory usage, running threads etc.
38. Points to remember for Daemon Thread in
Java
•
•
•
It provides services to user threads for background
supporting tasks. It has no role in life than to serve user
threads.
Its life depends on user threads.
It is a low priority thread.
39. Methods for Java Daemon thread by Thread
class
No. Method Description
1) public void setDaemon(boolean
status)
is used to mark the current thread as daemon thread
or user thread.
2) public boolean isDaemon() is used to check that current is daemon.
40. public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println(daemon thread work);
}
else{
System.out.println(user thread work);
} }
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
} }
41. Enumerations in Java
•
•
•
•
The Enum in Java is a data type which contains a fixed set of constants.
Java Enums can be thought of as classes which have a fixed set of
constants (a variable that does not change). The Java enum constants are
static and final implicitly. It is available since JDK 1.5.
Enums are used to create our own data type like classes. The enum data
type (also known as Enumerated Data Type) is used to define an enum in
Java. Unlike C/C++, enum in Java is more powerful. Here, we can define
an enum either inside the class or outside the class.
Java Enum internally inherits the Enum class, so it cannot inherit any other
class, but it can implement many interfaces. We can have fields,
constructors, methods, and main methods in Java enum.
42. •
•
•
•
•
Points to remember for Java Enum
Enum improves type safety
Enum can be easily used in switch
Enum can be traversed
Enum can have fields, constructors and
methods
Enum may implement many interfaces but
cannot extend any class because it internally
extends Enum class
Output:
WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
class EnumExample1{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//creating the main method
public static void main(String[] args) {
//printing all enum
for (Season s : Season.values()){
System.out.println(s); }
S y s t e m . o u t . p r i n t l n ( V a l u e o f W I N T E R i s
: +Season.valueOf(WINTER));
S y s t e m . o u t . p r i n t l n ( I n d e x o f W I N T E R i s
: +Season.valueOf(WINTER).ordinal());
S y s t e m . o u t . p r i n t l n ( I n d e x o f S U M M E R i s
: +Season.valueOf(SUMMER).ordinal());
}}
43. Autoboxing and Unboxing:
•
•
The automatic conversion of primitive data types into its equivalent
Wrapper type is known as boxing and opposite operation is known as
unboxing. This is the new feature of Java5. So java programmer
doesn't need to write the conversion code.
Advantage of Autoboxing and Unboxing:
No need of conversion between primitives and Wrappers manually so
less coding is required.
class BoxingExample1{
public static void main(String args[]){
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
System.out.println(a2+ +a3); }
}
44. •
Simple Example of Unboxing in java:
The automatic conversion of wrapper class type into corresponding primitive type, is known
as Unboxing. Let's see the example of unboxing:
class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;
System.out.println(a);
}
}
Output:
50
45. Java Annotations
•
•
•
•
•
Java Annotation is a tag that represents the metadata i.e. attached with
class, interface, methods or f i
elds to indicate some additional information
which can be used by java compiler and JVM.
Annotations in Java are used to provide additional information, so it is an
alternative option for XML and Java marker interfaces.
First, we will learn some built-in annotations then we will move on creating
and using custom annotations.
Built-In Java Annotations
There are several built-in annotations in Java. Some annotations are
applied to Java code and some to other annotations.
46. •
•
•
•
•
•
•
•
•
Built-In Java Annotations used in Java code
@Override
@SuppressWarnings
@Deprecated
Built-In Java Annotations used in other annotations
@Target
@Retention
@Inherited
@Documented
47. @Override
•
•
•
@Override annotation assures
that the subclass method is
overriding the parent class
method. If it is not so, compile
time error occurs.
Sometimes, we does the silly
mistake such as spelling
mistakes etc. So, it is better to
mark @Override annotation
that provides assurity that
method is overridden.
Output:Comple Time Error
class Animal{
void eatSomething(){System.out.println(
eating something);}
}
class Dog extends Animal{
@Override
void eatsomething(){System.out.println(
eating fruits);}//should be eatSomething
}
class TestAnnotation1{
public static void main(String args[]){
Animal a=new Dog();
a.eatSomething();
}}
48. @SuppressWarnings
•
•
@SuppressWarnings
annotation: is used to
suppress warnings issued
by the compiler.
If you remove the
@SuppressWarnings(unchecked)
annotation, it will show warning at
compile time because we are using
non-generic collection.
import java.util.*;
class TestAnnotation2{
@SuppressWarnings(unchecked)
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add(sonoo);
list.add(vimal);
list.add(ratan);
for(Object obj:list)
System.out.println(obj);
}}
Output: Now no warning at compile time.
49. @Deprecated
• @ D e p r e c a t e d
annoation marks that
t h i s m e t h o d i s
deprecated so compiler
p r i n t s w a r n i n g . I t
informs user that it may
b e re m o v e d i n the
future versions. So, it is
better not to use such
methods.
class A{
void m(){System.out.println(hello m);}
@Deprecated
void n(){System.out.println(hello n);} }
class TestAnnotation3{
public static void main(String args[]){
A a=new A();
a.n();
}}
At Compile Time:
Note: Test.java uses or overrides a deprecated
API.
Note: Recompile with -Xlint:deprecation for
details.
At Runtime:
hello n
50. Java Custom
Annotations
•
•
•
1.
2.
3.
4.
5.
Java Custom annotations or Java User-
defined annotations are easy to create and
use. The @interface element is used to
declare an annotation. For example:
@interface MyAnnotation{}
Here, MyAnnotation is the custom annotation
name.
Points to remember for java custom annotation
signature
The re are fe w point s t hat should be
remembered by the programmer.
Method should not have any throws clauses
Method should return one of the following:
primitive data types, String, Class, enum or
array of these data types.
Method should not have any parameter.
We should attach @ just before interface
keyword to define annotation.
It may assign a default value to the method.
•
1.
2.
3.
•
•
•
•
Types of Annotation
There are three types of annotations.
Marker Annotation
Single-Value Annotation
Multi-Value Annotation
1) Marker Annotation
An annotation that has no method, is called
marker annotation. For example:
@interface MyAnnotation{}
The @Override and @Deprecated are marker
annotations.
2) Single-Value Annotation
An annotation that has one method, is called
single-value annotation. For example:
@interface MyAnnotation{
int value(); }
3) Multi-Value Annotation
An annotation that has more than one method,
is called Multi-Value annotation. For example:
@interface MyAnnotation{
int value1();
String value2();
String value3(); } }
51. Generics in Java
•
•
•
Java Generic methods and generic
classes enable programmers to specify,
with a single method declaration, a set of
related methods, or with a single class
declaration, a set of related types,
respectively.
Generics also provide compile-time type
safety that allows programmers to catch
invalid types at compile time.
Using Java Generic concept, we might
write a generic method for sorting an
array of objects, then invoke the generic
method with Integer arrays, Double arrays,
String arrays and so on, to sort the array
elements.
•
•
•
Advantage of Java Generics
There are mainly 3 advantages of
generics. They are as follows:
1) Type-safety: We can hold only
a single t ype of object s in
generics. It doesn?t allow to
store other objects.
Without Generics, we can store
any type of objects.
List list = new ArrayList();
list.add(10);
list.add(10);
With Generics, it is required to
specify the type of object we need
to store.
ListInteger list = new ArrayListI
nteger();
list.add(10);
list.add(10);// compile-time error
52. •
2) Type casting is not required: There
is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add(hello);
String s = (String) list.get(0);
//typecasting
After Generics, we don't need to
typecast the object.
ListString list = new ArrayList
String();
list.add(hello);
String s = list.get(0);
3) Compile-Time Checking: It is
checked at compile time so problem
will not occur at runtime. The good
programming strategy says it is far
better to handle the problem at
compile time than runtime.
ListString list = new ArrayListSt
ring();
list.add(hello);
list.add(32);//Compile Time Error
Syntax to use generic collection
ClassOrInterfaceType
Example to use Generics in java
ArrayListString
53. import java.util.*;
class TestGenerics1{
public static void main(String args
[]){
ArrayListString list=new ArrayLi
stString();
list.add(rahul);
list.add(jai);
//list.add(32);//compile time error
String s=list.get(1);//type casting
is not required
System.out.println(element is: +s
);
IteratorString itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
•
•
•
•
•
Generic class
A class that can refer to any type is known as a
generic class. Here, we are using the T type
parameter to create the generic class of specif i
c
type.
Let's see a simple example to create and use the
generic class.
Creating a generic class:
class MyGenT{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
The T type indicates that it can refer to any type (like String, Integer, and
Employee). The type you specify for the class will be used to store and
retrieve the data.
class TestGenerics3{
public static void main(String args[]){
MyGenInteger m=new MyGenInteger();
m.add(2);
//m.add(vivek);//Compile time error
System.out.println(m.get());
}}
54. •
•
1.
2.
3.
4.
5.
Type Parameters
The type parameters naming
conventions are important to
learn generics thoroughly. The
common type parameters are
as follows:
T - Type
E - Element
K - Key
N - Number
V - Value
•
•
Generic Method
Like the generic class, we can create a generic
method that can accept any type of arguments. Here,
the scope of arguments is limited to the method
where it is declared. It allows static as well as non-
static methods.
Let's see a simple example of java generic method to
print array elements. We are using here E to denote
the element.
public class TestGenerics4{
public static E void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
System.out.println(); }
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N',
'T' };
System.out.println( Printing Integer Array );
printArray( intArray );
System.out.println( Printing Character Array );
printArray( charArray );
} }