Advanced Java Programming 2069
Section A
Attempt any Two questions. (2x10=20)
1. What are exceptions? Why is it important to handle exceptions? Discuss different keywords that are used to handle exception. (2+2+6)
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message.
Java exception handling is important because it helps maintain the normal, desired flow of the program even when unexpected events occur. If Java exceptions are not handled, programs may crash or requests may fail. Suppose there are 10 statements in a program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling.
Java provides five keywords that are used to handle the exception.
1. try: The "try" keyword is used to specify a block where an exception can occur. It is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must be followed by catch blocks or finally block or both.
2. Catch: The "catch" block is used to handle the exception. This block must follow the try block and a single try block can have several catch blocks associated with it. When an exception occurs in a try block, the corresponding catch block that handles that particular exception executes. It can be followed by finally block later.
3. Finally: A finally block contains all the crucial statements that must be executed whether an exception occurs or not. The statements present in this block will always execute, regardless an exception occurs in the try block or not such as closing a connection, stream etc.
4. throw: The "throw" keyword is used to throw an exception.
5. throws: The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
Example:
class TestExceptions {
static void myMethod(int testnum) throws Exception {
System.out.println ("start - myMethod");
if (testnum == 12)
throw new Exception();
System.out.println("end - myMethod");
return;
}
public static void main(String args[]) {
int testnum = 12;
try {
System.out.println("try - first statement");
myMethod(testnum);
System.out.println("try - last statement");
}
catch ( Exception ex) {
System.out.println("An Exception");
}
finally {
System. out. println( "finally") ;
}
System.out.println("Out of try/catch/finally - statement");
}
}
Output:
try - first statement
start - myMethod
An Exception
finally
Out of try/catch/finally - statement
2. Write a program using swing components to add two numbers. Use text fields for inputs and output. Your program should display the result when the user presses a button. (10)
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Addition extends JFrame implements ActionListener //implement listener interface
{
JLabel l1, l2;
JTextField t1, t2, t3;
JButton b1;
public Addition()
{
l1 = new JLabel("First Number:");
l1.setBounds(20, 10, 100, 20); //x, y, width, height
t1 = new JTextField(10);
t1.setBounds(120, 10, 100, 20);
l2 = new JLabel("Second Number:");
l2.setBounds(20, 40, 100, 20);
t2 = new JTextField(10);
t2.setBounds(120, 40, 100, 20);
b1 = new JButton("Sum");
b1.setBounds(20, 70, 80, 20);
t3 = new JTextField(10);
t3.setBounds(120, 70, 100, 120);
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(t3);
b1.addActionListener(this); //Registering event
setSize(400,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) //Handle Event
{
if(e.getSource()==b1){
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int sum = num1 + num2;
t3.setText(String.valueOf(sum));
}
public static void main(String args[])
{
new Addition();
}
}
3. What is java beans? Differentiate it with java class. Discuss bean writing process with suitable examples. (2+2+6)
Section B
Attempt any Eight questions. (8x5=40)
4. Discuss the use of interfaces to achieve multiple inheritance. (5)
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces. An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.
Multiple inheritance can be achieved with interfaces, because the class can implement multiple interfaces. To implement multiple interfaces, separate them with a comma.
In the following example Class Animal is derived from interface AnimalEat and AnimalTravel.
interface AnimalEat { void eat(); } interface AnimalTravel { void travel(); } class Animal implements AnimalEat, AnimalTravel { public void eat() { System.out.println("Animal is eating"); } public void travel() { System.out.println("Animal is travelling"); } }
5. Discuss the use of multithreading with suitable example. (5)
The process of executing multiple threads simultaneously is known as multithreading. The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread.
Example:
Program to create two threads. The first thread
should print numbers from 1 to 10 at intervals of 0.5 second and the second
thread should print numbers from 11 to 20 at the interval of 1 second.
class First extends Thread
{
@Override
public void run()
{
for (int i=1; i<=10; i++)
{
System.out.println(i);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
class Second extends Thread
{
@Override
public void run()
{
for (int i=11; i<=20; i++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
public class ThreadInterval
{
public static void main(String[] args)
{
Thread first = new First();
Thread second= new Second();
first.start();
second.start();
}
}
6. What is JDBC? How do you execute SQL statements in JDBC? (2+3)
Java Database Connectivity (JDBC) is an Application Programming Interface (API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. It allows java program to execute SQL statement and retrieve result from database.
The following steps are involved in executing SQL statements in JDBC:
1. Load
the JDBC driver.
2. Specify
the name and location (given as a URL) of the database being used.
3. Connect
to the database with a Connection object.
4. Execute
a SQL query using a Statement object.
5. Get the results in a ResultSet object.
6. Finish by closing the ResultSet, Statement and Connection objects.
Example:
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.ResultSet;
import
java.sql.SQLException;
import
java.sql.Statement;
public class
Simplejdbc{
public
static void main( String args[] ) {
try{
//Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//
Establish a connection
String url = "jdbc:mysql//localhost/test";
Connection conn = DriverManager.getConnection(url);
//Create a statement
Statement st =
conn.createStatement();
//Execute a statement
ResultSet rs = st.executeQuery("SELECT * FROM Employee");
while(rs.next()){
int id =
rs.getInt("E_ID");
String
name = rs.getString("E_Name");
String
address = rs.getString("E_Address");
Date
d = rs.getDate("DOB");
System.out.println(id+"\\t"+name+"\\t"+address+"\\t"+d);
}
st.close();
conn.close();
}catch
(SQLException sqlExcep){
System.out.println("Error:
" + sqlExcep.getMessage());
}
}
}
7. Discuss grid layout with suitable example. (5)
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. Components are placed in columns and rows.
Every Component in a GridLayout has the same width and height. Components are added to a GridLayout starting at the top-left cell of the grid and proceeding left to right until the row is full. Then the process continues left to right on the next row of the grid, and so on.
GridLayout Constructors:
GridLayout() | creates a grid layout with one column per component in a row. |
GridLayout(int rows, int cols) | creates a grid layout with the given rows and columns but no gaps between the components. |
GridLayout(int rows, int cols, int int hgap, int vgap) | creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps. |
Example:
import java.awt.*;
import javax.swing.*;
public class GridDemo
{
JButton b1, b2, b3, b4, b5, b6;
GridDemo()
{
JFrame f = new JFrame("GridLayoutDemo");
b1 = new JButton("A");
b2 = new JButton("B");
b3 = new JButton("C");
b4 = new JButton("D");
b5 = new JButton("E");
b6 = new JButton("F");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.setLayout(new GridLayout(2, 3));
f.setSize(200, 200);
f.setVisible(true);
}
public static void main(String args[])
{
new GridDemo();
}
}
8. Discuss any five classes to handle files in java. (5)
9. What is JSP? Differentiate it with servlet. (2+3)
Java Server Pages (JSP) is server side technology to create dynamic java web application. It allows
java programming code to be embedded in the HTML pages.
-
Scripting elements are used to provide
dynamic pages.
- JSP simply puts Java inside HTML pages.
Servlets |
JSP |
Servlet is a pure java code. |
JSP is a tag based approach. |
We write HTML in servlet code. |
We write JSP code in HTML. |
Servlet is faster than JSP. |
JSP is slower than servlet
because it first translate into java code then compile. |
Writing
code for servlet is harder than JSP as it is html in java. |
JSP
is easy to code as it is java in html. |
Servlet
can accept all protocol requests. |
JSP
only accept http requests. |
Modification
in Servlet is a time consuming task because it includes reloading,
recompiling and restarting the server. |
JSP
modification is fast, just need to click the refresh button. (reloading,
recompilation and restart the server is not required) |
Servlets do not have implicit
objects. |
JSP does have implicit objects. |
In
Servlet, we can override the service() method. |
In
JSP, we cannot override its service() method. |
In MVC pattern, servlet act as a
controller. |
In MVC, JSP act as a view. |
In Servlet, by default session
management is not enabled we need to enable explicitly. |
In JSP, session management is
automatically enabled. |
Packages are to be imported at
the top of the servlet. |
Packages can be imported anywhere
in the JSP code. |
10. What is UDP socket? Differentiate it with TCP socket. (2+3)
Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data. Java supports stream sockets and datagram sockets.
Datagram sockets use UDP (User Datagram Protocol) for data transport, thus they are also called UDP sockets. Stream sockets use TCP (Transmission Control Protocol) for data transport, thus they are also called TCP sockets. Since TCP can detect lost transports and resubmit them, the transports are lossless and reliable. UDP, in contrast, cannot guarantee lossless transport and so is unreliable.
TCP | UDP |
TCP is a connection oriented protocol. | UDP is a connectionless oriented protocol. |
TCP assure reliable delivery of data to the destination. | UDP does not assure reliable delivery of data to the destination. |
TCP provides extensive error checking mechanisms such as flow control and acknowledgement of data. | UDP does not provides error checking mechanisms such as flow control and acknowledgement of data. |
Delivery of data is guaranteed if you are using TCP. | Delivery of data is not guaranteed if you are using UDP. |
TCP is comparatively slow because of these extensive error checking mechanism. | UDP makes fast and best effort service to transmit data. |
Retransmission of lost packets is possible. | There is no retransmission of lost packets in UDP. |
The Java code to perform client-server communication using UDP sockets is given below:
//UDPClient.java
import java.net.*;
import java.io.*;
public class UDPClient
{
public static void main (String[] args)
{
try
{
DatagramSocket socket = new DatagramSocket ();
byte[] buf = new byte[256]; //Byte array to store information
String messg = "Hello UDP Server\\n";
buf = messg.getBytes (); //Getting the size of message
InetAddress address = InetAddress.getByName ("127.0.0.1");
DatagramPacket packet = new DatagramPacket (buf, buf.length, address, 1234);
socket.send(packet); // Sends datagram packet, packet
}
catch (IOException e)
{
}
}
}
//UDPServer.java
import java.net.*;
import java.io.*;
public class UDPServer
{
public static void main (String[] args)
{
try
{
DatagramSocket socket = new DatagramSocket (1234);
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket (buf, buf.length);
socket.receive (packet);
String received = new String (packet.getData());
System.out.println ("Received packet: " + received);
}
catch (IOException e)
{
}
}
}
11. How can you handle events using adapter classes? Discuss. (5)
12. What is RMI? Discuss architecture of RMI in detail. (1+4)
Remote Method Invocation (RMI) is a mechanism that allows an object running in
one java virtual machine (JVM) to invoke methods on an object running in
another java virtual machine (JVM). It
Architecture of RMI
In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides on the client).
- Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry).
- The client program requests the remote objects on the server and tries to invoke its methods.
The RMI architecture consists of four layers:
1. Application Layer:
This layer is the actual systems i.e. client and
server which are involved in communication. The java program on the client side
communicates with the java program on the server-side.
2. Proxy Layer: This layer contains the client stub and server skeleton objects.
- Stub is an object that resides on the client machine and it acts as a proxy for the remote object. It is like a gateway for the client program. When the client calls on the stub object, the stub forwards this request to a remote object (Skeleton) via RMI infrastructure which is then executed on the server.
- The server object which resides in a server machine is known as Skeleton. Stub communicates with server application with the help of an intermediate Skeleton object. The responsibility of the skeleton object is to send parameters to method implementation and send the return values back to the client.
3. Remote Reference Layer: This layer is responsible to maintain the session during the method call. i.e. It manages the references made by the client to the remote server object. This layer is also responsible for handling duplicated objects. The invocation semantics of the RMI connection is defined and supported by this layer.
4. Transport Layer: The
transport layer is responsible for setting up communication between the two
machines. This layer uses standard TCP/IP protocol for
connection. The actual transportation of data is performed through this layer.
13. Write a simple JSP program to display “Kathmandu, Nepal” 10 times. (5)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=“Content-Type”
content=“text/htm; charset=UTF-8”>
<title> JSP program to display “Kathmandu,
Nepal” 10 times</title>
</head>
<body>
<h1> Displaying “Kathmandu,
Nepal” 10 times!!</h1>
<table>
<%
for(int i=1; i<=10; i++){
%>
<tr><td> Kathmandu, Nepal</td></tr>
<% } %>
</table>
</body>
</html>