PPT ERJEEML101 JavaProgramming Part 2

185
1

description

PPT ERJEEML101 JavaProgramming Part 2

Transcript of PPT ERJEEML101 JavaProgramming Part 2

Page 1: PPT ERJEEML101 JavaProgramming Part 2

1

Page 2: PPT ERJEEML101 JavaProgramming Part 2

2

Page 3: PPT ERJEEML101 JavaProgramming Part 2

3

Page 4: PPT ERJEEML101 JavaProgramming Part 2

We shall now move on to the module on Multithreading.

4

Page 5: PPT ERJEEML101 JavaProgramming Part 2

After completion of the module you will be able to understand about

5

Creating and managing threads

Priority management

Thread synchronization

Thread groups and daemon threads

Page 6: PPT ERJEEML101 JavaProgramming Part 2

What is a Thread?

A thread is a unit of program having seperate execution path It provides facility to allow

6

A thread is a unit of program having seperate execution path. It provides facility to allowmultiple activities within a single process. Threads are also referred as lightweightprocesses. Each thread has its own program counter, stack and local variables. Threadsshare memory, heap area and files.

Advantages of Threads over Processes:

Threads are being used because they are memory efficient ,share common program space .Faster, context switching is possible since a thread has less context to save than a process.

Page 7: PPT ERJEEML101 JavaProgramming Part 2

A very good example of a multi-threaded application is a game software where the GUIdi l d ti f d ff t d ti di l h i ithi th

7

display, updation of scores, sound effects and timer display are happening within the sameapplication simultaneously

Why to use Threads?

To perform asynchronous or background processing

To Increase the responsiveness of GUI applications

For better utilization of system resources

Threads simplify program logic by having multiple independent entities

Page 8: PPT ERJEEML101 JavaProgramming Part 2

We can create threads in two ways.

8

1. By extending the Thread class and

2. By Implementing the Runnable interface.

In Java we cannot extend from more than one class. In some cases a class might beextending from some parent class and also we need to extend from Thread class. Insuch cases we can do multithreading by implementing Runnable interface.

Page 9: PPT ERJEEML101 JavaProgramming Part 2

9

Page 10: PPT ERJEEML101 JavaProgramming Part 2

The above code create a new class that extends Thread, and then create an instance of thatclass

10

class.

The extending class must override the run() method, which is the entry point for the new thread.It must also call the start() to begin the execution of the new thread. Call to start() methodbegins the execution of the thread by calling the run() method.

The ExtThread() is the constructor of the class which is implicitly called when the instance ofthe extending class is created.

Page 11: PPT ERJEEML101 JavaProgramming Part 2

The other option to create a thread is by implementing Runnable interface.

11

To implement Runnable, a class need to implement a single method called run().

run() implementation contains , the code that constitutes the new thread.

Page 12: PPT ERJEEML101 JavaProgramming Part 2

In order to create a thread from Runnable interface, we need to create a class thati l t R bl h i l ti th R bl i t f th i t f th

12

implements Runnable. when implementing the Runnable interface the instance of theimplementing class is to be created and the object of the same has to be passed to theobject of the Thread class to specify whose run method has to be executed which theninvokes the start() method, which starts the thread by invoking run() method.

Page 13: PPT ERJEEML101 JavaProgramming Part 2

A thread can be in one of the following states.

13

Newborn State:

When the new instance of the thread is created by executing the constructor Thread( ),Thread is said to be newborn. In this state no resources are allocated to the thread.

Runnable State:

When a start() method is called on the newborn thread instance, thread makes the transitionto Runnable state. In this state the thread is waiting for the scheduler to schedule it on theprocessor.

Running State:

When thread is being executed by the CPU it will be in the running state.

Non-Runnable State:

A running state can be suspended, i.e temporarily suspended from its activity. This is doneby invoking sleep() or wait () method. A suspended thread can then be resumed, allowing itto pick up from where it left off, by calling notify() method or when the sleep interval expires.

A thread will be blocked when waiting for a resource and will be unblocked once things aredone.

Dead State:

A thread comes to a dead state if it is over with the task. At any time, a thread can beterminated, which halts its execution immediately. Once terminated, a thread cannot beresumed.

Page 14: PPT ERJEEML101 JavaProgramming Part 2

There are 2 techniques for thread scheduling

14

Pre-emptive and time-sliced

In preemptive scheduling, the thread with a higher priority preempts threads with lowerpriority and grabs the CPU

In time-sliced or round robin scheduling, each thread will get some time of the CPU

The Java runtime system's thread scheduling algorithm is Fixed Priority preemptive. If at anytime a thread with a higher priority than all other runnable threads becomes runnable, theruntime system chooses the new higher priority thread for execution. The new higher prioritythread is said to preempt the other threads.

In the case when two Threads which are having same priority are competing for CPU thenis up to the underlying platform to decide on how to handle.

Solaris is preemptive, Macintosh and Windows are time sliced. In the case of Macintosh andWindows the threads of equal priority are time-sliced automatically in round-robin fashion. Incase of OS of preemptive types the threads of equal priority must yield control to its peersvoluntarily. If not done, then others has to wait.

Page 15: PPT ERJEEML101 JavaProgramming Part 2

In Java you can assign each thread a priority that determines how that thread should bet t d ith t t th Th d i iti i t th t if th l ti i it

15

treated with respect to others. Thread priorities are integers that specify the relative priorityof one thread to another. Thread priority can be used by the scheduler to decide whichthread is to be run. The priority of a Thread can be set using the method setPriority(). Themethod getPriority() will return the priority of a Thread. The priority can vary from 1 to 10.Thread.MIN_PRIORITY and Thread.MAX_PRIORITY can also be used for values of 1 and10. Normally a Thread will have the priority value of 5 also represented asThread.NORM_PRIORITY

Thread priority is used to decide when to switch from one running thread to the next. Thisprocess of switching is known as context switch.

Page 16: PPT ERJEEML101 JavaProgramming Part 2

The programmer should write code to ensure that time-slicing occurs even when theli ti i i i ti i t

16

application is running in a preemptive environment.

The static method sleep() of the Thread class will make a thread sleep for specified numberof milliseconds.

A sleeping thread can be interrupted by another thread using the method interrupt()

When interrupted, sleep method will throw an InterruptedException

Page 17: PPT ERJEEML101 JavaProgramming Part 2

yield():

17

It is used to give the other threads of the same priority a chance to execute. If other threadsat the same priority are runnable, yield() places the calling thread in the running state intothe runnable pool and allows another thread to run. If no other threads are runnable at thesame priority, yield() does nothing.

Page 18: PPT ERJEEML101 JavaProgramming Part 2

isAlive() method is used to determine if a thread is still alive. The term alive does not implyth t th th d i i it t t f th d th t h b t t d b t t l t d

18

that the thread is running; it returns true for a thread that has been started but not completedits task.

The method that you will more commonly use to wait for a thread to finish is called join().This method waits until the thread on which it is called terminates.

Page 19: PPT ERJEEML101 JavaProgramming Part 2

In a multithreaded environment two or more threads may access a shared resource.

19

There should be some means to ensure that the shared resource is accessed by only one thread at a time. There used is synchronization

In the case of 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.

Page 20: PPT ERJEEML101 JavaProgramming Part 2

Synchronization can be ensured by using the keyword synchronized

20

A method or block of code can be made synchronized.

Here is an example where a method is synchronized.

Page 21: PPT ERJEEML101 JavaProgramming Part 2

For interthread communication we use three method on collaboration that is wait(),notify()d tif ll () th d

21

and notifyall () methods.

Wait method can either wait for some time duration or on some condition .notify() andnotifyall() method methods are being used to tell to other threads that CPU cycles are freeand can be used by another thread.

Page 22: PPT ERJEEML101 JavaProgramming Part 2

22

Page 23: PPT ERJEEML101 JavaProgramming Part 2

In the above code, the bankBalance is a sharable resource between threads that areti d bitA t() d ditA t() th d B th th th d h b

23

executing debitAccount() and creditAccount() method. Both the methods have beendeclared as synchronized so that only one thread can access one of these methodscompletely at a time. i.e. While a thread is inside a synchronized method, all the otherthreads that try to call it or any other synchronized method on the same instance have towait.

debitAccount() method debits amount from bankBalance. The bankBalance should not belet with a negative value. So a check is made to see whether the sufficient amount isavailable before debiting the amount. If not the debit process should not happen. i.e theactivity must be kept in the pending state till the required amount gets credited.

This can be done as follows. The threads that enter the debitAccount() method on seeing thelowbalance has to wait till another thread can enter creditaccount method and updates thebalance. Since both the methods are synchorized only one thread can be active at a time onany of the methods of the account object. So the first thread calls wait() and gives up themonitor which will be used by second thread and finishes it work and notifies the first threadby calling notify(). Now the first thread resumes and finish of the task.

Page 24: PPT ERJEEML101 JavaProgramming Part 2

This program illustrates Inter-thread communication. Pause the presentation and analyze th d d lt

24

the code and result.

Page 25: PPT ERJEEML101 JavaProgramming Part 2

Represents a set of threads

25

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

ThreadGroup threadGroup = new ThreadGroup("MyGroup"); creates a new thread group.

Some of the important methods of ThreadGroup are activeCount(), destroy(), setMaxPriority()and setDaemon()

Page 26: PPT ERJEEML101 JavaProgramming Part 2

Daemon Thread is a thread that will run in the background, serving other threads.

26

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().

The system itself always has a few daemon threads running, one of which is the garbage collector.

Page 27: PPT ERJEEML101 JavaProgramming Part 2

In Multithreading module, we have discussed the low level APIs that help us to have Multithreading at li ti l l I thi d l ill di f th hi h l l f t hi h

27

application level. In this module we will discuss some of the high-level concurrency features which are introduced with Java 5.

Page 28: PPT ERJEEML101 JavaProgramming Part 2

Some of the high-level features are

28

Lock Objects

Executors

Synchronizers

Callables and Futures

Concurrent Collections

Atomic variables

Etc.

Page 29: PPT ERJEEML101 JavaProgramming Part 2

29

Page 30: PPT ERJEEML101 JavaProgramming Part 2

30

Page 31: PPT ERJEEML101 JavaProgramming Part 2

This example shows how to work with Executors.

31

Executors.newSingleThreadExecutor() method returns the executor which executes the command sometime in the future.

Page 32: PPT ERJEEML101 JavaProgramming Part 2

32

Page 33: PPT ERJEEML101 JavaProgramming Part 2

33

Page 34: PPT ERJEEML101 JavaProgramming Part 2

The given program explains the usage of Callable and Future Interfaces.

34

Page 35: PPT ERJEEML101 JavaProgramming Part 2

35

Page 36: PPT ERJEEML101 JavaProgramming Part 2

36

Page 37: PPT ERJEEML101 JavaProgramming Part 2

37

Page 38: PPT ERJEEML101 JavaProgramming Part 2

Here is a simple example to work with Semaphore which is associated with the account bj t

38

object.

Page 39: PPT ERJEEML101 JavaProgramming Part 2

39

Page 40: PPT ERJEEML101 JavaProgramming Part 2

40

Page 41: PPT ERJEEML101 JavaProgramming Part 2

41

Page 42: PPT ERJEEML101 JavaProgramming Part 2

42

Page 43: PPT ERJEEML101 JavaProgramming Part 2

Here is a simple example that work with locks.

43

Page 44: PPT ERJEEML101 JavaProgramming Part 2

We shall now move on to the module on Input Output Streams & Serialization.

44

Page 45: PPT ERJEEML101 JavaProgramming Part 2

After completion of the module you will be able to understand about

45

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? and

What is Serialization?

Page 46: PPT ERJEEML101 JavaProgramming Part 2

A stream is a path of communication between the source of some information and itsd ti ti Th d th d ti ti b fil th t '

46

destination. The source and the destination can be a file, the computer's memory, or eventhe Internet. An input stream allows you to read data from a source, and an output streamallows you to write data to a destination.

Page 47: PPT ERJEEML101 JavaProgramming Part 2

This diagram shows how streams work with the source and destination.

47

Page 48: PPT ERJEEML101 JavaProgramming Part 2

Classes which performs input output operations are available in a package name java.io.

48

There are four abstract classes up in the hierarchy which are :

Under Byte Stream:

1:InputStream

2:OutputStream

Under Char Stream:

1:Reader

2:Writer

We need to create object of there subclasses in order to create stream and perform input output operation.

Page 49: PPT ERJEEML101 JavaProgramming Part 2

A stream, which receives and sends information as bytes, is called a byte-oriented stream. At th t f th hi h th t b t t l I tSt d O t tSt fAt the top of the hierarchy are the two abstract classes: InputStream and OutputStream for input and output respectively. These classes define many important methods for handling the streams. The read() and write() methods in the InputStream and OutputStream are used for reading and writing to and from streams respectively. Both these methods are abstract and are implemented by all the classes derived from these InputStream and OutputStream classes .

49

Page 50: PPT ERJEEML101 JavaProgramming Part 2

50

Page 51: PPT ERJEEML101 JavaProgramming Part 2

Here are the Byte Input Stream Classes derived from the abstract class InputStream.

51

ByteArrayInputStream

It is used to create an input stream from an array of bytes. Allows a buffer in memory to be used as anInputStream.

FileInputStream

For reading information from a file.

ObjectInputStream

It supports retrieving the stored state of an object. It is associated with deserialization.

Filtered Streams: There are the wrappers around underlying I/O streams that transparently providesome extended level of functionality to the other InputSteam classes.

BufferedInputStream

This is one of the most valuable of all streams. Using a buffer, it prevents a physical read every timewhen more data is needed. It uses buffered array of bytes that acts as a cache for future reading.

DataInputStream

Used to read primitives from a stream in a portable fashion. All the methods that instances of this classunderstand are defined in a separate interface called DataInput, and implemented by this stream.

PushbackInputStream

Has a one byte push-back buffer with which it is possible to push back the last read byte. The filterstream class.

Page 52: PPT ERJEEML101 JavaProgramming Part 2

Methods defined in InputStream are,

52

available() – bytes of input available for reading will be returned by this method.

close() – closes the input source.IOException will be generated if further reading continues.

mark(int numberofBytes) – Responsible to put a mark at the current point in the input stream .Validity will beuntil you read those number of bytes

markSupported() – returns Boolean value true if this feature of mark()/reset() is supported.

read() –next available bytes integer representation in the input returned by this method .

reset() – For resetting the input pointer to previous set mark.

skip(long numberofBytes) – ignores the numberofBytes of input and returns the numberofBytes ignoredactually.

Page 53: PPT ERJEEML101 JavaProgramming Part 2

53

Page 54: PPT ERJEEML101 JavaProgramming Part 2

54

Page 55: PPT ERJEEML101 JavaProgramming Part 2

55

Page 56: PPT ERJEEML101 JavaProgramming Part 2

Here are the Byte Output Stream Classes derived from the abstract class OutputStream.

56

ByteArrayOutputStream

It is an implementation of an output stream that uses a byte array as the destination. The inverse ofByteArrayInputStream, which creates an input stream from an array of bytes, the ByteArrayOutputStream, directsan output stream into an array of bytes.

FileoutputStream

It is used for writing information to a file.

ObjectOutputStream

It supports permanently saving the state of an object. It is associated with serialization.

Filtered Streams: These are wrappers around underlying I/O streams that transparently provide some extendedlevel of functionality to the other OutputStream classes.

BufferedOutputStream

Using a buffer, it prevents a physical write every time data is sent.

DataOutputStream

It is used to write primitives to a stream in a portable fashion.

PrintStream

It is used for producing formatted output.

Page 57: PPT ERJEEML101 JavaProgramming Part 2

Methods defined in OutputStream are,

57

close() – This closes the output stream.

flush() – It flushes the output buffers.

write(int b) – this writes a byte to an output stream

write(byte buffer[]) - this writes an array of bytes to the output stream

write(byte buffer[], int offset, int numberofBytes) this writes a specified range of bytes from abyte array to the output stream

Page 58: PPT ERJEEML101 JavaProgramming Part 2

58

Page 59: PPT ERJEEML101 JavaProgramming Part 2

59

Page 60: PPT ERJEEML101 JavaProgramming Part 2

60

Page 61: PPT ERJEEML101 JavaProgramming Part 2

61

Page 62: PPT ERJEEML101 JavaProgramming Part 2

62

Page 63: PPT ERJEEML101 JavaProgramming Part 2

63

Page 64: PPT ERJEEML101 JavaProgramming Part 2

64

Page 65: PPT ERJEEML101 JavaProgramming Part 2

65

Page 66: PPT ERJEEML101 JavaProgramming Part 2

66

Page 67: PPT ERJEEML101 JavaProgramming Part 2

67

Page 68: PPT ERJEEML101 JavaProgramming Part 2

68

Page 69: PPT ERJEEML101 JavaProgramming Part 2

69

Page 70: PPT ERJEEML101 JavaProgramming Part 2

70

The DataOutputStream class and DataInputStream class are complement to each other .It is basically used to read and write primitive data and user defined data such as object to stream. It also keeps track of the number of bytes written to the output stream. It is an output filter and can be combined with any output-filtering streams.

Page 71: PPT ERJEEML101 JavaProgramming Part 2

71

The readXXX() methods are used to read primitive data while writeXXX() methods are used to write primitive data.

Page 72: PPT ERJEEML101 JavaProgramming Part 2

72

The DataOutputStream class and DataInputStream are complement to each other. Arbitrary objects and primitive data types can be written to the output stream with the help of these classes. Number of bytes written to the output stream can be traced by using these classes

Page 73: PPT ERJEEML101 JavaProgramming Part 2

73

This demo demonstrate how DataInputStream class can be configured with other fiter input stream classes to read the data.

Page 74: PPT ERJEEML101 JavaProgramming Part 2

When reading an input, you often need to peek at the next byte to see if it is the value thatt J id P hb kI tSt f thi Y d th b t

74

you expect. Java provides PushbackInputStream for this purpose. You can read the bytefrom the stream and push it back to the stream by unreading it.

The first form of unread() method pushes back the low order byte of bytevalue. This will bethe next byte returned by call to read().

The second form of unread() returns the bytes in the buffer.

The third form of unread() pushes back numBytes bytes beginning at offset from buffer.

Page 75: PPT ERJEEML101 JavaProgramming Part 2

PrintStream filter class provides functionality to print all data types.

75

It pro two methods, print() and println(), that are overloaded to print any primitive data type orobject.

Objects are printed by first converting them to strings using their toString() method inheritedfrom the Object class.

PrintStream class has the following constructor

PrintStream(OutputStream outputStream)

System.out is a PrintStream object

Page 76: PPT ERJEEML101 JavaProgramming Part 2

76

Page 77: PPT ERJEEML101 JavaProgramming Part 2

77

Page 78: PPT ERJEEML101 JavaProgramming Part 2

78

Page 79: PPT ERJEEML101 JavaProgramming Part 2

79

Page 80: PPT ERJEEML101 JavaProgramming Part 2

80

Page 81: PPT ERJEEML101 JavaProgramming Part 2

81

Page 82: PPT ERJEEML101 JavaProgramming Part 2

82

Page 83: PPT ERJEEML101 JavaProgramming Part 2

83

Page 84: PPT ERJEEML101 JavaProgramming Part 2

84

Page 85: PPT ERJEEML101 JavaProgramming Part 2

85

In order to write the object's contents to the stream and also read them back from the stream you can use methods of Externalizable class .

Interface Externalizable

Externalizable interface is a subclass of Serializable.

2 methods of this interface are: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized . Write code that reads/writes only the values of the attributes you are interested in in these methods. These attributes must be in the same sequence while serialization and desrialization.

Page 86: PPT ERJEEML101 JavaProgramming Part 2

86

Page 87: PPT ERJEEML101 JavaProgramming Part 2

87

Page 88: PPT ERJEEML101 JavaProgramming Part 2

88

Page 89: PPT ERJEEML101 JavaProgramming Part 2

89

Page 90: PPT ERJEEML101 JavaProgramming Part 2

We shall now move on to the module on JDBC.

90

Page 91: PPT ERJEEML101 JavaProgramming Part 2

After completion of the module you will be able to understand

91

What is JDBC?

What are the advantages of using JDBC?

How to work with a database using JDBC? and

Transaction control in JDBC.

Page 92: PPT ERJEEML101 JavaProgramming Part 2

The JDBC (Java Database Connectivity) API helps a Java program to access a databasei t d d

92

in a standard way.

JDBC is a specification that tells the database vendors how to write a driver program tointerface Java programs with their database.

Page 93: PPT ERJEEML101 JavaProgramming Part 2

A Driver written according to JDBC standard is called the JDBC Driver

93

All related classes and interfaces are present in the java.sql package

All JDBC Drivers implement the interfaces of java.sql

Page 94: PPT ERJEEML101 JavaProgramming Part 2

There are 4 types of drivers --Type1, Type2, Type3,Type4 drivers.

94

Let us see one by one in detail.

Page 95: PPT ERJEEML101 JavaProgramming Part 2

Type 1 driver uses ODBC connectivity which makes it dependent on the platform you arei it ODBC i itt i lik d hi h d d t t

95

using it.ODBC is written in programs like c and c++ which are dependent on system.

We use type 1 driver when you have to use it demonstration and all.

Page 96: PPT ERJEEML101 JavaProgramming Part 2

The driver is compiled for use with the particular operating system. The type 2 driver is notitt ti l i J it i t f ith J d th t k th fi l d t b

96

written entirely in Java as it interfaces with non-Java code that makes the final databasecalls.

Page 97: PPT ERJEEML101 JavaProgramming Part 2

This gives better performance that type 1 and type 2 drivers.

97

The type 3 driver is platform-independent as the platform-related differences are taken careby the middleware.

Page 98: PPT ERJEEML101 JavaProgramming Part 2

This is written entirely in java that why it achieves platform independence .This is the bestd i il bl d t th t 1 2 3 d i

98

driver available as compared to the type 1,2,3 drivers.

Page 99: PPT ERJEEML101 JavaProgramming Part 2

99

Page 100: PPT ERJEEML101 JavaProgramming Part 2

100

DriverManager class is responsible for loading the driver into the memory in that way it helps the dynamic loading of the drivers.

If you want to use features like connection pooling and want to have connection available in distributed application thane you cane make use of datasourse.

Page 101: PPT ERJEEML101 JavaProgramming Part 2

101

Page 102: PPT ERJEEML101 JavaProgramming Part 2

There are different overloaded version of getConnection method is available which can bed th i t

102

used as per the requirement.

Page 103: PPT ERJEEML101 JavaProgramming Part 2

Connection interface -

103

A connection object is representing the connection to the database.

In a session there can be number of Sql statament related to that connection object.

One application can have multiple connectivity through number of connection object or one application can have multiple connetion objects.

Page 104: PPT ERJEEML101 JavaProgramming Part 2

The different methods of Connection interface are:

104

close() – this method is responsible closing the database connection

createStatement() – this method is used to create an SQL Statement object

prepareStatement() – this method is used to create an SQL PreparedStatementobject.

prepareCall() – this method is responsible to create an SQL CallableStatementobject using the SQL string provided. (CallableStatement are used to invoke stored

procedure calls written in SQL language)

Page 105: PPT ERJEEML101 JavaProgramming Part 2

SQL is the language used to interact with the database. To retrieve or insert, update andd l t d t i t d t b d t t SQL t t t J id th

105

delete data into a database you need to execute SQL statements. Java provides threeinterfaces, i.e. the Statement interface, the PreparedStatement interface and theCallableStatement interface to achieve this.

Statement•It is responsible to Execute SQL without parameters

PreparedStatement•Responsible for pre-compiled SQL statements execution with or without

parameters

CallableStatement

•This statement Execute a call to the database stored procedure or function

Page 106: PPT ERJEEML101 JavaProgramming Part 2

Statement interface - defines methods to interact with database.

106

The different methods are:

executeQuery(String sql) - SQL statement (SELECT) can be executed by usingthis method that queries a database and in return gives a ResultSet object.

executeUpdate(String sql) - SQL statement (INSERT,UPDATE,or DELETE) canbe executed by using this method that updates the database and returns an int, thatis the row count associated with the SQL statement

execute(String sql) - SQL statement that is written as String object can beexecuted by using this method

getResultSet() – is used when we want to retrieve the ResultSet object

Page 107: PPT ERJEEML101 JavaProgramming Part 2

An example of the usage of the Statement interface and its methods is shown here usingth ‘E l ’ t bl d ’ DSN Th ‘E l ’ t bl i t f th fi ld l

107

the ‘Employee’ table and emp’ DSN. The ‘Employee’ table consists of three fields namely‘empcode’, ‘empname’ and ‘empage’. Pause the presentation and analyze the code.

Page 108: PPT ERJEEML101 JavaProgramming Part 2

Database query results are retrieved within ResultSet object.

108

The ResultSet is maintaining the position of the current row, whaich is starting with the first row ofdata returned.

The results of the query are returned as a table of data in rows and columns. The ‘ResultSet’ interfaceprovides access to this data. Method which helps us to access the database throws an SQLException so, you have to take neccsary action to handle SQLException.

Page 109: PPT ERJEEML101 JavaProgramming Part 2

The given example illustrates the use of the ResultSet interface and its methods. Pause thet ti d l th d

109

presentation and analyze the code.

Page 110: PPT ERJEEML101 JavaProgramming Part 2

Types of ResultSet Objects

110

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.

To create a Scrollable Resultset, we need to call the createStatement method with two arguments passed, the first specify the type of the ResultSet object.

The second argument must be one of the two ResultSet constants for specifying whether a result set is read-only or updateable.

To create an UpdatableResultSet object,we need to call the createStatement method with the ResultSet constant CONCUR_UPDATABLE as the second argument.The Statement object created produces an updatable ResultSet object when it executes a query.

Once you have an UpdatableResultSet object, you can insert a new row, delete an existing row, or modify one or more column values in the Result set and these changes will be reflected in the database.

Page 111: PPT ERJEEML101 JavaProgramming Part 2

In addition to the ResultSet.next() method, which is used to move the cursor forward, onet ti ll bl R ltS t t th th d i () hi h th

111

row at a time, scrollable ResultSets support the method previous() which moves the cursorback one row.

The effect of the first(), last(), beforeFirst() and afterLast() are clear from the method namesitself.

The method absolute(int number) moves the cursor to the row number indicated in theargument.

The method relative(int rowNumber) lets you specify how many rows to move from thecurrent row and in which direction to move. A positive number moves the cursor forward thegiven number of rows, a negative number moves the cursor backward the given number ofrows.

Page 112: PPT ERJEEML101 JavaProgramming Part 2

Here is a simple program that consolidates how to work with Statement and ResultSeti t f P th t ti d l th d

112

interfaces. Pause the presentation and analyze the code.

Page 113: PPT ERJEEML101 JavaProgramming Part 2

PreparedStatement interface -- helps us to execute precompiled SQL statements

113

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 replacedlater using setXXX method.

Page 114: PPT ERJEEML101 JavaProgramming Part 2

Here is a simple program that consolidates how to work with PreparedStatement andR ltS t i t f P th t ti d l th d

114

ResultSet interfaces. Pause the presentation and analyze the code.

Page 115: PPT ERJEEML101 JavaProgramming Part 2

CallableStatement interface -- helps us to call stored procedures and functions.

115

Page 116: PPT ERJEEML101 JavaProgramming Part 2

Before executing the procedures we have to register the out parameters of the procedurei i t O tP t () th d Aft ti th lt t d i t t

116

using registerOutParameter() method. After execution the result stored in out parameterscan be retrieved using getXXX() methods.

Page 117: PPT ERJEEML101 JavaProgramming Part 2

Here is a piece of code that lets you know how to work with CallableStatement interface.P th t ti d l th d

117

Pause the presentation and analyze the code.

Page 118: PPT ERJEEML101 JavaProgramming Part 2

118

Page 119: PPT ERJEEML101 JavaProgramming Part 2

The capability to group SQL statements for execution as a single entity is provided through SQL’ t ti h i

119

SQL’s transaction mechanism.

A transaction is collection of one or more statements that are executed as a unit that means they are either committed or rolled back as a group.

The commit command means that the change is made permanently in the database, and the rollback means that no change is made in the database

When the method commit or rollback is called, the current transaction ends, and another one begins.

A new JDBC connection is in auto-commit mode by default, meaning that when a statement is completed, the method commit is called on that statement automatically.

The commit occurs when the statement completes or the next execute occurs, whichever comes first.

Page 120: PPT ERJEEML101 JavaProgramming Part 2

If auto-commit mode has been disabled, a transaction will not terminate until either theit th d th llb k th d i ll d li itl th t ti ill i l d ll

120

commit method or the rollback method is called explicitly, so the transaction will include allthe statements that have executed since the last invocation of the commit or rollbackmethod.

Page 121: PPT ERJEEML101 JavaProgramming Part 2

Consider the case of a multiuser application, where one transaction has initiated a transferb t t t b t h t t itt d it h d t ti tt t t

121

between two accounts but has not yet committed it, when a second transaction attempts toaccess one of the account in question.

If the first transaction is rolled back, the value the second transaction reads will be invalid.

JDBC defines different levels of transaction isolation that provides different levels of conflictmanagement. The first and lowest level specifies that transaction are not supported at all,and on the other side the highest specifies that while one transaction is operating on adatabase, no other transactions is allowed make any changes to the data that transactionreads.

setTransactionIsolation(int level) of Connection interface sets the specified isolation level.Level can take one of the five values,

Connection.TRANSACTION_NONE,Connection.TRANSACTION_READ_UNCOMMITTED

Connection.TRANSACTION_READ_COMMITTED

Connection.TRANSACTION_REPEATABLE_READ

Connection.TRANSACTION_SERIALIZABLE

Page 122: PPT ERJEEML101 JavaProgramming Part 2

During a transaction, a named savepoint may be inserted between operations to act as ak th t th t ti b ll d b k t th t k l i ll f th

122

marker, so that the transaction may be rolled back to that marker, leaving all of theoperations before the marker in effect.

The above code shows a Savepoint being set after the first update,and the transaction beingrolled back to that Savepoint,removing two subsequent updates.

When a SQL statements make changes to a database, the commit method makes thosechanges permanent, and it releases any locks the transaction holds.

The rollback method, on the other hand, simply discards those changes.

Page 123: PPT ERJEEML101 JavaProgramming Part 2

We shall now move on to the module on Java Beans.

123

Page 124: PPT ERJEEML101 JavaProgramming Part 2

After completion of the module you will be able to understand about

124

•Reflection APIs

•What are Java Beans

•Why Java Beans are used

•How to write Java Beans

•Java Beans role in user interface

•and the Naming Convention followed in Java Beans.

Page 125: PPT ERJEEML101 JavaProgramming Part 2

125

The java.lang.reflect package provides reflection capability to a Java program.Which canhelp you determine what methods, constructors, and fields a class supports.

For each class the Java Run Time Environment (JRE) maintains an immutable Class object.This object contains all the details such as constructors, methods, and fields in the class,super class of the class if it is there and the interfaces if implemented by the class.

The getClass() method of the class’s object; for example we are having a class named Xand its object x1. Then x1.getClass() method returns a Class object of X, which contains allthe details of X.

The methods getContructors(), getFields() and getMethods() are used to analyze the Classobject.

Page 126: PPT ERJEEML101 JavaProgramming Part 2

126

Page 127: PPT ERJEEML101 JavaProgramming Part 2

The information about a class's constructors can be retrieved by invoking thetC t t () th d th Cl bj t hi h t f C t t bj t

127

getConstructors() method on the Class object, which returns an array of Constructor objects.Constructor Class has set of methods with which you determine the modifiers, parametertypes etc of the constructor.

Page 128: PPT ERJEEML101 JavaProgramming Part 2

Here is a sample program.

128

The above program prints the parameter types of each constructor in the Rectangle class.

The program performs the following steps:

1. It retrieves an array of Constructor objects from the Class object by calling getConstructors() method.

2. For every element in the Constructor array, it creates an array of Class objects by invokinggetParameterTypes() method. The Class objects in the array represent the parameters of theconstructor.

The program calls getName() method to fetch the class name of every parameter in the Class arraycreated in the preceding step.

When you try the program you can see the output as shown here.

Page 129: PPT ERJEEML101 JavaProgramming Part 2

129

Page 130: PPT ERJEEML101 JavaProgramming Part 2

130

When you try the program you can see the output as shown next to the program in theslides.

Page 131: PPT ERJEEML101 JavaProgramming Part 2

Java Beans:

131

A Java Bean is a reusable software component that can be visually manipulated in buildertools. The JavaBeans API makes it possible to write component software in the Javaprogramming language.

A Java Bean bears a strong resemblance to a well-written Java application. But since it is acomponent, a Bean's scope is usually smaller than that of an entire application, making iteasier to develop.

Page 132: PPT ERJEEML101 JavaProgramming Part 2

Java Beans API provides a framework for defining software components that are reusable,E b dd bl d d l

132

Embeddable and modular.

The main purposes of Java Beans are closely related to the main advantages of Javatechnology: The advantages includes

•Platform independence

•Mobility in a networked environment.

•Expose accessor methods (e.g. getValue() and setValue()) to allow retrieval and changingof attribute values by external sources;

•Allow for easy mixing and matching via GUI development tools;

•Generate or respond to appropriate events;

•Save their state using the Java Serialization mechanism.

•Compact and Easy

•Leverages the Strengths of the Java Platform

•Flexible Build-Time Component Editors

Frameworks and Builder tools which use Java Beans components use Java Reflection APIto handle components

Page 133: PPT ERJEEML101 JavaProgramming Part 2

Here is an example for Java Bean. The Employee class which

133

Has all data members private

Does not have a constructor

Having pair of public Get/Set methods for all or most member variables

Results in an Employee Bean. This bean has two properties employeeNumber andemployeeName.

Note the convention in writing the getter and setter methods of a property. The gettermethod will start with get followed by the name of the property with the initial letter in caps.Same holds with setter method.

Page 134: PPT ERJEEML101 JavaProgramming Part 2

Many real life situations require components to work with various frameworks and libraries

134

Data is in text files, XML files or other textual forms have to be mapped programmatically inmany applications i.e.

Names in text form can be mapped to variable names of a class

Reflection API in Java is used to achieve this

This is one of the reasons why Java Beans is used extensively in both UI frameworks andServer side code

Use of Java beans is more in Server side code than the GUI code

Page 135: PPT ERJEEML101 JavaProgramming Part 2

Properties:

135

Properties are attributes of a Bean that are referenced by name. These properties areusually read and written by calling methods on the Bean specifically created for thatpurpose.

Page 136: PPT ERJEEML101 JavaProgramming Part 2

Where do we use Java Beans?

136

Data handling and data intensive applications for mapping textual data to variables usesJava Beans.

Server side applications which use component based design uses Java Beans.

Web technologies and related frameworks like JSP, Struts etc uses Java Beans. Forexample:

JSP uses Java Beans so that the business logic can be moved to Java Beans andthe JSP page can handle only the presentation logic and use these Java Beans bywriting appropriate tags.

GUI applications based on Java Beans components uses Java Beans.

Page 137: PPT ERJEEML101 JavaProgramming Part 2

BDK (Bean Development Kit) was a specification from Sun for creating and usingbl UI b d J B

137

reusable UI based Java Beans

UI Java Beans differs from Simple Java Beans in the

Methods to draw on screen

Methods to persist data and settings

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 tobuild GUI Screens

Page 138: PPT ERJEEML101 JavaProgramming Part 2

The source code of a Java Bean has to follow certain naming conventions.

138

The naming conventions are:

Bean class can have any user defined name.

Three things need to be applies for a property

1. Data member should be private.

2. getter and setter methods should be public .

As discussed The getter method will start with get followed by the name of the property withthe initial letter in caps. Same holds with setter method.

Few more Conventions are,

• java.io.Serializable interface should be implemented by java bean class

• It should have a default constructor

• Properties of bean should be accessed using getter and setter methods .

• Required event handling methods should be there

Page 139: PPT ERJEEML101 JavaProgramming Part 2

Bean Serialization

139

A bean can be used as persistence component when its state information are saved to anypersistence storage.

Automatic and customized serialization can be done by using these interface.

Examples of serializable classes include Component, String, Date, Vector, and Hashtable

Page 140: PPT ERJEEML101 JavaProgramming Part 2

Java Object Serialization tools helps in achieve automatic serialization using Serializablei t f

140

interface.

Serializable is a marker interface .It has no methods within.

In order to remove a fields from serialization behavior, mark the fields using transientmodifier.

Default serialization will not serialize transient and static fields.

Page 141: PPT ERJEEML101 JavaProgramming Part 2

141

Page 142: PPT ERJEEML101 JavaProgramming Part 2

142

Page 143: PPT ERJEEML101 JavaProgramming Part 2

143

Page 144: PPT ERJEEML101 JavaProgramming Part 2

144

Page 145: PPT ERJEEML101 JavaProgramming Part 2

Here type parameter E can be instance of the class, a subclass instance or instance of a b l i l ti i t f E

145

subclass implementing interface E.

Page 146: PPT ERJEEML101 JavaProgramming Part 2

146

Page 147: PPT ERJEEML101 JavaProgramming Part 2

147

Page 148: PPT ERJEEML101 JavaProgramming Part 2

148

Page 149: PPT ERJEEML101 JavaProgramming Part 2

149

Page 150: PPT ERJEEML101 JavaProgramming Part 2

This code won’t compile because printList method expects an instance of List<Object> but t i t Li t D bl d Li t St i i t th h St i d D bl

150

we are trying to pass List<Double> and List<String> instances though String and Double are subclasses of Object.

Page 151: PPT ERJEEML101 JavaProgramming Part 2

Now the listPrint() method can accept List of any type.

151

Page 152: PPT ERJEEML101 JavaProgramming Part 2

Analyze the given example. This program will find the sum of elements in the list.

152

Problem:

Sum() method accepts list of any type. But as per the requirement it can accept only the list of type Numberic(Number and its sub types).

Page 153: PPT ERJEEML101 JavaProgramming Part 2

153

Page 154: PPT ERJEEML101 JavaProgramming Part 2

154

Page 155: PPT ERJEEML101 JavaProgramming Part 2

155

Page 156: PPT ERJEEML101 JavaProgramming Part 2

156

Page 157: PPT ERJEEML101 JavaProgramming Part 2

157

Page 158: PPT ERJEEML101 JavaProgramming Part 2

158

Page 159: PPT ERJEEML101 JavaProgramming Part 2

This code fails because at run-time

159

String listData=ls.get(0);

Becomes,

String listData=(String)ls.get(0);

Page 160: PPT ERJEEML101 JavaProgramming Part 2

160

Page 161: PPT ERJEEML101 JavaProgramming Part 2

161

Page 162: PPT ERJEEML101 JavaProgramming Part 2

162

Page 163: PPT ERJEEML101 JavaProgramming Part 2

163

Page 164: PPT ERJEEML101 JavaProgramming Part 2

•Annotations complement javadoc tags. In general, if the markup is intended to affect or produce a d t ti it h ld b j d t ti

164

documentation, it should be a javadoc or annotation .The JavadocTM tool parses the comments available in Java source files and

produces a corresponding HTML pages. It can be used to generate API documentation

Page 165: PPT ERJEEML101 JavaProgramming Part 2

165

Page 166: PPT ERJEEML101 JavaProgramming Part 2

166

Page 167: PPT ERJEEML101 JavaProgramming Part 2

The Legal Annotation Elements are

167

primitive types

Strings

enum types

Classes (not general Objects)

arrays of the above

combinations of the above

Page 168: PPT ERJEEML101 JavaProgramming Part 2

168

Page 169: PPT ERJEEML101 JavaProgramming Part 2

The pre defined Annotation types are

169

@Deprecated

@override

@SupressWarnings

@Target

@Retention

@Inherited

The last three are called as meta annotations. Since, These annotations helps to annotate the existing annotations.

Page 170: PPT ERJEEML101 JavaProgramming Part 2

170

Page 171: PPT ERJEEML101 JavaProgramming Part 2

171

Page 172: PPT ERJEEML101 JavaProgramming Part 2

172

Page 173: PPT ERJEEML101 JavaProgramming Part 2

The final of the three new annotations in J2SE 5.0, @SuppressWarnings .

173

It tells the compiler not to warn you about something that it would normally warn you about.

Warnings belong to a category, so you have to tell the annotation what types of warnings to suppress

The javac compiler defines seven options to suppress: all, deprecation, unchecked, fallthrough, path, serial, and finally. (The language specification defines only two such types: deprecation and unchecked.)

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:

Page 174: PPT ERJEEML101 JavaProgramming Part 2

Compile the class with javac. You'll see that it simply creates the .class file, and displays no warnings:

174

javac Fall.java

If you want the compiler to warn you about switch statements that fall through (that is, one or more break statements are missing), you compile with the -Xlint:fallthrough option.

Page 175: PPT ERJEEML101 JavaProgramming Part 2

@SuppressWarnings("fallthrough")

175

Compiling the class with the -Xlint:fallthrough option:

javac -Xlint:fallthrough Fall.java

will just generate the .class file and display no warnings.

@SuppressWarnings annotations can also be used to suppress other warnings such as those that would be displayed if you used a collection without specifying the data type of the collection elements.

Don't use the @SuppressWarnings annotation simply to avoid the compilation-time warning. Use it where an unchecked warning is unavoidable, such as when using a library that isn't built with generics in mind

Page 176: PPT ERJEEML101 JavaProgramming Part 2

If you want to have an annotation of specific type to a certain member type or set of member t Th d t l t f t d t t t ti t th t il

176

types.Then you need to supplysome sort of metadata to your annotation type, so that compiler can enforce that functionality.

You can use listed four predefined annotation types – known as meta-annotations -- to annotate your annotations

Read the slides

Page 177: PPT ERJEEML101 JavaProgramming Part 2

@Documented

177

Indicates that annotations with a type are to be documented by javadoc and similar tools by default.

@Inherited

It reflects that an annotation type motioned is automatically inherited .

If no superclass don’t have an annotation for this type, then this query will indicate that the class used has no such annotation.

Page 178: PPT ERJEEML101 JavaProgramming Part 2

This indicates the kinds of program parts on which this specific annotation type is applicable. In T t t t ti i t t t ti t d l ti th d l d t

178

case a Target meta-annotation is not present on an annotation type declaration, the declared type may be used on any program element. However if the case is like such a meta-annotation is present, thane the compiler has to enforce the specified restriction of usage.

Page 179: PPT ERJEEML101 JavaProgramming Part 2

Read the slides

179

Page 180: PPT ERJEEML101 JavaProgramming Part 2

Read the slides:-

180

Page 181: PPT ERJEEML101 JavaProgramming Part 2

181

Page 182: PPT ERJEEML101 JavaProgramming Part 2

Read the slides.

182

Page 183: PPT ERJEEML101 JavaProgramming Part 2

183

Page 184: PPT ERJEEML101 JavaProgramming Part 2

http://java.sun.com/javase/6/docs/technotes/guides/language/annotations.html

184

http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.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/LandersAnnotations.pdf

Page 185: PPT ERJEEML101 JavaProgramming Part 2

185