Advanced Java Programming 2076
Attempt any two questions. (2x10=20)
1. What is exception handling? Discuss the use of each keyword (try, catch, throw, throws and finally) with suitable Java program.
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.
Exception handling is a powerful mechanism or technique that allows us to handle runtime errors in a program so that the normal flow of the program can be maintained. 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 Java program to find the sum of two numbers using swing components. Use text fields for input and output. Your program displays output if you press any key in keyboard. Use key adapter to handle events.
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Addition
{
JLabel l1, l2, l3;
JTextField t1, t2, t3;
JFrame f = new JFrame();
Addition()
{
l1 = new JLabel("First Number:");
t1 = new JTextField();
l2 = new JLabel("Second Number:");
t2 = new JTextField();
l3 = new JLabel("Press any key");
t3 = new JTextField();
t3.addkeyListener(new keychecker());
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(l3);
f.add(t3);
f.setSize(250,150);
f.setLayout(new GridLayout(3,2));
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
}
class keychecker extends KeyAdapter{
public void keyPressed(KeyEvent e)
{
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int sum = num1 + num2;
JOptionPane.showMessageDialog(f, "The sum is" +sum);
t3.setText(null);
}
public static void main(String args[])
{
new Addition();
}
}
3. Define servlet. Discuss life cycle of servlet. Differentiate servlet with JSP. Write a simple JSP file to display 'IOST' 20 times.
A servlet is a small java program that executes on the server-side of web connection and dynamically extends the functionality of a web server. Servlet technology is used to create Dynamic web application.
In the life cycle of servlet there are three important methods. These methods are: init(), service() and destroy().
init():
- The server invokes the init( ) method of the servlet. This method is invoked only when the servlet is loaded in the memory for the first time. It is possible to pass initialization parameters to the servlet so it may configure itself.
service():
- The service() method is the main method to perform the actual task.
- The web server calls the service() method to handle requests coming from the client/browsers and to write the response back to the client (to process the HTTP rerquest). The service() method is called for each HTTP request.
destroy():
- Finally server unloads the servlet from the memory using the destroy() method to clean any resources.
- The destroy() method is called only once at the end of the life cycle of a servlet.
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. |
Program
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=“Content-Type” content=“text/htm; charset=UTF-8”>
<title> JSP program to display “IOST” 20 times</title>
</head>
<body>
<h1> Displaying “IOST” 20 times!!</h1>
<table>
<%
for(int i=1; i<=20; i++){
%>
<tr><td> IOST </td></tr>
<% } %>
</table>
</body>
</html>
Group B
Attempt any eight questions. (8x5=40)
4. Define class. How do you create a class in Java? Differentiate class with interface.
A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.
To create a class, use the keyword class.
Syntax:
Class vs Interface
5. Write a simple Java program that reads a file named "Test.txt" and displays its contents.
import
java.io.FileReader;
import
java.io.IOException;
public
class FileReaderDemo {
public static void main(String[] args) {
try {
FileReader fr = new
FileReader("Test.txt");
int c;
while ((c = fr.read()) != -1) {
System.out.print((char) c);
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
6. Why do we need layout management? What is GridBag layout?
The layout management is used to arrange components in a particular manner. The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
GridBagLayout is one of
the most flexible — and complex — layout managers the Java platform provides. A
GridBagLayout places components in a grid of rows and columns, allowing
specified components to span multiple rows or columns. Not all rows necessarily
have the same height.Similarly, not all columns necessarily have the same
width. Essentially, GridBagLayout places components in rectangles (cells) in a
grid, and then uses the components' preferred sizes to determine how big the
cells should be. The way the program specifies the size and position
characteristics of its components is by specifying constraints for each
component using GridBagConstraints object, as demonstrated below:
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
7. Discuss MVC design pattern with example.
MVC design pattern is also known as Model-View-Controller. It is a common architectural pattern which is used to design and create interfaces and the structure of an application. This pattern divides the application into three parts that are dependent and connected to each other.
1. Model: The Model contains only the pure application data. It doesn’t contain any information on how to show the data to the user. It is independent of the user interface. It controls the logic and rules of application.
2. View: The View presents the model’s
data to the user. The view knows how to access the model’s data, but it does
not know what this data means or what the user can do to manipulate it.
3. Controller: The
Controller acts as an interface between View and Model. It receives the
user requests and processes them, including the necessary validations. The
requests are then sent to model for data processing. Once they are processed,
the data is again sent back to the controller and then displayed on the
view.
8. What are the benefits of using JDBC? What is prepared statement?
Benefits of using JDBC:
- JDBC
enables enterprise applications to continue using existing data even if the
data is stored on different database management systems.
- The
combination of the java API and the JDBC API makes the databases transferable
from one vendor to another without modifications in the application code.
- JDBC is usually used to connect a user application to a ‘behind the scenes’ database, no matter of what database management software is used to control the database. In this function, JDBC is cross-platform or platform independent.
- With JDBC, the complexity of connecting a user program to a ‘behind the scenes’ database is hidden, and makes it easy to deploy and economical to maintain.
Prepared Statement
Prepared Statement is
used to execute parameterized or dynamic SQL queries.
E.g. of parameterized query:
String sql="insert into emp values(?,?,?)";
As we
can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.
It is preferred when a particular query is to be executed multiple times. We can pass the parameters to SQL query at run time using this interface.
The
prepareStatement() method of Connection interface is used to return the
object of PreparedStatement.
PreparedStatement pstmt = conn.prepareStatement(queryString);
Example:
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101); //1 specifies the first parameter in the query
stmt.setString(2,"Ramesh");
int i=stmt.executeUpdate();
System.out.println("No. of rows updated="+i);
con.close();
}catch(Exception e){
System.out.println(e);
}
}
}
9. Write Java programs using TCP sockets that communicate with each other in a computer network.
//Server.java
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("SERVER:......\\n");
ServerSocket s = new ServerSocket(95);
System.out.println("Server Waiting For The Client");
Socket cs=s.accept();
System.out.println("Client connected”);
BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream()));
PrintWriter out=new PrintWriter(cs.getOutputStream(),true);
while(true)
{
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
System.out.print("To Client:");
String tocl=din.readLine();
out.println(tocl);
String st=in.readLine();
if(st.equalsIgnoreCase("Bye")||st==null)break;
System.out.println("From Client:"+st);
}
in.close();
out.close();
cs.close();
}
catch(IOException e) { }
}
}
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("CLIENT:......\\n");
Socket con=new Socket("localhost", 95);
BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
PrintWriter out=new PrintWriter(con.getOutputStream(),true);
while(true)
{
String s1=in.readLine();
System.out.println("From Server:"+s1);
System.out.print("Enter the messages to the server:");
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
String st=din.readLine();
out.println(st);
if(st.equalsIgnoreCase("Bye")||st==null)break;
}
in.close();
out.close();
con.close();
}
catch(UnknownHostException e){ }
}
}
10. Define Java Bean. How is it different from other Java programs? What is design pattern?
11. How do you handle HTTP request (GET) using servlet?
Handling HTTP GET
requests involves overriding the doGet
method.
The following example shows the use of HTTP GET method.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType(“text/html”);
PrintWriter pw = res.getWriter();
pw.println("<html>");
pw.println("<head>");
pw.println(“<title>HW</title>”);
pw.println("</head>");
pw.println("<body>");
pw.println("<h2>Hello World!</h2>");
pw.println("</body>");
pw.println("</html>");
pw.close();
}
}
12. What are different layers of RMI architecture? Explain.
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 short notes on:
- Servlet API
- RMI vs CORBA
Servlet API
Two packages javax.servlet and javax.servlet.http contains the classes and interfaces that are required to build servlet. These two packages constitute the servlet API and these are not part of the core packages. Therefore they are not included in Java Software Development Kit (JSDK).
- The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.
Interfaces defined in javax.servlet package: Servlet, ServletConfig, ServletContext, ServletRequest, ServletResponse
Classes in javax.servlet packages: GenericServlet, ServletInputStream, ServletOutputStream, ServletException
- The javax.servlet.http package contains a number of interfaces and classes that are commonly used by servlet developers. Its functionality is to make easy to build servlets that work with HTTP requests and responses.
Interfaces used in javax.servlet.http package: HttpServletRequest, HttpServletResponse, HttpSession
Classes used in javax.servlet.http package: Cookie, HttpServlet
RMI vs CORBA
RMI | CORBA |
RMI is a Java-specific technology. | CORBA is independent of programming languages. It Can access foreign language objects. |
It uses Java interface for implementation. | It uses Interface Definition Language (IDL) to separate interface from implementation. |
RMI programs can download new classes from remote JVMs. | CORBA doesn't have this code sharing mechanism. |
RMI passes objects by remote reference or by value. | CORBA passes objects by reference. |
RMI uses the Java Remote Method Protocol as its underlying remoting protocol. | CORBA use Internet Inter- ORB Protocol (IIOP) as its underlying remoting protocol. |
The responsibility of locating an object implementation falls on JVM. | The responsibility of locating an object implementation falls on Object Adapter either Basic Object Adapter or Portable Object Adapter. |
Distributed garbage collection is available integrated with local collectors. | No distributed garbage collection is available |
Generally simpler to use. | More complicated. |
It is free of cost. | Cost money according to the vendor. |
| CORBA has better scalability. |