78
CS606 – JAVA PROGRAMMING LAB Ex. No. : 1 Title: Study of Simple Java Program Using Threading. Date : 01-08- 11 Aim : To write a program for thread concept using java. Objective : 1. To understand the concept of thread in java program. 2. To demonstrate how to create a thread using java program. 3. To appreciate each thread’s priority. 4. To identify the status of each thread during program execution. Pre lab : The procedure for creating threads based on the Runnable interface is as follows: 1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object. 2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method. 3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned. Page No: 1

Java Lab Programs

Embed Size (px)

Citation preview

Page 1: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Ex. No. : 1 Title: Study of Simple Java Program Using Threading.

Date : 01-08-11

Aim : To write a program for thread concept using java.

Objective :

1. To understand the concept of thread in java program.

2. To demonstrate how to create a thread using java program.

3. To appreciate each thread’s priority.

4. To identify the status of each thread during program execution.

Pre lab :

The procedure for creating threads based on the Runnable interface is as follows:

1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.

2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.

3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.

4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.

Syntax:

The Runnable Interface Signature

public interface Runnable

{

void run();

}

Page No: 1

Page 2: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Problem Description:

Audio clips are relatively easy to use in an applet. I created an AudioClip object using the applet getAudioClip() method, giving it the URL of the sound file located on the server. The clip can then be played using that object's play() or loop() methods. The buttons are initially disabled. When the corresponding sound clip, loading in a separate thread, finishes downloading, the button is enabled.

Pseudo Code:

1. Import Applet & AWT Packages into the program.2. Create a class and inherit applet class, and also implement an interface called runnable.3. Create an Audio clip variable & initialize a playing state variable as ‘stopped’ as false.4. Initialize the init() method4.1 Using getAudioClip() method - get the audio file.4.2 If audiofile !=NULL then

Create a thread and start a thread.5. In start() method

stopped:=false;6. In Stop() method

Stopped:=false;7. In run() method7.1 Set priority of a current thread as minimum.7.2 Using while if its true

If !stopped thenPlay an audio file.

7.3 Using try and catch statement Using sleep() method, it should sleep every 5secs of the audio file.

Test Case:

Since it’s a user level thread, in program itself we will give the resources such as audio file and thread execution.

.

Page No: 2

Page 3: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Coding:

import java.applet.*;import java.awt.*;import java.net.*;

/* <applet code="ex01.class" width=400 height=500> <param name="audio" value="beep.au"> </applet>*/public class ex01 extends Applet implements Runnable{ private AudioClip beep; private boolean stopped=false; public void init() { beep=this.getAudioClip(this.getDocumentBase(), this.getParameter("audio")); if(beep!= null) { Thread t=new Thread(this); t.start(); } } public void start() { this.stopped=false; } public void stop() { this.stopped=false; } public void run() { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while(true) { if(!stopped)

beep.play(); try { Thread.sleep(5000); } catch(InterruptedException e){ } } }}

Page No: 3

Page 4: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Output:

D:\java\java lab>javac ex01.java

D:\java\java lab>appletviewer ex01.java

Result:

Thus the program for simple thread using java is done & output is verified.

Page No: 4

Page 5: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

THREADING

Review Questions:

1. How to create a thread?In the most general sense, you create a thread by instantiating an object of type

Thread. Java defines two ways in which this can be accomplished.

You can implement the Runnable Interface You can extend the Thread class itself.

2. What is threaded programming and when it is used?

Threaded programming is normally used when a program is required to do more than one task at the same time. Threading is often used in applications with graphical user interfaces; a new thread may be created to do some processor-intensive work while the main thread keeps the interface responsive to human interaction.

The Java programming language has threaded programming facilities built in, so it is relatively easy to create threaded programs. However, multi-threaded programs introduce a degree of complexity that is not justified for most simple command line applications.

3. Differentiate thread’s start() and run() methods.

The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

The Thread class' run() method calls the run() method of the Runnable type class passed to its constructor. Subclasses of Thread should override the run() method with their own code to execute in the second thread.

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method. Howevever, the code will only be executed in a new thread if the start() method is used.

4. Can a class have more than one thread?

Any Java class may be loaded and instantiated as part of a multi-threaded program. Since Java is fundamentally a multi-threaded programming language all classes

Page No: 5

Page 6: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

should be designed with this possibility in mind, with a judgment whether it is likely and what its consequences would be.

You should normally have enough information to judge whether your own classes are likely to be used in a multi-threaded context. If there is the no immediate requirement, avoid thread-proofing your class until that time comes.

The Java API is used for general programming purposes that cannot be anticipated in advance, so thread safety considerations are usually noted in classes' API documentation. Many data storage and management classes in the java.util package are distinguished by their thread safety status because safety is usually a trade-off against the time-performance of key operations.

5. Why not override Thread to make a Runnable?

There is little difference in the work required to override the Thread class compared with implementing the Runnable interface, both require the body of the run() method to be implemented. However, it is much simpler to make an existing class hierarchy runnable because any class can be adapted to implement the run() method. A subclass of Thread cannot extend any other type, so application-specific code would have to be added to it rather than inherited.

Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed.

6. What are the ways to determine whether a thread has finished?

isAlive – Determine if the thread is still running.

join – Wait for a thread to terminate.

Page No: 6

Page 7: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Ex. No. : 2 Title: Create a Simple Application using Applet.

Date : 08-08-11

Aim : To write a program for Applet using Java.

Objective :

1. To understand the need of an Applet in java program.

2. To demonstrate the life cycle of an Applet.

3. To recognize how to develop an Applet

4. To comprehend how to deploy the Applet.

Pre lab :

A Java applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of the java.applet.Applet class. The Applet class provides the standard interface between the applet and the browser environment.

Syntax:

/*

<applet code =”MyApplet” width=200 height=60>

</applet>

*/

This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high.

Page No: 7

Page 8: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Problem Description:

Ultimate aim to play a audio file by click on a play button. The sound can be shut off with a call to stop() or once it time will be over.

Pseudo Code:

1. Import Applet & AWT Packages into the program.2. Create a class and inherit Applet class.3. Create a button as ‘b’4. Initialize the init() method4.1. Set the bound for ‘b’ to place a button in an applet.4.2. Add the button in an applet.5. Create an action () method with parameter ‘e’ as Event.5.1 if e.target():=b then

Get the Audio URL & Play it.5.2 if not Print Error Message.

Test Case:

Sl # Test Case Code

Test Case Description Expected Result

Actual Result

Pass / Fail

1. TC01 If the user clicks out of play button in an applet

window

It won’t play an

audio file

Not played Pass

2. TC02 If the user exactly clicks on play button.

It will play an audio file

from the given audio

URL.

Played at given audio

URL.

Pass

3. TC03 If given URL is not valid It will play an audio just gives a error

message

Empty Applet Screen.

Fail

Page No: 8

Page 9: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Coding:

import java.applet.*;import java.net.*;import java.awt.*;

/* <applet code="ex02.class" width=400 height=500> <param name="audio" value="beep.au"> </applet>*/

public class ex02 extends Applet{ Button b=new Button("PLAY"); public void init() { b.setBounds(10,10,10,10); add(b); } public boolean action(Event e,Object o) { if(e.target==b) { try { URL u=new URL(this.getCodeBase(), this.getParameter("audio")); this.play(u); } catch(MalformedURLException me) { System.err.println("\n MalFormed URL Exception" +me); } return true; } return false; }}

Page No: 9

Page 10: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Output:

D:\java\java lab>javac ex02.java

D:\java\java lab>appletviewer ex02.java

Result:

Thus the simple program for applet using java is done & output is verified.

Page No: 10

Page 11: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

APPLET

Review Questions:

1. Which classes can an applet extend?

An applet can extend the java.applet.Applet class or the java.swing.JApplet class. The java.applet.Applet class extends the java.awt.Panel class and enables you to use the GUI tools in the AWT package. The java.swing.JApplet class is a subclass of java.applet.Applet that also enables you to use the Swing GUI tools.

2. For what do you use the start() method?

You use the start() method when the applet must perform a task after it is initialized, before receiving user input. The start() method either performs the applet's work or (more likely) starts up one or more threads to perform the work.

3. True or false: An applet can make network connections to any host on the Internet.

False: An applet can only connect to the host that it came from.

4. How do you get the value of a parameter specified in the JNLP file from within the applet's code?

You use the getParameter("Parameter name") method, which returns the String value of the parameter.

5. Which class enables applets to interact with JavaScript code in the applet's web page?

The netscape.javascript.JSObject class enables applets to interact with JavaScript code in the applet's web page.

6. True or False: Applets can modify the contents of the parent web page.

True:Applets can modify the contents of the parent web page by using the getDocument method of the com.sun.java.browser.plugin2.DOM class and the Common DOM API.

Page No: 11

Page 12: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Ex. No. : 3 Title: Create a Simple Application using UDP and TCP Sockets.

Date : 29.08.11

Aim : To write a program for UDP & TCP using java.

Objective :

1. To know what is a socket in Java Program.

2. To demonstrate reading from and writing to a Socket.

3. To understand writing a Client/Server pair.

4. To know how to close the streams and sockets.

Pre lab :

Syntax:

1. Socket(String hostname, int port)

Creates a socket connecting the local host to the named host and port; can throw an UnknownHostException or an IOException.

2. Socket(InetAddress ipAddress, int port)

Creates a socket using a preexisting InetAddress object and a port; can throw an IOException.

3. InetAddress getInetAddress()

Returns the InetAddress associated with the Socket object.

4. InputStream getInputStream()

Returns the InputStream associated with the invoking socket.

5. OutputStream getOutputStream()

Returns the OutputStream associated with the invoking socket.

Page No: 12

Page 13: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Transmission Control Protocol

Problem Description:

TCP (Transmission Control Protocol), which provides a reliable, connection-oriented service to the invoking application. It offers several additional services to applications, it provides reliable data transfer. TCP ensures that data is delivered from sending process to receiving process correctly and in order. TCP thus converts IP’s unreliable service between end systems into a reliable data transport service between processes.

Pseudo Code:

Client Side:

1. Import network package.2. Create a class and throws Exception in main function.3. CreateSocket method and initialize an object (cilentSocket).4. Using While loop do the protocol procedure.

4a. Initialize “FromServer” & “ ToServer” variable using BufferedReader class.4b. Initialize “outToClient” variable using PrintWriter class.

5. Get the transactions information using the sockets.6. Until type “q” transaction proceeds.

6a. If input is “q” it ends/quit using close() method.

Server Side:

1. Import network package.2. Create a class and throws Exception in main function.3. Create ServerSocket method and initialize an object (Server).4. Using While loop do the protocol procedure.

4a. Accept the server object through Socket method via connected object.4b. Get the Internet Address using getPort() method.4c. Initialize “inFromUser” & “ inFromClient” variable using BufferedReader class.4d. Initialize “outToClient” variable using PrintWriter class.

5. Get the transactions information using the sockets.6. Until type “q” transaction proceeds.

6a. If input is “q” it ends/quit, using close() method.

Page No: 13

Page 14: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Test Case:

Sl # Test Case Code

Test Case Description Expected Result

Actual Result

Pass / Fail

1. TC01 When some characters to be sent

Sent without any loss

To be sent as it is.

Pass

2. TC02 When some numbers to be sent

Sent without any data

loss

To be sent as it is.

Pass

3. TC03 When the client wants to quit by typing “q”.

Closed Closed Pass

Page No: 14

Page 15: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Coding://ts.javaimport java.io.*;import java.net.*;class ts{ public static void main(String argv[]) throws Exception { String fromclient; String toclient; ServerSocket Server = new ServerSocket (5000); System.out.println ("TCPServer Waiting for client on port 5000"); while(true) { Socket connected = Server.accept(); System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED "); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); BufferedReader inFromClient = new BufferedReader(new InputStreamReader

(connected.getInputStream())); PrintWriter outToClient = new PrintWriter(connected.getOutputStream(),true); while ( true ) { System.out.println("SEND(Type q to Quit):"); toclient = inFromUser.readLine(); if ( toclient.equals ("q") ) { outToClient.println(toclient); connected.close(); break; } else { outToClient.println(toclient); fromclient = inFromClient.readLine(); if ( fromclient.equals("q") ) { connected.close(); break; } else System.out.println( "RECIEVED:" + fromclient ); } } } } }

Page No: 15

Page 16: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

//tc.java

import java.io.*;import java.net.*;

class tc{ public static void main(String argv[]) throws Exception { String FromServer; String ToServer; Socket clientSocket = new Socket("localhost", 5000); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(),true); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); while (true) { FromServer = inFromServer.readLine(); if ( FromServer.equals("q") || FromServer.equals("Q")) { clientSocket.close(); break; } else { System.out.println("Received: " +FromServer); System.out.println("SEND(Type q to Quit):"); ToServer = inFromUser.readLine(); if (ToServer.equals("q")) { outToServer.println (ToServer) ; clientSocket.close(); break; } else outToServer.println(ToServer); } } }}

Page No: 16

Page 17: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Output:

Client System

D:\java\java lab>javac tc.java

D:\java\java lab>java tc

Received: hi

SEND(Type q to Quit):

hello

Received: hw r u?

SEND(Type q to Quit):

am 5n :)

Received: hw do u do?

SEND(Type q to Quit):

okay ll catch u later! bye

D:\java\java lab>

Server System

D:\java>javac ts.java

D:\java>java ts

TCPServer Waiting for client on port 5000

THE CLIENT /127.0.0.1:49182 IS CONNECTED

SEND(Type q to Quit):

hi

RECIEVED:hello

SEND(Type q to Quit):

Page No: 17

Page 18: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

hw r u?

RECIEVED:am 5n :)

SEND(Type q to Quit):

hw do u do?

RECIEVED:okay ll catch u later! bye

SEND(Type q to Quit): q

D:\java\java lab>

Page No: 18

Page 19: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

User Datagram Protocol (UDP)

Problem Description:

UDP (User Datagram Protocol), which provides an unreliable, connectionless service to the invoking application. How might you go about doing this? sending side, you might consider using a vacuous transport protocol. In particular, on the sending side, you might consider taking the messages from the application process and passing them directly to the network layer; and on the receiving side, you might consider taking the messages arriving from the network layer and passing them directly to the application process.

Pseudo Code:

Client Side:

1. Import network package.2. Create a class and throws IOException in main function.3. Initialize required variables.4. Initialize DatagramSocket with the client port and initialize an object (cilentsocket).5. Get the local host name using “ia” variable.6. Using While loop do the protocol procedure.

6a. Get the data interms of bytes.6b. If data will be “bye” then quit it using close() method.6c. If data is not “bye” then clientsocket.send(new DatagramPacket(buffer,length of the string to be send, internet

address ,server port));7. Receive the server information through receive() method.

Server Side:

1. Import network package.2. Create a class and throws Exception in main function.3. Initialize required variables.4. Initialize DatagramSocket with the server port and initialize an object (serversocket).5. Get the local host name using “ia” variable.6. Receive the client information through receive() method.7. Using While loop do the protocol procedure.

7a. Get the data interms of bytes.7b. If data will be “bye” then quit it using close() method.7c. If data is not “bye” then serversocket.send(new DatagramPacket(buffer,length of the string to be send, internet address ,client port));

Page No: 19

Page 20: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Test Case:

Sl # Test Case Code

Test Case Description Expected Result

Actual Result

Pass / Fail

1. TC01 When some characters to be sent

Sent without any loss

To be sent as it is.

Pass

2. TC02 When some numbers to be sent

Sent without any data

loss

To be sent as it is.

Pass

3. TC03 When the client wants to quit by typing “bye”.

Closed Closed Pass

Page No: 20

Page 21: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Coding:

//UDPClient

import java.io.*;

import java.net.*;

class UDPClient

{

public static DatagramSocket clientsocket;

public static DatagramPacket dp;

public static BufferedReader dis;

public static InetAddress ia;

public static byte buf[]=new byte[1024];

public static int cport=789,sport=790;

public static void main(String a[]) throws IOException

{

clientsocket=new DatagramSocket(cport);

dp=new DatagramPacket(buf,buf.length);

dis=new BufferedReader(new InputStreamReader(System.in));

ia=InetAddress.getLocalHost();

System.out.println("Client is Running.... Type 'STOP' to Quit");

while(true)

{

String str=new String(dis.readLine());

buf=str.getBytes();

if(str.equals("bye"))

{

System.out.println("Terminated...");

clientsocket.send(new DatagramPacket(buf,str.length(),ia,sport));

break;

}

clientsocket.send(new DatagramPacket(buf,str.length(),ia,sport));

Page No: 21

Page 22: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

clientsocket.receive(dp);

String str2=new String(dp.getData(),0,dp.getLength());

System.out.println("Server: "+str2);

}

}

}

//UDPServer.java

import java.io.*;

import java.net.*;

class UDPServer

{

public static DatagramSocket serversocket;

public static DatagramPacket dp;

public static BufferedReader dis;

public static InetAddress ia;

public static byte buf[]=new byte[1024];

public static int cport=789, sport=790;

public static void main(String a[]) throws IOException

{

serversocket=new DatagramSocket(sport);

dp=new DatagramPacket(buf,buf.length);

dis=new BufferedReader(new InputStreamReader(System.in));

ia=InetAddress.getLocalHost();

System.out.println("Server is Running....");

while(true)

{

serversocket.receive(dp);

String str=new String(dp.getData(),0, dp.getLength());

if(str.equals("bye"))

Page No: 22

Page 23: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

{

System.out.println("Terminated...");

break;

}

System.out.println("Client: "+str);

String str1=new String(dis.readLine());

buf=str1.getBytes();

serversocket.send(new DatagramPacket(buf,str1.length(),ia,cport));

}

}

}

Page No: 23

Page 24: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Output:

Server Side

D:\java\java lab>javac UDPServer.java

D:\java\java lab>java UDPServer

Server is Running....

Client: hi deepu hw r u?

am dng gr8 argata, den wassup?

Client: nothing spl here, over thr?

no dude, shall v go muttukadu dis sunday?

Client: okay nice, ll go dakshinachitra also wat do u say?

okay no prob at al, den?

Client: okay ll catch u later,

okay bye

Terminated...

D:\java\java lab>

Client Side:

D:\java\java lab>javac UDPClient.java

D:\java\java lab>java UDPClient

Client is Running.... Type 'bye' to Quit

hi deepu hw r u?

Server: am dng gr8 argata, den wassup?

nothing spl here, over thr?

Page No: 24

Page 25: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Server: no dude, shall v go muttukadu dis sunday?

okay nice, ll go dakshinachitra also wat do u say?

Server: okay no prob at al, den?

okay ll catch u later,

Server: okay bye

bye

Terminated...

D:\java\java lab>

Result:

Thus the program for Transmission Control Protocol & User Datagram Protocol using

Java is done & output is verified.

Page No: 25

Page 26: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

UDP AND TCP SOCKETS

Review Questions:

1. What does a socket consists of ?

The combination of an IP address and a port number is called a socket.

2. Differentiate TCP and UDP?

TCP and UDP are both transport-level protocols. TCP is designed to provide reliable communication across a variety of reliable and unreliable networks and internets. UDP provides a connectionless service for application-level procedures. Thus, UDP is basically an unreliable service; delivery and duplicate protection are not guaranteed.

3. How do you make a connection to a URL?.

URLConnection openConnection()

It returns a URLConnection object associated with the invoking URL object. It may throws an IOException.

3. Should I use ServerSocket or DatagramSocket in my applications?

DatagramSocket allows a server to accept UDP packets, whereas ServerSocket allows an application to accept TCP connections. It depends on the protocol we're trying to implement. If we're creating a new protocol.

DatagramSockets communciate using UDP packets. These pacur kets don't guarantee delivery - we'll need to handle missing packets in our client/server.

ServerSockets communicate using TCP connections. TCP guarantees delivery, so all we need to do is have our applications read and write using a socket's InputStream and OutputStream.

5. How do I perform a hostname lookup for an IP address.

InetAddress getAddress() – Returns the destination InetAddress, typically used for sending.

7. True or False: Applet can connect via Sockets and can bind to a local port.

True – Applet can connect via sockets and can bind to a local port.

Page No: 26

Page 27: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Ex. No. : 4 Title: Implement the Concept of Java Message Services

Date : 05-09-11

Aim : To write a program for Java Messaging Services.

Objective :

1. To understand what is a Messaging System.

2. To demonstrate types of Messaging Services.

3. To create a connection to the messaging system provider.

4. To create sessions, for sending and receiving messages.

Pre lab :

Syntax:

A TextMessage wraps a simple String object. This is useful in situations where only strings are being passed.

Creation of a TextMessage object is simple, as these two lines of code indicate:

TextMessage message =

session.createMessage();

message.setText("hello world");

An ObjectMessage, as its name implies, is a message wrapping a Java object. Any serializable Java object can be used as an ObjectMessage.

This is how an Object message is created:

ObjectMessage message = session.createObjectMessage();

message.setObject(myObject);

Page No: 27

Page 28: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Problem Description:

Java Messaging System is incorporate both SMTP (Simple Mail Transfer Protocol) and POP3 (Post Office Protocol Version 3). Here SMTP will be performed over here. SMTP gets the sender and receiver address then transfers the content given by sender to receiver.

Pseudo Code:

Client Side:

1. Import network package.2. Create a class and throws IOException in main function.3. Initialize required variables.4. Initialize Socket with the client port and initialize an object (s).5. Using while loop do the protocol procedure.

Server Side:

1. Import network package.2. Create a class and throws IOException in main function.3. Initialize required variables.4. Initialize DatagramSocket with the server port and initialize an object (serversocket).5. Using while loop do the protocol procedure..

Test Case:

Sl # Test Case Code

Test Case Description Expected Result

Actual Result

Pass / Fail

1. TC01 When some characters to be sent

Sent without any loss

To be sent as it is.

Pass

2. TC02 When some numbers to be sent

Sent without any data

loss

To be sent as it is.

Pass

Page No: 28

Page 29: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Coding:

//SMTPClient.package SMTPcli;

import java.io.*;import java.net.*;public class SMTPcli{public static void main(String arg[])throws IOException{Socket s=new Socket("localhost",8080);DataInputStream m=new DataInputStream(System.in);DataInputStream n=new DataInputStream(System.in);PrintStream p=new PrintStream(s.getOutputStream());p.println("ready");System.out.println("Enter from address:");String str=m.readLine();p.println(str);System.out.println("Enter to address:");String str1=n.readLine();p.println(str1);System.out.println("Enter the message");while(true){String cmd=m.readLine();p.println(cmd);if(cmd.equals("send")){System.out.println("Client message has been sent");break;}}}}

Page No: 29

Page 30: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

//SMTPServer

package SMTPser;

import java.io.*;import java.net.*;import java.util.*;public class SMTPser{public static void main(String arg[])throws IOException{ServerSocket ss=new ServerSocket(8080);Socket s=ss.accept();ServerClient(s);}public static void ServerClient(Socket s)throws IOException{DataInputStream ds=null;PrintStream ps=null;ds=new DataInputStream(s.getInputStream());ps=new PrintStream(s.getOutputStream());FileWriter f=new FileWriter("abcEmail.doc");FileInputStream f1;String tel=ds.readLine();if(tel.equals("ready")){System.out.println("Ready signal received:ClIENT ACCEPTED");System.out.println("From address");String from=ds.readLine();System.out.println(from);f.write("FROM"+from+"\n");System.out.println("To address");String to=ds.readLine();System.out.println(to);f.write("TO:"+to+"\n");System.out.println("Client Msg");f.write("message");while(true){String cmd=ds.readLine();

Page No: 30

Page 31: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

if(cmd.equals("send")){cmd="SERVER message received";System.out.println(cmd);break;}f.write("\n");System.out.println(cmd);f.write(cmd+"\n");}f.close();}}}

Page No: 31

Page 32: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Output:

Result: Thus the program for Java Messaging System (SMTP) is done & output is verified.

JAVA MESSAGE SERVICES

Page No: 32

Page 33: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Review Questions:

1. What is JMS?

Java Messaging System is used mail services through SMTP and POP3.

2. Differentiate Byte Message and Stream Message.

A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual physical devices to which they are linked differ.

Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data.

3. Can you remember the three components of a message?

Sender, Intermediate Buffer & Receiver.

4. Does Tomcat support JMS (Java Messaging Service)?

Yes, its support for Messaging System.

5. True or False: JMS can support e-mail operations.

True, it handles such a protocol to function messaging system.

Ex. No. : 5 Title: Create a Simple Application using Swing.

Page No: 33

Page 34: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Date : 26-09-11

Aim : To write a program for swing using java.

Objective :

1. To understand the concept of Swing in Java.

2. To know about “Java Foundation Classes”.

3. To comprehend the Swing Class Hierarchy.

4. To demonstrate the different Swing components.

Pre lab : Swing labels are instances of the JLabel class which extends JComponent: It can display text and/or an icon.

Syntax: Some of the Swing label constructors are mentioned below:

JLabel(Icon i)

JLabel(String s)

JLabel(String s, Icon I, int align).

Here, s and i are the text and icon used for the label. The align argument is either LEFT, RIGHT, CENTER, LEADING, or TRAILING.

Listeners register and un-register for these events via the methods shown here:

void addActionListener(ActionListener al)

void removeActionListener(ActionListener al)

Here, al is the action listener.

Problem Description: Page No: 34

Page 35: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Swing is implementing for Look & Feel interface, basically java will not give such an impact on user interface level. Hence Swing is introducing for such sort of problem. “javax.swing.*” is an advance enhanced for Look & Feel point of view.

Pseudo Code:

1. Import the “javax.swing” package.

2. Create a Button and provide the URL for the image to be display.

3. Create an Exit Button and if its clicks then window will be close.

4. Using actionperfomed method to get the action.

4a. if user clicks the Button then it could display image on the give space.

Test Case:

Sl No Test Case Code

Test Case Description Expected Result

Actual Result Pass / Fail

1. TCO1 If “Click Here” to be Click

Displayed Image

Image Displayed Pass

2. TC02 If Clicks “Exit” Button Close the window

Window Closed Pass

Coding:

Page No: 35

Page 36: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

package image;

import java.awt.Color;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;public class image implements ActionListener { public JLabel l1=new JLabel("SWING CONCEPT"); public JButton b1=new JButton("Click Here"); ImageIcon someIcon = new ImageIcon("D:/fagneesh.jpg"); public JButton b2= new JButton(); public JButton EXIT=new JButton("EXIT"); public JFrame f1; public Container c; image() { f1=new JFrame("SWING"); c=f1.getContentPane(); c.setLayout(null); f1.setSize(500, 500); f1.show(); l1.setBounds(200,35,100,50); b1.setBounds(200,85,100,50); b2.setBounds(200,185,200,140); EXIT.setBounds(210,385,80,50); l1.setForeground(Color.BLUE); b1.setForeground(Color.MAGENTA); c.add(l1); c.add(b1); c.add(b2); c.add(EXIT); b1.addActionListener(this); b2.addActionListener(this); EXIT.addActionListener(this); }

Page No: 36

Page 37: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { b2.setIcon(someIcon); f1.setTitle("CRESCENT"); } if (e.getSource()== EXIT) { System.exit(0); } } public static void main(String args[]) { new image(); }}

Output:

Page No: 37

Page 38: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Result:

Thus the program for Swing using java is done & output is verified.

SWING

Review Questions:

Page No: 38

Page 39: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

1. What is a swing?

Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT.

2. Name a few Container classes.

Applet provides all necessary support for applet execution.

Applet extends a AWT class Panel, in turn Panel extends Container which extends Component. The Container class is a subclass of Component. The Panel class is a concrete class of container.

4. Can you run Swing under a browser?

No, its only for application purpose.

5. Differentiate a Window and a Frame.

The Window class creates a top- level window. A top-level window is not contained within any other object; it sits directly on the desktop.

Frame encapsulates what is commonly thought of as a “window”. It is a subclass of Window. If you create a Frame object from within an applet, it will contain a warning message, such as “Java Applet Window”.

6. What is the difference between Swing and AWT components?

Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT.

AWT is a base of swing.

Ex. No. : 6 Title: Remote Method Invocation

Page No: 39

Page 40: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Date :

Aim : To write a program for Remote Method Invocation.

Objective :

1. To understand the concept of Remote Method Invocation (RMI) in Java.

2. To know how to build distributed applications.

3. To comprehend RMI way of communication between client and server.

4. To locate remote objects.

Pre lab : To know about serialization in java. All remote interfaces must extend the Remote interface, which is part of java.rmi.

Syntax: All remote methods can throw a Remote Exception

Import java.rmi.*;

Public interface AddServerIntf extends Remote

{

Double add(double d1, double d2) throws RemoteException;

}

Problem Description:

Page No: 40

Page 41: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Remote method invocation allows applications to call object methods located remotely, sharing resources and processing load across systems. Unlike other systems for remote execution which require that only simple data types or defined structures be passed to and from methods, RMI allows any Java object type to be used - even if the client or server has never encountered it before. RMI allows both client and server to dynamically load new object types as required. In this article, you'll learn more about RMI.

Pseudo Code:

1. Create a Client program which request to their interface. 2. Create a Server program which implements the request from interface.

3. Stub interface (used by the client so that it knows what functions it can access on the server side)

4. Skeleton interface (used by the server as the interface to the stub on the client side)

5. The information flows as follows: the client talks to the stub, the stub talks to the skeleton and the skeleton talks to the server.

Test Case:

Sl No Test Case Code

Test Case Description Expected Result

Actual Result Pass / Fail

1. TC01 If the registry is properly registered.

Connection Established

Connection Established

Pass

2. TC02 If the stub is not created Throws an Exception in Client side.

Throws an Exception in Client side.

Pass

3. TC03 If the skeleton is not created

Throws an Exception in Server side.

Throws an Exception in server side.

Pass

Coding:

//ReceiveMessageInterface.java

Page No: 41

Page 42: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

import java.rmi.*;public interface ReceiveMessageInterface extends Remote{ void receiveMessage(String x) throws RemoteException;}

//RmiServer.java

import java.rmi.*;import java.rmi.registry.*;import java.rmi.server.*;import java.net.*; public class RmiServer extends java.rmi.server.UnicastRemoteObjectimplements ReceiveMessageInterface{ int thisPort; String thisAddress; Registry registry; public void receiveMessage(String x) throws RemoteException { System.out.println(x); } public RmiServer() throws RemoteException { try { thisAddress= (InetAddress.getLocalHost()).toString(); } catch(Exception e) { throw new RemoteException("can't get inet address."); } thisPort=3232; System.out.println("this address="+thisAddress+",port="+thisPort); try { registry = LocateRegistry.createRegistry( thisPort ); registry.rebind("rmiServer", this); }

Page No: 42

Page 43: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

catch(RemoteException e) { throw e; } } static public void main(String args[]) { try { RmiServer s=new RmiServer(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }

//RmiClient.java

import java.rmi.*;import java.rmi.registry.*;import java.net.*;

public class RmiClient{ static public void main(String args[]) { ReceiveMessageInterface rmiServer; Registry registry; String serverAddress=args[0]; String serverPort=args[1]; String text=args[2]; System.out.println("sending "+text+" to "+serverAddress+":"+serverPort); try { registry=LocateRegistry.getRegistry(serverAddress,(new Integer(serverPort)).intValue()); rmiServer=(ReceiveMessageInterface)(registry.lookup("rmiServer")); rmiServer.receiveMessage(text);

Page No: 43

Page 44: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

} catch(RemoteException e) { e.printStackTrace(); } catch(NotBoundException e) { e.printStackTrace(); } }}

Output:

Server side:

C:\Program Files\Java\jdk1.6.0_23\bin>javac RmiServer.java Page No: 44

Page 45: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

C:\Program Files\Java\jdk1.6.0_23\bin>rmic RmiServer

C:\Program Files\Java\jdk1.6.0_23\bin>java RmiServer

this address=admin/192.168.1.2,port=3232

crescent

Client side

C:\Program Files\Java\jdk1.6.0_23\bin>javac RmiClient.java

C:\Program Files\Java\jdk1.6.0_23\bin>java RmiClient 192.168.1.2 3232 crescent

sending crescent to 192.168.1.2:3232

Result:

Thus the program Remote Method Invocation (RMI) using java is done and output is verified.

REMOTE METHOD INVOCATION

Review Questions:

1. What is the functionality UnicastRemoteObject?

Page No: 45

Page 46: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

UnicastRemoteObject which provides functionality that is needed to make objects available from remote machine.

2. Does RMI require use of an HTTP server?

No, it allows a java object that executes on one machine to invoke a method of a java object that executes on other machine.

2. How will you create Client Program?

Stub interface (used by the client so that it knows what functions it can access on the server side)

Ex. No. : 7 Title: JavaScript

Date : 15-10-11

Page No: 46

Page 47: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Aim : To write a program for JavaScript using HTML.

Objective :

1. To understand the concept JavaScript.

2. To know the different data types, variables, and operators.

3. To comprehend how to interact with the users.

4. To work with forms and objects.

Prelab:

Simple recursive function example:

function factorial(n) {

if (n == 0) {

return 1;

}

return n * factorial(n - 1);

}

Problem Description:

Script will trigger a small set of segment/function as to give an effective operation along with the web application. Here scripting will use for validating the field and ease to avoid some sort of redundancy & to sustain the consistency level.

Page No: 47

Page 48: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Pseudo Code:

1. Create a main page for authentication.

2. Get the username and password & validate using javascript.

3. If given data is correct and continue with the test else say “Login Failed”

4. In test module, using radio button get the answer for the given question.

5. And Compute at last for the set questions and print the total score using javascript.

Test Case:

Sl No Test Case Code

Test Case Description Expected Result

Actual Result

Pass / Fail

1. TC01 On Authentication if given input is proper.

It transfers to Test Page

Displayed a Test Page

Pass

2 TC02 On Authentication if given input is not proper.

It gives error

message

Login Failed, Message will be Displayed

Pass

3 TC03 Total Score based scripting routine.

Gives a Total Score

Total Score is displayed

Pass

Coding:

//login.htm

<html>

<head>

Page No: 48

Page 49: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>LOGIN</title>

</head>

<body>

<HR>

<p align="center"> <font color="#0000FF" size="6">

AUTHENTICATION ENTRY </font> </p>

<hr>

<form>

<center>

<p align="center">

CRESCENT ID &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="text" name="t1" id="name"> <br><br>

CRESCENT PWD &nbsp;&nbsp;&nbsp;

<input type="password" name="t2" id="pass"> <br><br>

</p>

<p align="center">

<input type="button" value="login" onclick="login();">

</p>

</center>

</form>

</body>

<script type="text/javascript">

function login()

{

x=document.getElementById("name");

y=document.getElementById("pass");

if(x.value=="a" && y.value=="a")

{

window.open("test.html");

window.close("login.html");

}

Page No: 49

Page 50: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

else if(x.value==" " && y.value==" ")

{

alert("enter your name and password ");

}

else

alert("incorrect entrty");

}

</script>

</html>

// test.htm

<html>

<title> Aptitude test </title>

<body bgcolor="green">

<hr>

<p align="center"> <font color="#0000FF" size="6">Test Session</font>

</p>

<hr>

<form>

<center>

<input type="radio" name="radio1" id="radio1"> English Section &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="radio" name="radio1" id="radio2"> Mathematics Section <br><br>

<input type="button" value="GO" onclick="go();">

</center>

</form>

</body>

<script type="text/javascript">

function go()

{

if(document.getElementById("radio1").checked==true)

Page No: 50

Page 51: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

{

window.open("english.html");

}

if(document.getElementById("radio2").checked==true)

{

window.open("maths.html");

}

}

</script>

</html>

//English.htm

<html>

<title> English Cognitive Section </title>

<body bgcolor="tan">

<p align="center">

<font color="#0000FF" size="6"> English Section <font>

</p>

<form>

<br> &nbsp;&nbsp;&nbsp;&nbsp;

1. Nonversation? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="radio" name="radio10" id="radio1"> Meaningful Conversation &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="radio" name="radio10" id="radio2"> Meaningless Conversation <br><br><br>

&nbsp;&nbsp;&nbsp;&nbsp;

2. Reprimand? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="radio" name="radio11" id="radio3"> Express Strong Disapproval &nbsp;&nbsp;

<input type="radio" name="radio11" id="radio4"> Express Strong Approval <br><br>

<center> <input type="button" value="SUBMIT" name="b1" onclick="validate();"> </center>

</form>

</body>

Page No: 51

Page 52: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

<script type="text/javascript">

function validate()

{

var a=0;

if(document.getElementById("radio2").checked==true)

a=a+1;

if(document.getElementById("radio3").checked==true)

a=a+1;

total=a;

prec=total*100/2;

if(a==1) alert("yor score : 1 out of 2");

else if(a==2) alert("yor score 2 out of 2");

else if(a==0) alert("yor score 0 out of 2");

}

</script>

</html>

//maths.htm

<html>

<title> Maths Section </title>

<body bgcolor="tan">

<p align="center">

<font color="#0000FF" size="6"> Mathematics Section

</font></p>

<form>

<br><br> &nbsp;&nbsp;&nbsp;&nbsp;

1. sin(cos(tan(45))) in degree mode? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="radio" name="radio10" id="radio1"> 0.01744 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="radio" name="radio10" id="radio2"> 0.17449 <br><br>&nbsp;&nbsp;&nbsp;&nbsp;

Page No: 52

Page 53: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

2. ln(log(45)) ? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="radio" name="radio11" id="radio3"> 0.7098 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="radio" name="radio11" id="radio4"> 0.5027 <br><br>

<center>

<input type="button" value="SUBMIT" name="b1" onclick="validate();"></center>

</form>

</body>

<script type="text/javascript">

function validate()

{

var a=0;

if(document.getElementById("radio2").checked==true)

a=a+1;

if(document.getElementById("radio4").checked==true)

a=a+1;

if(a==1) alert("yor score : 1 out of 2");

else if(a==2) alert("yor score 2 out of 2");

else if(a==0) alert("yor score 0 out of 2");

}

</script>

</html>

Output:

Page No: 53

Page 54: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Page No: 54

Page 55: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Page No: 55

Page 56: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Result:

Thus the program for javascript is done & output is verified.

JAVASCRIPT

Page No: 56

Page 57: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Review Questions:

1. What is the general structure of an HTML document?

<html>

<body> statement to be execute </body>

</html>

2. Is it possible to incorporate a JavaScript in an XML document?

Yes, it’s a possible to incorporate a JavaScript in an XML Document.

3. How about 2+5+"8"?

2+5+”8” = 78

4. What are objects in JavaScript?

JavaScript objects store their properties in an internal table that can access in two ways.

1st way - using object name property name.

2nd way- using array which enables to access all an objects properties in sequence.

Another way - Associative Array associative a left and a right side element, value of right side can be used by specifying the value of left side as index.

Eg: document[Href] - > this is used to access the href property of document object.

5. Give the difference between Java and JavaScript.

Java is an application language, which as its own independent code.

JavaScript enables to embed commands in a HTML tags.

JavaScript enables web authors to write small scripts that executes on the user’s browsers rather on the server.

Ex. No. : 8 Title: Application Program Using JDBC Page No: 57

Page 58: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Date : 31-10-11

Aim : To write a program for Java Database Connectivity.

Objective :

1. To know the concept the JDBC

2. To understand the components of JDBC.

3. To demonstrate a JDBC connection.

4. To comprehend JDBC drivers..

Pre lab :

For Setting a Driver:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

For Connection Establishment:

Connection con=DriverManager.getConnection("jdbc:odbc:test"); For Statement Exection:

Statement s=con.createStatement(); For initializing a result set:

ResultSet rset=s.getResultSet();

Page No: 58

Page 59: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Problem Description:

The Java Database Connectivity will place a role to get a value in run time and store in database. Here we get a set of data to be stored in MS-Access. Connectivity ensures the stability through Open Database Connectivity with Driver Manager.

Pseudo Code:

1. Import “sql” packages into the program.2. Create a class and execute a statement through try – catch statement.3. Using try get the Driver Name.4. Create an object for Connection class and provided give the database name.5. Create an object for Statement class and create a statement through connection.6. Execute a Query.7. Create an object for result set, through the statement object; initialize the result set. 8. Using while get the sequence of result.9. If any exception gives through catch statement.10. Finally print “execution completed!”

Test Case:

Sl No. Test Case Code

Test Case Description` Expected Result

Actual Result Pass / Fail

1. TC01 If the fields items are properly given

Properly Stored Stored in corresponding

fields

Pass

2. TC02 If the Driver Manger could not properly links

Display an error message

Throws an Exception

Pass

Page No: 59

Page 60: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Coding:

package javap;

import java.sql.*;

public class javap { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:test"); Statement s=con.createStatement(); s.executeQuery("SELECT *FROM products"); ResultSet rset=s.getResultSet(); while(rset.next()) { System.out.println(rset.getString("ProductName")); System.out.println(rset.getString("ProductPrice")); } } catch(Exception e) { System.out.println(); } finally { System.out.println("*** CHOCLATE STORE ***"); } }}

Page No: 60

Page 61: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

Database:

Output:

Result:

Thus the program for JDBC using java & MS-Access is done & output is verified.

Page No: 61

Page 62: Java Lab Programs

CS606 – JAVA PROGRAMMING LAB

JDBC – Java Database Connectivity

Review Questions:

1. What are the steps involved in establishing a JDBC connection?

a. Open or establish a connection to the database

b. Execute a SQL statement.

c. Process the result.

d. Close the connection to the database.

2. How can you load the drivers?

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

DriverManager.getConnection("jdbc:odbc:test");

3. What will Class.forName do while loading drivers?

Loading the JDBC driver is very simple using a static method called forName which belongs to the class Class. This method creates an instance of the driver and registers it with the DriverManager.

4. How can you make the connection?

Connection con = DriverManager.getConnection("jdbc:odbc:test");

5. What does setAutoCommit do?

If all transaction would have finished successfully, this command will execute.

6. What are callable statements?

If some of the query to be executed then callable statement will provide such a environment.

Page No: 62