0% found this document useful (0 votes)
93 views188 pages

ERJEEML101 - JavaProgramming Part 2 PDF

The document discusses key concepts in multithreading in Java such as creating and managing threads, thread priorities, synchronization, and inter-thread communication. It covers threading mechanisms like extending the Thread class and implementing Runnable, and methods for thread control including sleep, yield, join, and wait/notify. Examples are provided for creating and running threads using different approaches.

Uploaded by

Manohar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
93 views188 pages

ERJEEML101 - JavaProgramming Part 2 PDF

The document discusses key concepts in multithreading in Java such as creating and managing threads, thread priorities, synchronization, and inter-thread communication. It covers threading mechanisms like extending the Thread class and implementing Runnable, and methods for thread control including sleep, yield, join, and wait/notify. Examples are provided for creating and running threads using different approaches.

Uploaded by

Manohar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 188

Java Programming Part 2

Education & Research

ER/CORP/CRS/ERJEEML101/003
Session Plan
• Multithreading
• Concurrency
• Input Output Streams & Serialization
• JDBC
• Java Beans
• Generics
• Annotations

2
Java Programming Part 2
Module 1 - Multithreading

ER/CORP/CRS/ERJEEML101/003
Lesson Outcomes
• After completion of the module you will be able to
understand about
– Creating and managing threads
– Priority management
– Thread synchronization
– Thread groups and daemon threads

We enable you to leverage knowledge


4
anytime, anywhere!
What are Threads?
• A thread is a single sequential flow of control within a
program
• Facility to allow multiple activities within a single process
• Referred as lightweight process
• Each thread has its own program counter, stack and
local variables
• Threads share memory, heap area, files

We enable you to leverage knowledge


5
anytime, anywhere!
Why use Threads?
• To perform asynchronous or background processing
• Increases the responsiveness of GUI applications
• Better utilization of system resources
• Simplify program logic when there are multiple
independent entities

We enable you to leverage knowledge


6
anytime, anywhere!
Creating the Thread

Two ways:
• Extending the Thread class
• Implementing the Runnable interface

We enable you to leverage knowledge


7
anytime, anywhere!
The Thread class (1 of 2)
• Extend the Thread class
• Override the run() method
• Create an object of the sub class and call the
start method to execute the Thread

We enable you to leverage knowledge


8
anytime, anywhere!
The Thread class (2 of 2)
class ExtThread extends Thread
{
ExtThread()
{
System.out.println("Child Thread created");
}
public void run()
{
System.out.println("Child Thread running");
}
}
class ExtThreadMain
{
public static void main(String a[])
{
System.out.println("Hi I'm main thread");
ExtThread obj=new ExtThread ();
obj.start();
System.out.println("This is the main thread printing");

}}

We enable you to leverage knowledge


9
anytime, anywhere!
The Runnable Interface (1 of 2)

• Useful when the class is already extending another class


and needs to implement mutithreading
• Need to implement the run() method
• Create a thread object (the worker) and give it a
Runnable object (the job)
– public Thread(Runnable target);
• Start the thread by calling the start() method

We enable you to leverage knowledge


10
anytime, anywhere!
The Runnable Interface (2 of 2)
class RunnableThread implements Runnable
{
RunnableThread()
{
System.out.println("Child Thread: ");
}
public void run()
{
System.out.println("Hi I'm a new thread");
}
}

class RunnableThreadMain
{
public static void main(String a[])
{
System.out.println("Hi I'm main thread");
RunnableThread rt=new RunnableThread();
Thread t=new Thread(rt);
t.start();
System.out.println("Hi I'm main thread");
}}

We enable you to leverage knowledge


11
anytime, anywhere!
Thread States

NEWBORN DEAD
start() run() returns or
thread interrupted

notify(), notifyAll()
WAITING RUNNABLE
Sleep interval
expires
yield() or end schedule
of time slice
SLEEPING sleep() wait()

I/O completion RUNNING


BLOCKED
I/O request

NON-RUNNABLE
ALIVE

We enable you to leverage knowledge


12
anytime, anywhere!
Thread scheduling
• There are 2 techniques for thread scheduling
– Pre-emptive and time-sliced
• In preemptive scheduling, the thread with a higher priority
preempts threads with lower priority and grabs the CPU
• In time-sliced or round robin scheduling, each thread will
get some time of the CPU
• Java runtime system’s thread scheduling algorithm is
preemptive but it depends on the implementation
• Solaris is preemptive, Macintosh and Windows are time
sliced
• In theory, a thread with high priority should get more CPU
time, but practically it may depend on the platform

We enable you to leverage knowledge


13
anytime, anywhere!
Thread Priorities
• Thread priority can be used by the scheduler to decide
which thread is to be run
• The priority of a Thread can be set using the method
setPriority()
– t.setPriority(7);
• The method getPriority() will return the priority of a
Thread
– t.getPriority()
• The priority can vary from 1 to 10 or
Thread.MIN_PRIORITY to Thread.MAX_PRIORITY
• Normally a Thread will have the priority 5 or
Thread.NORM_PRIORITY
We enable you to leverage knowledge
14
anytime, anywhere!
Ensuring time-slicing (1 of 2)
• The programmer should write code to ensure that time-
slicing occurs even when the application is running in a
preemptive environment
• The static method sleep of the Thread class will make a
thread sleep for specified number of milliseconds
Thread.sleep(1000);
• A sleeping thread can be interrupted by another thread
using the method interrupt()
• When interrupted, sleep method will throw an
InterruptedException

We enable you to leverage knowledge


15
anytime, anywhere!
Ensuring time-slicing (2 of 2)
• The yield method of the class Thread will give a chance
to other threads to run
– t.yield();
• The yield() method ensures that the thread behaves like
a polite thread and not a selfish thread

We enable you to leverage knowledge


16
anytime, anywhere!
isAlive() and join() methods
• The state of a thread can be queried using the isAlive()
method
– Returns true if the thread has been started but not
completed its task
– A thread can wait for another thread to finish by using
the join() method

We enable you to leverage knowledge


17
anytime, anywhere!
Thread synchronization (1 of 2)
• In a multithreaded environment 2 or more threads may
access a shared resource
• There should be some means to ensure that the shared
resource is accessed by only one thread at a time. This
is termed as synchronization
• Every such shared object has a mutually exclusive lock
called monitor
• Only one thread can get the monitor of an object at a
time

We enable you to leverage knowledge


18
anytime, anywhere!
Thread synchronization (2 of 2)
• Synchronization can be ensured by using the keyword
synchronized
• A method or block of code can be made synchronized
• Example
public class Account{
int bankBalance;
public synchronized void creditAccount (int amount) {
bankBalance+= amount;
}
}

We enable you to leverage knowledge


19
anytime, anywhere!
Inter-thread communication (1 of 3)
• Thread must wait for the state of an object to change
while executing a synchronized method, it may call wait()
– void wait()
– void wait (long timeout)
• The thread calling wait will release the lock on that
particular object
• The thread will wait till it is notified by another thread
owning the lock on the same object
– void notify()
– void notifyAll()

We enable you to leverage knowledge


20
anytime, anywhere!
Inter-thread communication (2 of 3)
• If there are multiple threads waiting on the same object,
the notify() method will notify one among them
• The thread that would be notified cannot be predicted
• It is safer to call notifyAll(), since it will notify all waiting
threads
• Code for synchronization should be written carefully else
may lead to a dead-lock situation

We enable you to leverage knowledge


21
anytime, anywhere!
Inter-thread communication (3 of 3)
• Example
public class Account {

int bankBalance;
public synchronized void debitAccount (int amount) {
while((bankBalance - amount)<0) wait();
bankBalance -= amount;

}
public synchronized void creditAccount (int amount) {
bankBalance += amount;
notify();

}
}

We enable you to leverage knowledge


22
anytime, anywhere!
Inter-thread communication[Example]
class Thread2 extends Thread{
class Account { Account ac;
int bankBalance; Thread2(Account ac){
public synchronized void debitAccount (int this.ac=ac; }
amount) {
public void run(){
try{
int i=100;
System.out.println("Checking for bal");
while(i<=300){
while((bankBalance - amount)<0){
ac.creditAccount(100);
System.out.println("going to
wait"); wait(); } i+=100;
System.out.println("debiting.."); } } }
bankBalance -= amount; public class ITCCheck{
}catch(Exception e){} } public static void main(String[] args){
public synchronized void creditAccount (int Account ac=new Account();
amount) { Thread1 t1=new Thread1(ac);
bankBalance += amount; t1.start();
System.out.println("bal="+bankBalance+" Thread2 t2=new Thread2(ac);
notify"); t2.start();
notify(); } } } }
class Thread1 extends Thread{
Account ac;
Thread1(Account ac){
this.ac=ac; }
public void run(){
ac.debitAccount(300); } }

We enable you to leverage knowledge


23
anytime, anywhere!
Thread Groups
• Represents a set of threads
• Can also contain other thread groups, creating a hierarchy
of thread groups
• Provides a single-point control on the threads belonging to
the thread group
• Creation time association is for the life time of the thread
– ThreadGroup threadGroup = new
ThreadGroup("MyGroup");
• Some of the important methods of ThreadGroup are
– activeCount(), destroy(), setMaxPriority(), setDaemon()

We enable you to leverage knowledge


24
anytime, anywhere!
Daemon Thread
• Daemon Thread is a thread that will run in the
background, serving other threads
• So, a program can stop, if all non-daemon threads have
finished execution
• A thread can be made a daemon by calling the method
setDaemon(true) before calling its start() method
• Can query thread status using the method isDaemon()

We enable you to leverage knowledge


25
anytime, anywhere!
Java Programming Part 2
Module 2- Concurrency

ER/CORP/CRS/ERJEEML101/003
Concurrency
• Packages added in Java 5 for the support of concurrent programming are
– java.util.concurrent
• Contains classes and interfaces useful in concurrent programming
– java.util.concurrent.locks
• Contains interfaces and classes providing a framework for locking
and waiting for conditions that is distinct from built-in synchronization
and monitors.
– java.util.concurrent.atomic
• Contains classes that support lock-free thread-safe programming on
single variables.
• There are also new concurrent data structures added in the Java Collections Framework.
• Need for high level APIs
– Reduced Programmer effort
– Increased performance
– Improved maintainability
– Increased reliability
We enable you to leverage knowledge
27
anytime, anywhere!
Task Scheduling Framework
• As discussed in Module 1 there are two ways to create threads.
– Extending the Thread class
• Extend the Thread class
• Override the run() method
• Create an object of the sub class and call the start method to execute
the Thread
– Implementing the Runnable interface
• Useful when the class is already extending another class and needs to
implement mutithreading
• Implement the run() method
• Create a thread object (the worker) and give it a Runnable object (the
job)
• Start the thread by calling the start() method
• This works fine for smaller applications but in larger applications the thread
management and creation has to be separated from the rest of the application.
• This can be done by Executor which facilitates the standardized invocation,
scheduling and execution of threads..
We enable you to leverage knowledge
28
anytime, anywhere!
Task Scheduling Framework(Contd..)
• Executor Interface
– This interface provides a way of decoupling task submission from the
mechanics of how each task will be run, including details of thread use,
scheduling, etc.
– An Executor is normally used instead of explicitly creating threads.
– Example:
Executor executor = anExecutor;
executor.execute(new RunnableTask1());
– Many Executor implementations impose some sort of limitation on how and
when tasks are scheduled.
• ExecutorService Interface
– Extends Executor interface
– Has features that help manage the lifecycle of both the individual tasks and
the executor itself.
• Executors
– It is a factory for creating various kinds of ExecutorService
implementations.
We enable you to leverage knowledge
29
anytime, anywhere!
Task Scheduling Framework(Contd..)
import java.util.concurrent.*;
class RunnableThread implements Runnable
{
RunnableThread()
{
System.out.println("Child Thread: ");
}
public void run()
{
System.out.println("Hi I'm a new thread");
}
}
public class Main {
public static void main(String[] args) {
ExecutorService e1=Executors.newSingleThreadExecutor();
e1.execute(new RunnableThread()); } }

We enable you to leverage knowledge


30
anytime, anywhere!
Callables and Futures
• In the previous versions of Java there was no provision for the
callable thread to return values to the calling thread.
• With the addition of Callable<V> interface it is made possible.
• The callable thread class has to implement Callable interface.
• The Callable interface is similar to Runnable, in that both are
designed for classes whose instances are potentially executed
by another thread. A Runnable thread, however, does not
return a result.
• Callable thread has to implement call() method in the same
way as we implement the run() method when Runnable
interface is used.
• Call() methods return the required data to the calling thread.

We enable you to leverage knowledge


31
anytime, anywhere!
Callables and Futures

• Calling thread uses the submit method on the


ExecutorService instance instead of using execute()
method.
• Submit() method submits Callable object for execution and
returns a Future object. Calling thread can then call the get()
method on the Future object to retrieve the result sent by the
callable thread.
– If the result is ready, it will be returned
– If not the calling thread will be blocked.

We enable you to leverage knowledge


32
anytime, anywhere!
Callables and Futures
class PriceCalculation implements public Double call(){
Callable<Double> { switch(itemCode){
double price=0; case 101:
int itemCode; disPer=10; break;
PriceCalculation(int itemCode){ case 102:
this.itemCode=itemCode; disPer=20; break;
} }
public Double call(){ return new Double(disPer);
switch(itemCode){ }}
public class Main {
case 101:
public static void main(String[] args) {
price=1000.0; break;
ExecutorService
case 102: pool=Executors.newFixedThreadPool(2);
price=2000.0; break; Future<Double> price=pool.submit(new
} PriceCalculation(101));
return new Double(price); Future<Double> discount=pool.submit(new
DiscountCalculation(101));
}} try {
class DiscountCalculation implements System.out.println("Net amount to be paid is:
Callable<Double>{ "+(price.get()-(price.get()*discount.get()/100)));
double disPer=0; } catch (Exception e){}
int itemCode; } }
DiscountCalculation(int itemCode){
this.itemCode=itemCode; }

We enable you to leverage knowledge


33
anytime, anywhere!
Synchronizers
• Java 5 introduced general purpose classes such as
– Semaphore
– Mutex
– Etc.
Which facilitate coordination between the threads.
• These classes are added as a part of java.util.concurrent
package.

We enable you to leverage knowledge


34
anytime, anywhere!
Semaphores
• In Java a Semaphore is a lock with a counter.
• It is typically used to restrict access to fixed size pool of
resources.
• The Semaphore object will be created with the count which
is the same as the number of resources in the pool.
• Thread which tries to access the resource will call acquire()
method on the Semaphore object.
• This will return when the count>0.
• If the count is zero then the thread will be blocked till the
release() method is called on the semaphore object by
another thread.
• acquire() and release() are thread safe atomic operations.

We enable you to leverage knowledge


35
anytime, anywhere!
Semaphores (Contd...)
• Semaphores are usually implemented as follows.

private Semaphore available;


private Resource[] resources;
public Resource (int poolSize){
available=new Semaphore(poolSize);
/*initialize the Resources*/
}
public Resource getResource(){
try{available.aquire();}catch(Exception e){}
/*Provide Resource from the pool*/
}
public void returnResource(Resource r){
/*Return Resource to the pool*/
available.release();}

We enable you to leverage knowledge


36
anytime, anywhere!
Semaphores (Contd...)
class Account{ class ThreadB implements Runnable{
double amt; Semaphore sa;
Account(double amt){ Account acc;
this.amt=amt; } ThreadB(Semaphore sa,Account acc){
public void withdraw(double amt){ this.sa=sa; this.acc=acc; }
this.amt-=amt; } public void run(){
public void deposit(double amt){ try {
this.amt+=amt; } sa.acquire(); acc.deposit(100.0);
public double display(){ Thread.sleep(1000);
return amt; } } catch (InterruptedException ex) {}
} System.out.println("Amount after Deposit:
class ThreadA implements Runnable{ "+acc.display());
Semaphore sa; Account acc; sa.release();
ThreadA(Semaphore sa,Account acc){ }}
this.sa=sa; this.acc=acc;
} public class Main {
public void run(){ public static void main(String[] args) {
try { // Semaphore working with Single Object pool;
sa.acquire(); acc.withdraw(200.0); Account acc=new Account(10000);
Thread.sleep(1000); Semaphore s1=new Semaphore(1);
} catch (InterruptedException ex) {} ExecutorService
System.out.println("Amount after withdrawal: e1=Executors.newFixedThreadPool(2);
"+acc.display()); e1.execute(new ThreadA(s1,acc));
sa.release(); } } e1.execute(new ThreadB(s1,acc)); } }

We enable you to leverage knowledge


37
anytime, anywhere!
Concurrent Collections
• There are also new concurrent data structures added in
the Java Collections Framework.
• The purpose of these classes is to provide high-
performance, highly-scalable, thread-safe versions of the
basic collection types.
• They are added as a part of java.util.concurrent package.
• Some of them are,
– BlockingQueue
– ConcurrentMap
– ConcurrentNavigableMap
– ConcurrentLinkedQueue
– Etc.
We enable you to leverage knowledge
38
anytime, anywhere!
Atomic Variables
• Atomic variables have features that minimize
synchronization and avoids memory consistency errors.
• Atomic variables are fine-grained and light-weight than
locks, and are critical for implementing high-performance
concurrent code on multiprocessor systems.
• Atomic variables limit the scope of contention to a single
variable.
• With algorithms based on atomic variables instead of
locks, threads are more likely to be able to proceed
without delay.
• Atomic classes AtomicInteger, AtomicLong, etc. in
java.util.concurrency.atomic package help us to work
with atomic variables.
• All classes have get and set methods that work like read
and write to volatile variables.

We enable you to leverage knowledge


39
anytime, anywhere!
Locks
• Package java.util.concurrent.locks contains interfaces
and classes providing a framework for locking and
waiting for conditions that is distinct from built-in
synchronization and monitors.
• Lock Interface
– Provides extensive locking operations than synchronized block.
– Simple to handle locking and unlocking.
Lock l = ...; l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();}
– Has tryLock() method which helps the threads to
acquire Locks with out blocking

We enable you to leverage knowledge


40
anytime, anywhere!
Locks (contd..)
• Reentrant Lock
– This is the complete implementation of Lock interface.
– Holding thread can call lock() multiple times and won’t block.
– Lock() acquires the lock if it is not held by another thread and
returns immediately, setting the lock hold count to one.
– If the current thread already holds the lock then the hold count is
incremented by one and the method returns immediately.
– If the lock is held by another thread then the current thread
becomes disabled for thread scheduling purposes and lies
dormant until the lock has been acquired, at which time the lock
hold count is set to one.
• ReadWrite Lock
– Has two locks that control the read and write access.
– readLock() method returns a lock for reading
– writeLock() method returns the lock for writing.

We enable you to leverage knowledge


41
anytime, anywhere!
Locks (contd..)
class Account{ class ThreadB implements Runnable{
double amt; Account acc;
Lock lock=new ReentrantLock(); ThreadB(Account acc){
Account(double amt){ this.acc=acc;
this.amt=amt; } }
public void withdraw(double amt){ public void run(){
this.amt-=amt; } try {
public void deposit(double amt){ acc.lock.lock();
this.amt+=amt; } acc.deposit(100.0); Thread.sleep(1000);
public double dispay(){ System.out.println("After deposit:
return amt; } } "+acc.dispay());
class ThreadA implements Runnable{ } catch (Exception ex) { }
Account acc; finally{
ThreadA(Account acc){ acc.lock.unlock();
this.acc=acc; } } }
public void run(){ }
try { public class Main {
acc.lock.lock(); acc.withdraw(200.0); public static void main(String[] args) {
Thread.sleep(1000); Account acc=new Account(10000);
System.out.println("After withdrawal: ExecutorService
"+acc.dispay()); e1=Executors.newFixedThreadPool(2);
} catch (Exception ex) { } e1.execute(new ThreadA(acc));
finally{ acc.lock.unlock(); e1.execute(new ThreadB(acc));
} }} } }

We enable you to leverage knowledge


42
anytime, anywhere!
Java Programming Part 2
Module 3 - Input Output Streams & Serialization

ER/CORP/CRS/ERJEEML101/003
Lesson Outcomes
• After completion of the module you will be able to
understand about
– What are Streams?
– What are the types of streams available?
– What are the classes available to work with streams?
– How the buffered streams are advantageous over the
non-buffered streams?
– What is Serialization?

We enable you to leverage knowledge


44
anytime, anywhere!
Streams
• Streams are channels of communication between
programs and source/destination of data
– A stream is either a source of bytes or a destination for
bytes.
• Provide a good abstraction between the source and
destination
• Abstract away the details of the communication path from
I/O operation
• Streams hide the details of what happens to the data
inside the actual I/O devices.
• Streams can read/write data from/to blocks of memory,
files and network connections

We enable you to leverage knowledge


45
anytime, anywhere!
Streams(Contd…)

Reads
Source Stream Program

Writes

Program Stream Destination

We enable you to leverage knowledge


46
anytime, anywhere!
Input and Output
• The Java Input/Output system is designed to make it
device independent
• Irrespective of the device, the way in which input and
output operations are performed is the same
• The classes for performing input and output operations
are available in the package java.io

We enable you to leverage knowledge


anytime, anywhere!
Bytes and Characters
• The basic input/output classes of Java can handle only two
types of data
– Bytes
– Characters
• The four abstract classes at the top of the hierarchy of I/O
classes that are used for input and output of these two data
types are
– InputStream (for reading bytes)
– OutputStream (for writing bytes)
– Reader (for reading characters)
– Writer (for writing characters)
• For performing any kind of I/O operation, we depend on the
sub classes of these classes

We enable you to leverage knowledge


anytime, anywhere!
InputStream
• The method int read() reads the next byte from the input
stream and returns an integer
• The read method returns -1 if no more data is available
for reading
– For example, end of file
• If the returned int is not -1, typecasting it to a byte gives
the actual data that is read
• The method void close() closes the stream

We enable you to leverage knowledge


anytime, anywhere!
Input Stream hierarchy

InputStream
ByteArrayInputStream

FilterInputStream FileInputStream

BufferedInputstream ObjectInputStream

DataInputStream

PushbackInputStream

We enable you to leverage knowledge


50
anytime, anywhere!
Methods in InputStream
• int available()
• void close()
• void mark(int numberofBytes)
• boolean markSupported()
• int read()
• int read(byte buffer[])
• int read(byte buffer[], int offset, int numberofBytes)
• void reset()
• long skip(long numberofBytes)

We enable you to leverage knowledge


51
anytime, anywhere!
FileOutputStream

• The following code snippet stores some bytes of data into a


file
• FileOutputStream, a sub class of OutputStream is used for
this

FileOutputStream fos = new FileOutputStream(“Data”);


byte data1 = 65, data2 = 66, data3 = 67;
fos.write(data1);
fos.write(data2);
fos.write(data3);
fos.close();

We enable you to leverage knowledge


anytime, anywhere!
FileInputStream

• The following code snippet reads bytes from a file


• FileInputStream, a sub class of InputStream is used for this

FileInputStream fis = new FileInputStream(“Data”);


int value = fis.read();
while(value != -1){
System.out.println((byte)value);
value = fis.read();
}
fis.close();

We enable you to leverage knowledge


anytime, anywhere!
OutputStream
• The method void write(int) accepts an integer and writes
its byte part into the device
• The method void close() closes the stream

We enable you to leverage knowledge


anytime, anywhere!
Output Stream hierarchy

OutputStream ByteArrayOutputStream

FilterOutputStream FileOutputStream

BufferedOutputstream ObjectOutputStream

DataOutputStream

PrintStream

We enable you to leverage knowledge


55
anytime, anywhere!
Methods in OutputStream
• void close()
• void flush()
• void write(int b)
• void write(byte buffer[])
• void write(byte buffer[], int offset, int numberofBytes)

We enable you to leverage knowledge


56
anytime, anywhere!
Reader
• The method int read() reads the next char from the
reader and returns an integer
• The read method returns -1 if no more data is available
for reading
– For example, end of file
• If the returned int is not -1, typecasting it to a char gives
the actual data that is read
• The method void close() closes the reader

We enable you to leverage knowledge


anytime, anywhere!
Writer
• The method void write(int) accepts an integer and writes
its char part into the device
• The method void write(String) writes a String to the
device
• The method void close() closes the writer

We enable you to leverage knowledge


anytime, anywhere!
FileWriter

• The following code snippet stores some characters into a


file
• FileWriter, a sub class of Writer is used for this

FileWriter fw = new FileWriter("Data");


char c1 = 'A', c2 = 'B', c3 = 'C';
fw.write(c1);
fw.write(c2);
fw.write(c3);
fw.close();

We enable you to leverage knowledge


anytime, anywhere!
FileReader
• The following code snippet reads characters from a file
• FileReader, a sub class of Reader is used for this

FileReader fr = new FileReader("Data");


int i = fr.read();
while(i != -1){
System.out.println((char)i);
i = fr.read();
}
fr.close();

We enable you to leverage knowledge


anytime, anywhere!
Filter Classes
• The Java I/O System uses filter classes to build
specialized I/O streams that provide particular
capabilities as needed.
• The special capability could be buffering, data
conversion etc

We enable you to leverage knowledge


anytime, anywhere!
BufferedOutputStream (1/4)

• Whenever the write method of the FileOutputStream is


invoked, the byte is written into the harddisk
• Multiple access of the hard disk drive will make the program
slower
• BufferedOutputStream is a sub class of OutputStream
which can wrap around any OutputStream to provide
buffering
• The following constructor is used for this wrapping
BufferedOutputStream(OutputStream)

We enable you to leverage knowledge


anytime, anywhere!
BufferedOutputStream (2/4)

• A FileOutputStream can be wrapped in a


BufferedOutputStream as follows

FileOutputStream fos = new FileOutputStream(“Data”);


BufferedOutputStream bos = new BufferedOutputStream(fos);

We enable you to leverage knowledge


anytime, anywhere!
BufferedOutputStream(3/4)
• The method void write(int) accepts an integer and writes
its byte part into the device
• The method void close() closes the stream
• The write method of the BufferedOutputStream can be
used for writing bytesThe byte will not be really written
into the file, instead stored in the buffer
• The close method of the BufferedOutputStream will
transfer all the data in the buffer to the hard disk and
closes the underlying FileOutputStream

We enable you to leverage knowledge


64
anytime, anywhere!
BufferedOutputStream (4/4)

FileOutputStream fos = new FileOutputStream(“Data”);


BufferedOutputStream bos = new BufferedOutputStream(fos);
byte data1 = 65, data2 = 66, data3 = 67;
bos.write(data1);
bos.write(data2);
bos.write(data3);
bos.close();

We enable you to leverage knowledge


anytime, anywhere!
BufferedInputStream (1/2)

• To avoid multiple access to the device for reading data,


BufferedInputStream can be used as a wrapper around any
InputStream
• The read method of BufferedInputStream will read a buffer
full of bytes from the underlying device
• Subsequent calls to the read method will fetch the data
from the buffer and not from the device

We enable you to leverage knowledge


anytime, anywhere!
BufferedInputStream (2/2)

FileInputStream fis = new FileInputStream("Data");


BufferedInputStream bis = new BufferedInputStream(fis);
int i = bis.read();
while(i != -1){
System.out.println((byte)i);
i = bis.read();
}
bis.close();

We enable you to leverage knowledge


anytime, anywhere!
BufferedReader and BufferedWriter

• Corresponding to BufferedInputStream and


BufferedOutputStream classes for bytes there are
BufferedReader and BufferedWriter classes for characters
• BufferedReader can wrap around a Reader making the
reading faster
• Buffered Writer can wrap around a Writer making the
writing faster

We enable you to leverage knowledge


anytime, anywhere!
DataInputStream and DataOutputStream (1/4)
• InputStream and OutputStream deal with bytes only
• DataInputStream and DataOutputStream are filter
classes that wrap around InputStream and OutputStream
objects so that primitive types can be read and written

We enable you to leverage knowledge


anytime, anywhere!
DataInputStream and DataOutputStream (2/4)

DataOutputStream has the following methods


writeInt(int)

writeDouble(double)

writeBoolean(boolean)

writeXXX(XXX)

DataInputStream has the following methods


int readInt()

double readDouble()

boolean readBoolean()

XXX readXXX()

We enable you to leverage knowledge


anytime, anywhere!
DataInputStream and DataOutputStream (3/4)

FileOutputStream fos = new FileOutputStream("Data");

DataOutputStream dos = new DataOutputStream(fos);

dos.writeInt(300);

dos.writeDouble(345.67);

dos.writeBoolean(true);

dos.close();

We enable you to leverage knowledge


anytime, anywhere!
DataInputStream and DataOutputStream (4/4)

FileInputStream fis = new FileInputStream("Data");

DataInputStream dis = new DataInputStream(fis);

System.out.println(dis.readInt());

System.out.println(dis.readDouble());

System.out.println(dis.readBoolean());

dis.close();

We enable you to leverage knowledge


anytime, anywhere!
PushbackInputStream
• Pushback is used on an input stream for reading a byte
and then pushing it back to the stream as if it is unread
• The filter class PushbackInputStream provides the
following methods for pushing back

– void unread(int bytevalue)


– void unread(byte buffer[])
– void unread(byte buffer[], int offset, int numBytes)

We enable you to leverage knowledge


73
anytime, anywhere!
PrintStream
• This filter class provides functionality to print all data
types.
• It provides two methods, print() and println(), that are
overloaded to print any primitive data type or object.
• Objects are printed by first converting them to strings
using their toString() method inherited from the Object
class.
• PrintStream class has the following constructor
– PrintStream(OutputStream outputStream)
• System.out is a PrintStream object

We enable you to leverage knowledge


74
anytime, anywhere!
“Bridge” Classes (1/2)
• Two classes act as bridge between byte streams and
characters
– InputStreamReader
– OutputStreamWriter
• InputStreamReader wraps around an InputStream object
and helps to read characters from an InputStream
• OutputStreamWriter wraps around an OutputStream
object and helps to write characters into an
OutputStream

We enable you to leverage knowledge


anytime, anywhere!
“Bridge” Classes (2/2)

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

System.out.print("Enter the first number ");

String data1 = br.readLine();

System.out.print("Enter the second number ");

String data2 = br.readLine();

int sum = Integer.parseInt(data1) +


Integer.parseInt(data2);

System.out.println("The sum is " + sum);

We enable you to leverage knowledge


anytime, anywhere!
Device Independent I/O
• The following method accepts any OutputStream object and
writes 3 bytes
• This method remains the same irrespective of the device
public void writeBytes(OutputStream os){
try{
os.write(65);
os.write(66);
os.write(67);
}
catch(IOException exception){
System.out.println(exception);
}
}

We enable you to leverage knowledge


anytime, anywhere!
Serialization
• Serialization is the process of converting an object into a
stream of bytes
• An object that can be serialized can be written into a file
and later retrieved
• The ability of an object to exist beyond the execution of
the program which created it is called Persistence
• Only those objects that implements java.io.Serializable
interface can be serialized
• The Serializable interface is just a marker interface and
does not have any methods

We enable you to leverage knowledge


anytime, anywhere!
ObjectOutputStream (1/3)

• The filter class ObjectOutputStream wraps around any


OutputStream and helps to write a Serializable object into
the OutputStream

• The method writeObject(Object object) will write the


object to the underlying OutputStream

ObjectOutputStream(OutputStream)

We enable you to leverage knowledge


anytime, anywhere!
ObjectOutputStream (2/3)

class Student implements Serializable{


private String name;
private int classNo;
public Student(String name, int classNo){
this.name = name;
this.classNo = classNo;
}
public void write(){
System.out.println(name);
System.out.println(classNo);
}
}

We enable you to leverage knowledge


anytime, anywhere!
ObjectOutputStream (3/3)

FileOutputStream fos = new FileOutputStream("Data");


ObjectOutputStream oos = new ObjectOutputStream(fos);
Student student = new Student("Sally", 54);
oos.writeObject(student);
oos.close();

We enable you to leverage knowledge


anytime, anywhere!
ObjectInputStream (1/2)

• The filter class ObjectInputStream wraps around any


InputStream and helps to read bytes from an InputStream
and reconstruct the bytes into an Object
• The method readObject() will read bytes of data from the
underlying InputStream, constructs an Object and returns it

We enable you to leverage knowledge


anytime, anywhere!
ObjectInputStream (2/2)

FileInputStream fis = new FileInputStream("Data");


ObjectInputStream ois = new ObjectInputStream(fis);
Student s = (Student)ois.readObject();
ois.close();
s.write();

We enable you to leverage knowledge


anytime, anywhere!
Externalizable Interface (1/3)

• Classes that want to control the serialization of its


instances should implement the interface
java.io.Externalizable
• The two methods of this interface are
readExternal(ObjectInput) and
writeExternal(ObjectOutput)
• The writeObject method of the ObjectOutputStream will in
turn call the writeExternal method of the Externalizable
object passed to it
• The programmer can control the way in which the object
is written by implementing the writeExternal method

We enable you to leverage knowledge


anytime, anywhere!
Externalizable Interface (2/3)

• Similarly, the readObject method of ObjectInputStream


calls the readExternal method of the Externalizable object
passed to it
• The programmer can control the way in which the object
is recreated by implementing the readExternal method

We enable you to leverage knowledge


anytime, anywhere!
Externalizable Interface (3/3)

• The following class overrides the writeExternal method so


that the Student object is written to a stream as
characters and readExternal method so that the Student
object is constructed properly

We enable you to leverage knowledge


anytime, anywhere!
Demo
class Student implements Externalizable{
//Data Members and Other Methods
public void readExternal(ObjectInput in) throws
IOException{
name = in.readUTF();
classNo = Integer.parseInt(in.readUTF());
}
public void writeExternal(ObjectOutput out) throws
IOException{
out.writeUTF(name);
out.writeUTF(Integer.toString(classNo));
}
}

We enable you to leverage knowledge


87
anytime, anywhere!
Security: an issue in
serialization

• Serialized objects can be sent over network


• Can be accidentally or deliberately modified
• Sensitive data written into a file can be read
Solution
• Encrypt the object during serialization
• Ensure that sensitive objects do not implement
Serialializable or Externalizable

We enable you to leverage knowledge


anytime, anywhere!
Java Programming Part 2

Module 4 - JDBC

ER/CORP/CRS/ERJEEML101/003
Lesson Outcomes
• After completion of the module you will be able to
understand
– What is JDBC?
– What are the advantages of using JDBC?
– How to work with a database using JDBC? and
– Transaction control in JDBC.

We enable you to leverage knowledge


90
anytime, anywhere!
JDBC
• The JDBC (Java Database Connectivity) API helps a
Java program to access a database in a standard
way
• JDBC is a specification that tells the database vendors
how to write a driver program to interface Java programs
with their database

We enable you to leverage knowledge


91
anytime, anywhere!
JDBC [Contd..]
• A Driver written according to this standard is called the
JDBC Driver
• All related classes and interfaces are present in the
java.sql package
• All JDBC Drivers implement the interfaces of java.sql

We enable you to leverage knowledge


92
anytime, anywhere!
JDBC Drivers
• There are 4 types of drivers --Type1, Type2,
Type3,Type4

We enable you to leverage knowledge


93
anytime, anywhere!
Type1 Driver (JDBC-ODBC bridge driver)

Calling Java Application

JDBC API

JDBC Driver Manager

JDBC - ODBC Bridge


(Type I Driver)

ODBC Driver

Database Library APIs

DataBase

We enable you to leverage knowledge


94
anytime, anywhere!
Type2 Driver (Native-API driver )

Calling Java Application

JDBC API

JDBC Driver Manager

Native - API driver


(Type II Driver)

Database Library APIs

DataBase

We enable you to leverage knowledge


95
anytime, anywhere!
Type3 Driver (Network-protocol driver )
Calling Java Application

JDBC API

JDBC Driver Manager

Network-Protocol driver
(Type III Driver)

MiddleWare
(Application Server)

Different DataBase Vendors

We enable you to leverage knowledge


96
anytime, anywhere!
Type4 Driver (Native-protocol driver )

Calling Java Application

JDBC API

JDBC Driver Manager

Native - Protocol driver


(Type 4 Driver)

direct calls using specific


database protocol

DataBase

We enable you to leverage knowledge


97
anytime, anywhere!
Database interaction
• The steps involved in a database interaction are:
– Loading the specific driver
– Making a connection to the database
– Sending SQL statements to the database
– Processing the results

We enable you to leverage knowledge


98
anytime, anywhere!
JDBC - classes and interfaces

• DriverManager class :
– Manages all the JDBC Drivers that are loaded in
the memory
– Helps in dynamic loading of Drivers
• Data Source :
– Offer the user considerably more capability than
the basic Connection objects that the
DriverManager provides.
– It supports connection pooling and distributed
transactions

We enable you to leverage knowledge


99
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• Three types of standard DataSource objects :
– The basic DataSource that produces standard
Connection objects just like those that the
DriverManager produces
– A PooledDataSource that supports connection
pooling. Pooled connections are returned to a pool for
reuse by another transaction.
– A DistributedDataSource that supports distributed
transactions accessing two or more DBMS servers.

We enable you to leverage knowledge


100
anytime, anywhere!
JDBC - classes and interfaces [Contd..]

• Methods in DriverManager class -


– getConnection() : to establish a connection to a
database.
• Connection getConnection(String url, Properties
info)
• Connection getConnection(String url)
• Connection getConnection(String url, String
userID, String password)
– registerDriver(java.sql.Driver)

We enable you to leverage knowledge


101
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• Connection interface - defines methods for interacting
with the database via the established connection.
– A connection object represents a connection with a
database.
– A connection session includes the SQL statements
that are executed and the results that are returned
over that connection.
– A single application can have one or more
connections with a single database, or it can have
many connections with many different databases.

We enable you to leverage knowledge


102
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• The different methods of Connection interface are:
– close() - closes the database connection
– createStatement() - creates an SQL Statement
object
– prepareStatement() - creates an SQL
PreparedStatement object. (PreparedStatement
objects are precompiled SQL statements)
– prepareCall() - creates an SQL CallableStatement
object using an SQL string. (CallableStatement
objects are SQL stored procedure call statements)

We enable you to leverage knowledge


103
anytime, anywhere!
Statement

• A statement object is used to send SQL statements to


a database.
• Three kinds :
Statement
– Execute simple SQL without parameters
PreparedStatement
– Used for pre-compiled SQL statements with or
without parameters
CallableStatement
– Execute a call to a database stored procedure or
function

We enable you to leverage knowledge


104
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• Statement interface - defines methods that are used to interact with
database via the execution of SQL statements.

• The different methods are:


– executeQuery(String sql) - executes an SQL statement
(SELECT) that queries a database and returns a ResultSet
object.

– executeUpdate(String sql) - executes an SQL statement


(INSERT,UPDATE,or DELETE) that updates the database and
returns an int, the row count associated with the SQL statement

– execute(String sql) - executes an SQL statement that is written


as String object

– getResultSet() - used to retrieve the ResultSet object

We enable you to leverage knowledge


105
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
Example:
Connection connection = DriverManager.getConnection(“jdbc:odbc:emp”, “”, “”);
/* create statement */
Statement statement = connection.createStatement();
/* get all records from the Employee table */
ResultSet resultSet = statement.executeQuery("select * from Employee");
/* update the age in empcode 1 and check no of records affected by change */
String sql = “update Employee set empage = 25 where empcode = 1”;
int recordsAffected = stmt.executeUpdate(sql);
if(recordsAffected == 0)
System.out.println(“Update failed”);
/* delete employee record with empcode = 2 */
String sql = “delete from employee where empcode = 2”;
int recordsAffected = statement.executeUpdate(sql);
/* we have to commit the transaction once we delete the record, otherwise the record is
just marked for deletion but not physically deleted. we achieve this by using the
commit() method of the Connection interface */
connection.commit();

We enable you to leverage knowledge


106
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• ResultSet Interface - maintains a pointer to a row
within the tabular results. The next() method is used to
successively step through the rows of the tabular
results.
• The different methods are:
– getBoolean(int) - Get the value of a column in the
current row as a Java boolean.
– getByte(int) - Get the value of a column in the
current row as a Java byte.
– getDouble(int) - Get the value of a column in the
current row as a Java double.
– getInt(int) - Get the value of a column in the current
row as a Java int.
We enable you to leverage knowledge
107
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
The following example illustrates the use of the ResultSet
interface and its methods.
Connection connection = DriverManager.getConnection(“jdbc:odbc:emp”, “”, “”);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from Employee");
/* Employee table has three columns first is a code (number), second is name (String)
and
third is age (number)*/
while(resultSet.next()){
int code = rs.getInt(1);
String name= rs.getString(2);
int age = rs.getInt(3);
System.out.println(“Code : ”+ code + “Name: ” + name + “ Age : ” + age);
}
resultSet.close();
connection.close();

We enable you to leverage knowledge


108
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• Types of ResultSet Objects
– ScrollableResultSet
It supports the ability to move a result set’s cursor in
either direction and there are methods for getting the
cursor position and moving the cursor to a particular
row.
– Updatable ResultSets
This allows to make the updates to the values in the
ResultSet itself, and these changes are reflected in
the database.

We enable you to leverage knowledge


109
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• Cursor control methods
– next()
– previous()
– first()
– last()
– beforeFirst()
– afterLast()
– absolute(int rowNumber)
– relative(int rowNumber)

We enable you to leverage knowledge


110
anytime, anywhere!
Using Statement and ResultSet
import java.sql.*;
class JDBCTest{
public static void main(String args[]) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@
DB IPaddress:port_no:host
string",“uid",“password");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from Student");
while(resultSet.next()){
System.out.println(resultSet.getInt("ClassNo"));
} }
catch(Exception exception) {
System.out.println(exception); } }}

We enable you to leverage knowledge


111
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• PreparedStatement interface -- helps us to work with
precompiled SQL statements
• Precompiled SQL statements are faster than normal
statements
• So, if a SQL statement is to be repeated, it is better to
use PreparedStatement
• Some values of the statement can be represented by a ?
character which can be replaced later using setXXX
method

We enable you to leverage knowledge


112
anytime, anywhere!
Using PreparedStatement
import java.sql.*;
class PreparedStatementTest{
public static void main(String args[]) throws Exception{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection(“url", “UID", “password");
PreparedStatement preparedStatement =
connection.prepareStatement("select * from Emp where ename=?");
preparedStatement.setString(1,str);
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString("ename"));
} }
catch(Exception exception){
System.out.println(exception); }
} }

We enable you to leverage knowledge


113
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• CallableStatement interface -- helps us to call stored
procedures and functions
CallableStatement callableStatement =
connection.prepareCall(“execute proc ?”);
callableStatement.setInt(1,50);
callableStatement.execute();

We enable you to leverage knowledge


114
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• The out parameters are to be registered
callableStatement.registerOutParameter(int
parameterIndex, int SQLType);
• To get the value stored in the out parameter--
callableStatement.getXXX(int parameterIndex);

We enable you to leverage knowledge


115
anytime, anywhere!
Using CallableStatement
• Example - Calling a stored procedure named GetSalary.
The procedure queries on the Employee table and
returns the salary of an employee. It has one input
parameter that takes the EmpCode and an out
parameter that returns the salary

CallableStatement callableStatement =
connection.prepareCall("begin GetSalary(?,?); end;");
callableStatement.setInt(1,29418);
// OUT parameters must be registered.
callableStatement.registerOutParameter(2,Types.DOUBLE);
callableStatement.execute();
System.out.println("Salary : " + callableStatement.getDouble(2));

We enable you to leverage knowledge


116
anytime, anywhere!
JDBC - classes and interfaces [Contd..]
• ResultSetMetaData Interface - holds information on the
types and properties of the columns in a ResultSet.
• The following code creates a ResultSet obect and
ResultSetMetaData object.
ResultSet rs = stmt.executeQuery("SELECT * FROM
TABLE2"); ResultSetMetaData rsmd = rs.getMetaData();
• The different methods are:
– getColumnName(int column)
– getColumnType(int column)

We enable you to leverage knowledge


117
anytime, anywhere!
Transaction Management using JDBC

• Transactions
– The capability to group SQL statements for execution
as a single entity is provided through SQL’s
transaction mechanism.
– A transaction consists of one or more statements that
are executed, completed and either committed or
rolled back as a group.
– The commit means that the change is made
permanently in the database, and the term rollback
means that no change is made in the database.

We enable you to leverage knowledge


118
anytime, anywhere!
Transaction Management using JDBC [Contd..]
• By default, auto commit mode of the connection
reference is set to true
• A transaction can be done as follows using methods of
the Connection interface
...
connection.setAutoCommit(false); //by default it is true

try{
//Statements
connection.commit();
}
catch(Exception exception){
connection.rollback();
}

We enable you to leverage knowledge


119
anytime, anywhere!
Transaction Management using JDBC [Contd..]
• Transaction Isolation Levels
This allows to manage simple conflicts arising from
events such as a failure to complete a linked series of
SQL commands.
• The current level of isolation can be queried using the
method :
public int getTransactionIsolation()
• The control over the isolation level of a connection is
provided by this method:
setTransactionIsolation(
TRANSACTION_ISOLATION_LEVEL_XXX).

We enable you to leverage knowledge


120
anytime, anywhere!
Transaction Savepoints
• During a transaction, a named savepoint may be inserted
between operations to act as a marker, so that the
transaction may be rolled back to that marker, leaving all
of the operations before the marker in effect.
• Transaction savepoints are JDBC enhancements that
offer finer control over transaction commit and rollback.
con.setAutocommit(false);
Statement stmt = con.createStatement();
Stmt.executeUpdate(update1);
Savepoint savepoint1 = con.setSavepoint(“SavePoint1”);
stmt.executeUpdate(update2);
stmt.executeUpdate(update3);
con.rollback(savePoint1);

We enable you to leverage knowledge


121
anytime, anywhere!
Java Programming Part 2
Module 5- Java Beans

ER/CORP/CRS/ERJEEML101/003
Lesson Outcomes
• Reflection API

• Introducing Java Beans

• Simple Java Bean

• Why Java Bean

• Java Beans in User Interface

• Naming conventions

We enable you to leverage knowledge


123
anytime, anywhere!
The Reflection API
• Reflection is the ability of software to analyze itself
• The java.lang.reflect package provides reflection
capability to a Java program
• The getClass() method of the class Object returns a
Class object
• The getContructors(), getFields() and getMethods() are
used to analyze the
class object

We enable you to leverage knowledge


124
anytime, anywhere!
Class Objects
• A Class object can be retrieved in several ways.
• If an instance of the class is available, Object.getClass is
invoked.
• The following line of code gets the Class object for an
object named mystery: Class c = mystery.getClass();
• If we need to retrieve the Class object for the superclass
that another Class object reflects, invoke the
getSuperclass method.
• If the name of the class is known at compile time, its
Class object can be retrieved by appending .class to its
name.
• If the class name is unknown at compile time, but
available at runtime, you can use the forName method
We enable you to leverage knowledge
125
anytime, anywhere!
Class Constructors(1/2)
• The information about a class's constructors could be
retrieved by invoking the getConstructors method, which
returns an array of Constructor objects

We enable you to leverage knowledge


126
anytime, anywhere!
Class Constructors ( 2/2)
import java.lang.reflect.*; Output:
import java.awt.*;
()
class SampleConstructor
{ public static void main(String[] args) ( java.awt.Rectangle )
{ Rectangle r = new Rectangle(); showConstructors(r); } ( int int int int )
static void showConstructors(Object o)
{ Class c = o.getClass(); ( int int )
Constructor[] theConstructors = c.getConstructors(); ( java.awt.Point
for (int i = 0; i < theConstructors.length; i++) java.awt.Dimension )
{ System.out.print("( ");
Class[] parameterTypes = ( java.awt.Point )
theConstructors[i].getParameterTypes();
( java.awt.Dimension )
for (int k = 0; k < parameterTypes.length; k ++)
{ String parameterString = parameterTypes[k].getName();
System.out.print(parameterString + " "); }
System.out.println(")");
} }
}

We enable you to leverage knowledge


127
anytime, anywhere!
Identifying Class Fields (1/2)
• A class's fields can be identified by invoking the getFields
method on a Class object.
• The getFields method returns an array of Field objects
containing one object per accessible public field.
• A public field is accessible if it is a member of either:
– this class
– a superclass of this class
– an interface implemented by this class
– an interface extended from an interface implemented
by this class

We enable you to leverage knowledge


128
anytime, anywhere!
Identifying Class Fields (2/2)
import java.lang.reflect.*;
import java.awt.*; Output:
class SampleField Name: RELATIVE, Type: int
{ public static void main(String[] args) Name: REMAINDER, Type: int
{ GridBagConstraints g = new
GridBagConstraints(); Name: NONE, Type: int
printFieldNames(g); } Name: BOTH, Type: int
static void printFieldNames(Object o) Name: HORIZONTAL, Type:
{ Class c = o.getClass(); int
Field[] publicFields = c.getFields(); Name: VERTICAL, Type: int
for (int i = 0; i < publicFields.length;
i++) Name: CENTER, Type: int
{ String fieldName = Name: NORTH, Type: int
publicFields[i].getName(); Name: NORTHEAST, Type: int
Class typeClass = publicFields[i].getType();
Name: EAST, Type: int
String fieldType = typeClass.getName();
System.out.println("Name: " + fieldName + ", Type: Name: SOUTHEAST, Type: int
" + fieldType); Name: SOUTH, Type: int
}}} ….

We enable you to leverage knowledge


129
anytime, anywhere!
What is a Java Bean?
• Component
– An artifact that is one of the individual parts of which makes a
composite entity
– Usually a component is a part that can be separated from or
attached to a system or module in a system
• A Java bean is a reusable software component
– Java Beans is the de-facto component model in Java world
– Java Bean is NOT AN Enterprise Java Bean (EJB)
• EJB is covered in Introduction to J2EE
• Various Frameworks and Tools can use Java Bean
components to build something bigger
– Example 1: An address component holds address of a person in
a program
– Example 2: A text box is a reusable component of a screen
We enable you to leverage knowledge
130
anytime, anywhere!
What is a Java Bean? (Continued…)
• Java Beans API provides a framework for defining software
components that are
– Reusable: Component which is capable of being used again and
again
– Embeddable: Component which is expected to function without
human intervention.
– Modular: A solution made of several discrete pieces, so that any
piece can be replaced without rebuilding the whole solution
• Allows creation of reusable components
– Library of reusable components can be built
– Third Party library of components can be used to build an
application
• Frameworks and Builder tools which use Java Beans components
use Java Reflection API to handle components
We enable you to leverage knowledge
131
anytime, anywhere!
Simple Java Bean
• Employee Class class Employee {
private int employeeNumber;
– Has all data members private String employeeName;
private ...
– Does not have a public void setEmployeeNumber
constructor (int employeeNumber) {
this.employeeNumber=
– A pair of public employeeNumber;
Get/Set methods for }
all or most member public int getEmployeeNumber() {
variables return employeeNumber;
– Names of Get/Set }
public void setEmployeeName
methods should match
(String employeeName) {
the variable names this.employeeName=
• Results in an employeeName;
}
Employee Bean public String getEmployeeName() {
• Has properties return employeeName;
}
– employeeNumber ...
– employeeName }
We enable you to leverage knowledge
132
anytime, anywhere!
Why Java Beans?
• Many real life situations require components to work with various
frameworks and libraries
• Data is in text files, XML files or other textual forms have to be
mapped programmatically in many applications
– Names in text form can be mapped to variable names of a class
– Reflection API in Java is used to achieve this
– Example: <Employee>
<employeeNumber>29853</employeeNumber>
<employeeName>Tom</employeeName>
...
</Employee>

• This is one of the reasons why Java Beans is used extensively in


both UI frameworks and Server side code
• Use of Java beans is more in Server side code than the
GUI code We enable you to leverage knowledge
133
anytime, anywhere!
Properties
• Properties are Discrete attributes of a Bean that are
referenced by name
– Example: “EmployeeNumber” is a property of
EmployeeBean

• Value of a property can be read programmatically by


using a name

We enable you to leverage knowledge


134
anytime, anywhere!
Where do we use Java Beans?
• Data handling and data intensive applications for
mapping textual data to variables

• Server side applications which use component based


design

• Web technologies and related frameworks like JSP,


Struts etc
– JSP Tag beans (covered in Introduction to J2EE
course)
– Struts is a framework for presentation layer of Java
based web applications

• GUI applications based on Java Beans components


– Rarely used because of limited scope of Java in GUI
applications

We enable you to leverage knowledge


135
anytime, anywhere!
Java Beans in User Interface
• BDK (Bean Development Kit) was a specification
from Sun for creating and using reusable UI based
Java Beans

• Difference in UI Java Beans compared to Simple


Java Beans
– Methods to draw on screen are provided
– Methods to persist data and settings
• Persistence: storing data of an object in a non-volatile
manner and retrieving it when required
– Event Handling methods to respond to user action on UI
components
– Customization of component’s features which are visible
graphically
– Application Builder or similar GUI frameworks can understand
and use these components to build GUI Screens

We enable you to leverage knowledge


136
anytime, anywhere!
Naming Conventions
• Bean
– Class name: Any user defined name
– Should not have a constructor
• Properties
– What makes up a property?
– Example:
• A private data member called ‘employeeNumber’
• A public get method by name ‘getEmployeeNumber’
• A public set method by name ‘setEmployeeNumber’
• Together these three form a property of a bean called
‘EmployeeNumber’
• Note: Method names and variables names are case
sensitive
We enable you to leverage knowledge
137
anytime, anywhere!
Bean Serialization (1/2)
• A bean has the property of persistence when its properties,
fields, and state information are saved to and retrieved from
storage.
• The beans support serialization by implementing either the
– java.io.Serializable interface, or the
– java.io.Externalizable interface
• These interfaces offer the choices of automatic serialization
and customized serialization.
• If any class in a class's inheritance hierarchy implements
Serializable or Externalizable, then that class is serializable
• Examples of serializable classes include Component, String,
Date, Vector, and Hashtable

We enable you to leverage knowledge


138
anytime, anywhere!
Bean Serialization (2/2)
• The Serializable interface provides automatic
serialization by using the Java Object Serialization tools.
• Serializable declares no methods; it acts as a marker,
telling the Object Serialization tools that your bean class
is serializable
• To exclude fields from serialization in a Serializable
object from serialization, mark the fields with the
transient modifier.
transient int status;
Default serialization will not serialize transient and static
fields.

We enable you to leverage knowledge


139
anytime, anywhere!
Java Programming Part 2

Module 6: Generics

ER/CORP/CRS/ERJEEML101/003
Why Generics?
• Many algorithms work in a similar way irrespective of the data
types on which they are applied on
– All Stacks work in a similar way irrespective of they type of
object they hold
• Generics help to write algorithms independent of a data type.
• Generic programming in earlier versions of Java uses “Object”
as the basic element of a data structure.
• For example Generic Stack has methods which works with
Objects Class Stack
{
..
public Object push(Object item) {..}
public Object pop(){..}
..}

We enable you to leverage knowledge


141
anytime, anywhere!
Older Approach
• Example: Generic Stack. [JDK1.4]
import java.util.*;
//Removing elements from the stack;
public class StackExample{
Integer x;
public static void main(String[] args){
int i1=1; x= (Integer)s1.pop();
int i2=2; x= (Integer)s1.pop();
int i3=3; x= (Integer)s1.pop();
}
}
//Stack creation
Stack s1=new Stack();

//Adding elements to the stack


s1.push(new Integer(i1));
s1.push(new Integer(i2));
s1.push(new Integer(i3));

We enable you to leverage knowledge


142
anytime, anywhere!
Older Approach (contd..)
• The constraints over this approach are,
– Any object whatever it [String, Integer etc.] may be
can be pushed on to the stack.
– If a Stack is supposed to hold only strings, we can’t
restrict the Stack to hold only the Strings.
– Object that is popped out from the stack has to be
type casted back to the required type before use.
– This type cast is unsafe too. Because the compiler
won’t check whether the typecast is to the same type
as stored in the stack. So the cast may fail at run-time.
• Solution:
– Generics [Java 5]
We enable you to leverage knowledge
143
anytime, anywhere!
New Approach [Generics]
• The new approach expects Stack to be of the form.
Class Stack <E>
{
..
public E push(E item) {..}
public E pop(){..}
..}

• Where E is the Type Parameter.


• The elements pushed onto and popped from the stack are
type E.
• If we declare Stack<String> s=new stack<String>() then
s.push(“Hello”); will be allowed and s.push(new Integer(0)) will
be rejected at compile-time.
• Furthermore s.pop() is known to compiler as String, So no
type cast is necessary.

We enable you to leverage knowledge


144
anytime, anywhere!
New Approach [Generics] (contd..)
• Example: Generic Stack. [Java 5]
import java.util.*;
public class StackExample{
//Removing elements from the stack;
public static void main(String[] args){
int i1=1; Integer x;
int i2=2;
int i3=3; x= s1.pop();
x= s1.pop();
//Stack creation
x= s1.pop();
Stack<Integer> s1=new Stack<Integer>();
//Adding elements to the stack }
s1.push(new Integer(i1)); }
s1.push(new Integer(i2));
s1.push(new Integer(i3));

• In this approach once the compiler knows the element


type of the stack, the compiler can check whether the
correct type is used consistently and can insert the correct
casts on the values taken out from the stack.

We enable you to leverage knowledge


145
anytime, anywhere!
Multiple Type Parameters
• There can be more than one type parameter for a class
or interface.

• Example:

class Hashtable<K,V>{
..
public V put(K key, V value) { ..}
..
}

We enable you to leverage knowledge


146
anytime, anywhere!
Raw Type
• All the collection types in J2SE 5.0 has been made Generic.
• Still a Generic type can be used without type parameters.
Such a type is called Raw type.
• Example: Stack Generic Type used as Raw Type
Stack s=new Stack();
s.push(new Integer(0));
Integer x=(Integer)s.pop();
In such case the compiler will give the following warning.
Note:
D:\NetBeansDemos\GenericsDemo\GenericDemo\src\g
enericdemo\Main.java uses unchecked or unsafe
operations.
Note: Recompile with -Xlint:unchecked for details.
We enable you to leverage knowledge
147
anytime, anywhere!
Bounded Types
• A generic can restrict the type of object that can be used
as the parameter
– A generic List class that performs arithmetic operations on the
elements may want to restrict the parameters to Integer, Float,
Double etc
– Number is the super class of all the numeric wrapper classes

public class List<T extends Number>{


//Code goes here
}

• Only Number or its sub classes can be used as a parameter


to List

We enable you to leverage knowledge


148
anytime, anywhere!
WildCards

• Consider the following example


import java.util.*; List<Integer> li=new ArrayList<Integer>();
public class Main { li.add(new Integer(100));
public static void printList li.add(new Integer(200));
(List<Object> list){ li.add(new Integer(300));
for(Object element:list){
System.out.println(element); printList(ls); //Compilation Error
} printList(li); //Compilation Error
} }
public static void main(String[] args) { Problem: This code won’t compile
List<String> ls=new because printList method expects
ArrayList<String>(); an instance of List<Object> but we
ls.add("One"); are trying to pass List<Integer>
ls.add("Two");
and List<String> instances; though
String and Integer are subclasses
ls.add("Three"); of Object.

We enable you to leverage knowledge


149
anytime, anywhere!
WildCards (Contd..)
• Solution: Use Wildcards.
import java.util.*; List<Integer> li=new
public class Main { ArrayList<Integer>();
public static void printList (List<?> li.add(new Integer(100));
list){ li.add(new Integer(200));
li.add(new Integer(300));
for(Object element:list){
System.out.println(element); printList(ls);
} printList(li);
} }
public static void main(String[] args) {
List<String> ls=new NOTE:
ArrayList<String>(); Wildcards can not be used when
ls.add("One"); declaring or creating a generic data
type. If a list has to be created that
ls.add("Two"); accepts any type of Object, then the
ls.add("Three"); following has to be used
List<Object> lo=new …

We enable you to leverage knowledge


150
anytime, anywhere!
Bounded Wildcards

• Consider the following example


import java.util.*;
public class Main { public static void main(String[]
public static void args) {
sumOfElements(List<?> li){ List<Double> i1=new
double sum=0; ArrayList<Double>();
for(Object element:li){ i1.add(new Double(100));
Number i1.add(new Double(200));
num=(Number)element;
i1.add(new Double(300));
sum+=num.doubleValue();
sumOfElements(i1);
}
System.out.println("Sum of }
elements of the List is: "+sum); }
}

We enable you to leverage knowledge


151
anytime, anywhere!
Bounded Wildcards (contd..)
• Problem:
– sumOfElements method can accept list of any type:
List<String>, List<Object>, List<Integer> etc.
– But as per the requirement it can accept only the list
of Numeric types (Number and its sub types).
• Solution:
– Use Bounded Wildcards.
– Types
• Upper Bounds (Keyword: extends)
• Lower Bounds (Keyword: super)

We enable you to leverage knowledge


152
anytime, anywhere!
Bounded Wildcards (contd..)
• Upper Bounds
– Example:
import java.util.*;
public static void main(String[] args) {
public class Main {
List<Double> i1=new
public static void sumOfElements(List<?
extends Number> li){ ArrayList<Double>();
double sum=0; i1.add(new Double(100));
for(Number element:li){ i1.add(new Double(200));
sum+=element.doubleValue(); i1.add(new Double(300));
} sumOfElements(i1);
System.out.println("Sum of elements }
of the List is: "+sum); } }

– Use of “<? extends Number>” sets sumOfElements method to accept Lists of type List<Number>
or a List of instances of a Number subclass, such as List<Integer>, List<Float>, List<Double> etc
and not others.

We enable you to leverage knowledge


153
anytime, anywhere!
Bounded Wildcards (contd..)
• Lower Bounds

– Keyword: super.
– Example:
• sumOfElements(List<? super Integer> li){..}
– Use of “<? super Integer>” sets sumOfElements
method to accept List of type List< Integer> or a List
of instances of Integer superclass, such as
List<Number> and List<Object> and not others.

We enable you to leverage knowledge


154
anytime, anywhere!
Generic Methods
• Method declarations can also be made generic.
• Based on the types of the arguments passed to the
generic method, the compiler handles each method call
appropriately.
• The type parameter section is delimited by angle
brackets and appears before the method's return type.
public static <T extends Comparable<T>> T public static void main(String[] args) {
greatest(T a,T b){ int max=greatest(19999,2000);
if(a.compareTo(b)>0){ System.out.println(max);
return a; double max1=greatest(-0.0111,
} -0.111);
else{ System.out.println(max1);
return b; } } }

We enable you to leverage knowledge


155
anytime, anywhere!
Generic Sub Class
• A Generic Class can be extended to create another
Generic class
public class LinkedList<T> extends List<T>{
//Code goes here
}

We enable you to leverage knowledge


156
anytime, anywhere!
Generic Interface
• Generic interfaces can be created and used as follows

interface List<T>{
public void put(T element, int position);
public T get(int position);
}

class LinkedList<T> implements List<T>{


//Implementation goes here
}

We enable you to leverage knowledge


157
anytime, anywhere!
Erasure
• Generics in Java are implemented using a technique
called erasure.
• Generic type information is present only at compile time,
after which it is erased by the compiler.
• Advantage:
– interoperability between generic code and legacy code that uses
non-parameterized types (Raw types).
• Disadvantage:
– parameter type information is not available at run time, and that
automatically generated casts may fail when interoperating with
ill-behaved legacy code.
• Example:
Integer ival=new Integer(10);
List<String> ls=new ArrayList<String>();
List lr=ls;
lr.add(ival);
String listData=ls.get(0); //Run Time Error

We enable you to leverage knowledge


158
anytime, anywhere!
Some Generic Restrictions
• A type parameter cannot be instantiated
T t1 = new T(); //Error, this will not work
T [] t2 = new T[5]; //Error, this will not work

• A generic class cannot extend Throwable


– We cannot have generic exception classes
• We can’t use a Generic of Primitive type.
– List<int>=new .. //not allowed.

We enable you to leverage knowledge


159
anytime, anywhere!
Java Programming Part 2
Module 7 - Annotations

ER/CORP/CRS/ERJEEML101/003
Agenda
• Overview
• Introduction to Annotations
• Annotation Basics
• Built-in Annotations
– @override
– @deprecated
– @SuppressWarnings
• Meta Annotations
• Accessing Annotation at Runtime
• Annotation Inheritance
• Advantages of Annotations
• References
We enable you to leverage knowledge
161
anytime, anywhere!
Overview
• Annotations, a new feature in J2SE 5.0 brings a much-
needed metadata facility to the core java language.

• Annotations are modifiers, can be added to the code and


applied to package declarations, type declarations,
constructors, methods, fields, parameters, and variables.

• Annotations do not directly affect program semantics, but


they do affect the way programs are treated by tools and
libraries, which can in turn affect the semantics of the
running program.

We enable you to leverage knowledge


162
anytime, anywhere!
Introduction to Annotations
• The Java designers took the notion of a javadoc tag and
generalized it.
• An Annotation is a special kind of modifiers(such as
public, static or final). By convention, annotations
precede other modifiers.
• An annotation is an attribute of a program element.
• Annotations can be read from source files, class files, or
reflectively at run time
• Annotations take the form of an "at" sign (@), followed by
the annotation name.
• Examples:
@Author( "Jack Doe" )
@Author( value="Jack Doe" )
@Author(@Name(first="Jack",last="Doe"))
We enable you to leverage knowledge
163
anytime, anywhere!
Introduction to Annotations
• Annotations go in their own files, just like classes.
• Annotation interfaces may not extend anything. They
automatically extend java.lang.annotation.Annotation.
Their methods take no arguments.
– A field with the same name is automatically declared.
• An annotation instance consists of
@InfosysAnnotation(
– the "@" sign id = 77480,
– the annotation name Name = “Rahul",
Designation =
– a parenthesized list of name-value pairs. “Manager",
date = “27/3/2007"
• If only one value named value, )
public static void employeeJoining
– The name may be omited. (int id) { ... }

• If no values,
– No parentheses needed.
We enable you to leverage knowledge
164
anytime, anywhere!
Annotation Basics
• Annotatable Program elements:
– package
– class, including
• interface
• enum
– method
– field
– only at compile time
• local variable
• Formal parameter

We enable you to leverage knowledge


165
anytime, anywhere!
Legal Annotation Elements
• primitive types
• Strings
• enum types
• Classes (not general Objects)
• arrays of the above
• combinations of the above

We enable you to leverage knowledge


166
anytime, anywhere!
Annotation Basics
Annotations fall into three basic categories:

Annotations

Marker Multi-valued
Single-valued
Annotations Annotations
Annotations
(With more
(with no member ) (With single
Than one
member)
Member)
Example:-
•@MarkerAnnotation()
•@SingleValueAnnotation("my data")
•@MultiValuedAnnotation(var1="data value 1",
•var2="data value 2", var3="data value 3").

We enable you to leverage knowledge


167
anytime, anywhere!
Built in Annotations
• The pre defined Annotation types are
– @Deprecated
– @override
– @SupressWarnings
– @Target
– @Retention
– @Inherited

We enable you to leverage knowledge


168
anytime, anywhere!
Built in Annotation -Deprecated
• Deprecated is a marker annotation.
• As you might expect, you use Deprecated to annotate a method that
shouldn't be used anymore.
• The following Main class has a method named deprecatedMethod()
that is flagged with the @Deprecated annotation

public class Main {


@Deprecated
public static void deprecatedMethod() {
System.out.println("Don't call me");
}}

You compile a class with annotations the same way as you


do for one without annotations:
> javac Main.java produces Main.class
We enable you to leverage knowledge
169
anytime, anywhere!
Built in Annotation -Deprecated
• If you use the deprecated method, it produces a
compilation-time warning
public class User {
public static void main(String args[]) {
Main.deprecatedMethod(); } }

Compile the class:

javac User.java

and you'll see the following warning about using a


deprecated method:
Note: User.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

We enable you to leverage knowledge


170
anytime, anywhere!
Built in Annotation
• Override : Override should be used only on methods
(not on classes, package declarations, or other
constructs). It indicates that the annotated method is
overriding a method in a superclass.
public class Overrode {
@Override
public int hashCode() {
return 0;
}

@Override
public boolean equals(Object o) {
return true; } }

We enable you to leverage knowledge


171
anytime, anywhere!
SuppressWarnings Annotation
• The final of the three new annotations in J2SE 5.0,
@SuppressWarnings .
• It tells the compiler not to warn you about something that
it would normally warn you about.
• The javac compiler defines seven options to suppress:
all, deprecation, unchecked, fallthrough, path, serial, and
finally.
• let's look at the suppression of the fallthrough option

• Let's start with the following class. Notice that the class is
missing a break statement for each case of the switch
statement:

We enable you to leverage knowledge


172
anytime, anywhere!
SuppressWarnings Annotation
public class Fall {

public static void main(String args[]) {

int i = args.length;
switch (i) {
case 0: System.out.println("0");
case 1: System.out.println("1");
case 2: System.out.println("2");
case 3: System.out.println("3");
default: System.out.println("Default");

}
} }

We enable you to leverage knowledge


173
anytime, anywhere!
SuppressWarnings Annotations
public class Fall {
@SuppressWarnings("fallthrough")
public static void main(String args[]) {
int i = args.length;
switch (i) {
case 0: System.out.println("0");
case 1: System.out.println("1");
case 2: System.out.println("2");
case 3: System.out.println("3");
default: System.out.println("Default");
}
}
}

We enable you to leverage knowledge


174
anytime, anywhere!
Meta Annotations

• @Documented

• @Inherited

• @Target

• @Retention

We enable you to leverage knowledge


175
anytime, anywhere!
Meta-Annotations

• @Documented
– javadoc should be generated when this annotation is
applied to an element
– Is the use of the annotation part of the public API

@Inherited
– Does the annotated get applied to subclasses or to
the base type?
– only works on classes
• not overriden methods
• not interfaces
We enable you to leverage knowledge
176
anytime, anywhere!
Meta-Annotations

• @Target
– Where the annotation can be used
• What kind of source elements
• Defaults in all

public @interface Target {

ElementType[] value();

We enable you to leverage knowledge


177
anytime, anywhere!
Annotation-@Retention
• Indicates how long annotations with the annotated type
are to be retained. If no Retention annotation is present
on an annotation type declaration,

• The retention policy defaults to RetentionPolicy.CLASS.


• Annotations meta-annotated with Retention(RUNTIME)
can be accessed via reflection mechanisms

We enable you to leverage knowledge


178
anytime, anywhere!
Meta Annotations -Retention Policies

• Annotations can have one of three retention policies:


• Source-file retention
– Annotations with source-file retention are read by the compiler
during the compilation process, but are not rendered in the
generated .class files.
• Class-file retention
– This is the default retention policy. Annotations with class-file
retention are read by the compiler and also retained in the
generated .class files.
• Runtime retention
– Annotations with runtime retention are read by the compiler,
retained in the generated .class files, and also made available at
runtime.
• Local variable annotations are not retained in class files (or at runtime)
regardless of the retention policy set on the annotation type

We enable you to leverage knowledge


179
anytime, anywhere!
Class Annotation Example
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(value=RetentionPolicy.RUNTIME)
@Illustrate( {
Illustrate.Feature.annotation,
Illustrate.Feature.enumeration } )
public @interface Illustrate {
enum Feature {
annotation, enumeration, forLoop,
generics, autoboxing, varargs;

@Override public String toString() {


return "the " + name() + " feature";
}
};
Feature[] value() default {Feature.annotation};
}

We enable you to leverage knowledge


180
anytime, anywhere!
import java.lang.annotation.Target;
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;

@Illustrate(
{Illustrate.Feature.enumeration,Illustrate.Feature.forLoop})
public class Suggester {
// @SuppressWarnings({"unchecked"}) // not yet supported
public static void main( String[] args ) {
try {
java.util.Scanner userInput =
new java.util.Scanner( System.in );
System.out.print( "In what class are you interested? " );
Class theClass = Class.forName( userInput.next() );
Illustrate ill =
(Illustrate)theClass.getAnnotation( Illustrate.class);
We enable you to leverage knowledge
181
anytime, anywhere!
if ( ill != null ) {
System.out.println( "Look at this class if you'd " +
" like to see examples of" );
for ( Illustrate.Feature f : ill.value() ) {
System.out.println( "\t" + f );
}
}
else {
System.out.println(
"That class will teach you nothing." );
}
}
catch( ClassNotFoundException cnfe ) {
System.err.println( "I could not find a class named \"" +
cnfe.getMessage() + "\"." );
System.err.println( "Are you sure about that name?" );
}
} }

We enable you to leverage knowledge


182
anytime, anywhere!
Compilation and Execution
• javac *.java
Note: Suggester.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

• java Suggester
In what class are you interested? Suggester
Look at this class if you'd like to see examples of
the enumeration feature
the forLoop feature

• java Suggester
In what class are you interested? Illustrate
Look at this class if you'd like to see examples of
the annotation feature
the enumeration feature

We enable you to leverage knowledge


183
anytime, anywhere!
Annotation Inheritance
• By default annotations are not inherited.
• For Example
@MyAnnotation class Super {

@Oneway public void foo() {}


}

class Sub extends Super {


public void foo() {}
}

Then Sub does not have the MyAnnotation annotation, and


Sub.foo() is not an @Oneway method, despite the fact that it
overrides Super.foo() which is.

We enable you to leverage knowledge


184
anytime, anywhere!
Advantages
• EJB, Web Services etc
– Replace or supplement descriptors with annotation
– Code generate boring classes/interface
• Annotated EJB implementation to generate Home, Remote
etc
• Annotated web Services implementation to generate servlets
binding and JAX-RPC interfaces etc.
• Your use case for generating code form annotated
classes/interfaces
– JavaBeans, logger utilities, debugging classes , etc
• Recognizing special methods, classes, etc at runtime
– Test methods, plug-in points, UI elements, etc

We enable you to leverage knowledge


185
anytime, anywhere!
References
http://java.sun.com/javase/6/docs/technotes/guides/language/
annotations.html

http://www.eclipse.org/aspectj/doc/released/adk15notebook/an
notations.html

http://www-128.ibm.com/developerworks/library/j-annotate1/

http://www-128.ibm.com/developerworks/library/j-
annotate2.html

http://www.softwaresummit.com/2004/speakers/LandersAnnot
ations.pdf
http://java.sun.com/mailers/techtips/corejava/2006/tt0620.html
We enable you to leverage knowledge
186
anytime, anywhere!
Summary
In this course, following topics were covered:-
• Multithreading
• Concurrency
• Input Output Streams & Serialization
• JDBC
• Java Beans
• Generics
• Annotations

We enable you to leverage knowledge


187
anytime, anywhere!
Thank You!

We enable you to leverage knowledge


188
anytime, anywhere!

You might also like