Advance Java | Preboard Solutions | 2019

5th Semester


Short Answer Questions:

  1. Define Event handling.
    Event handling is a mechanism that controls the event and decides what should happen if an event occurs.
  2. What is Java Servlet?
    Servlet is a small java program that runs within a server.Servlet receive and respond to request from web clients,usually across HTTP,the HyperText Transfer Protocol.
  3. What is JFrame?
    JFrame is a class of javax.swing package extended by java.awt.frame, it adds support for JFC/SWING component architecture. It is the top level window, with border and a title bar. JFrame class has many methods which can be used to customize it.
  4. What are the two exceptions related with Servlet?
    – ServletException
    – IOException
  5. How do you create constant variable in Java?
    Final keyword
  6. Name the event generated when the button is clicked?
  7. What is application server?
    An application server is a software framework that provides both facilities to create web applications and a server environment to run them.
  8. What is XML?
    XML schema is a language which is used for expressing constraint about XML documents.
  9. Define PreparedStatement.
    A prepared statement is a feature used to execute the same (or similar) SQLstatements repeatedly with high efficiency.
  10. What does mean by implicit object in JSP?
    JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared.

Short Answer Questions:

2.Write a program passing parameter in applet.Write complete HTML file to include applet.

3.Explain two key swing features.

Swing offers two key features:

Swing components are lightweight and don’t rely on peers. Swing supports a pluggable look and feel. The three PLAFs available to all users are Metal (default), Windows, and Motif.

4.Write a swing program demonstrating GridLayout.

5.JSP is slower than Servlet.Explain.

A Servlet is faster than a JSP.

This is because the JSP is first converted into a servlet and then processed. The processing of JSP to convert to a Servlet is extra and hence you can conclude that JSP is slower than a Servlet.

Differentiate between SAX and DOM parser.

1) DOM parser loads whole XML document in memory while SAX only loads a small part of the XML file in memory.

2) DOM parser is faster than SAX because it access whole XML document in memory.

3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn’t require much memory.

4) DOM parser works on Document Object Model while SAX is an event based XML parser.

Long Answer Questions:

7.Write a program to insert data using JDBC in MYSql database called contact_db.



Group A

Ans The two types of Applet are :
 – JApplet (Applet class of swing)
-Applet (Applet class of AWT).
Ans Event listener is the interface which is get notified after event occured if an event is registered with the listener.
 Key listener, Mouse listener, etc are some of the event listener.
Ans In AWT, a radio button is created
by grouping checkbox.
For eg: Checkbox Group cb = new Checkbox Group (); Checkbox checkbox 1 = new checkbox (Checkbox 1, cb, true);
checkbox checkbox 2 = new check box (Check box 2, cb, false);
Ans  The two swing key features are
– Swing are lightweight.
– Swing has pluggable look and feel.
Ans. The difference between Swing and AWT are:           

AWT Swing
1). It is lightweight. It is heavy weight.
2) It is platform independent.     It is platform dependent.

Ans 3 tier architecture is the architecture having 3 layers in the network. All the layers are dependent of each other.In this architecture, the presentation logic, business logic and data are logically distributed in three tiers.

vii Ans:
Steps to connect in JDBC are:

  1. Register the driver with driver manager.
  2. Obtain connection from driver.
  3. Obtain statement from connection.
  4. Run the query using statement.
  5. Close the connection

Viii. Ans:
XML is the extensible Mark up language which are used to store data in a tree like structure. XML has no pre defined tags like of HTML.XML tags are based on XML document.
For eg.
<name> ……………..root node
<fname>Java</fname>……..child node
<lname > PHP</lname>…….child node
ix. Ans:
We store data in session using setAttribute() and retrieve the data using getAttribute().
For storing data in session
session.setAttribute(“name”,new String(“JAVA”));
For retrieving session
x. Ans:
A web container is the JEE specific container that include web component.  Simply, it is the run-time environment to execute the web component.


Source Code




Group C

Ans: Delegation model is the modern approach of handling the event that defines standard and consistent mechanism to create the event and control the event.
Source Code:


Ans: Servlet is the java program that generates dynamic web pages and extends the functionality of server.

The lifecycle methods of servlet are:

  1. init()
    The init() methods run once in a servlet that initialize the servlet object and variables.
  2. service()
    The service() methods deals with dynamic request of client and generate the dynamic web pages.
  3. destroy()
    The destroy method() is used before deleting the servlet from memory.

Deployment Descriptor
Web container uses XML based file to read the information about servlet and name the file as web.xml which is known as deployment descriptor.
//Structure of Deployment Descriptor
<servlet_name> Demo</servlet_name>

St. Xaviers

Group A

  1. What are two key features of swing?
    • Swing components are lightweight and don’t rely on peers.
    • Swing supports a pluggable look and feel.
  1. Difference between listener interface and adapter class.

Listener Interface

Adapter Class

All the methods in needs to be overridden. It is ‘blank’ implementation of listener interface.
It ensures multiple inheritance for any event. It does not support multiple inheritance.


  1. What are the different places for putting event handling code?
    • Same class (by implementing listener interface in same class)
    • Inner anonymous class
    • Outer class ( by implementing listener interface in separate class)
  1. What is SQL exception?

The SQL Exception class provides information on a database access error.

  1. What are the different types of drivers used in JDBC?
    • JDBC-ODBC bridge driver,
    • Native-API driver,
    • Network Protocol driver,
    • Thin driver.
  1. What is servlet?

Servlets are the Java programs that runs on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, and then send response back to the web server.

  1. What is request dispatcher?

Request Dispatcher is an interface whose implementation defines an object which can dispatch the request to any resources on the server.

  1. What is state maintenance in servlet?

Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server.

  1. List the different jsp tag.
    • Declarative tag
      <% ! … %>
    • Directive tag
      <%@ page … %
      <%@ include … %>
      <%@ taglib … %>
    • Scriplet tag
      <%  … %>
    • Expression tag
      <%= … %>
  1. Difference between XML and HTML.

Group B

  1. Create a HTML document that contain the header information of page and include this HTML as a header file in JSP.

// index.html


<% @include file=”index.html” %>

  1. What is key event? How is it handled in java? Explain with suitable java source code.

On entering the character the Key event is generated. There are three types of key events which are represented by the integer constants. These key events are following



  1. How can you maintain session in servlet? Explain with example.

In such case, container creates a session id for each user. The container uses this id to identify the particular user. An object of HttpSession can be used to perform two tasks:

    • bind objects
    • view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.


<form action=”servlet1″>

Name:<input type=”text” name=”userName”/><br/>

<input type=”submit” value=”go”/>





  1. Write a servlet program to find the prime number between 20 and 100.
  2. Write a swing program to insert data in table using prepared statement. (You can assume your own database, table, and number of field.

Group C

  1. How exception can be handled in JSP and forward to the “error.jsp”? Explain with suitable JSP script.

There are two ways of handling exceptions in JSP. They are:

    • By errorPage and isErrorPage attributes of page directive.
    • By <error-page> element in web.xml file.


<% @page errorPage = “error.jsp” %>

< %

String num1 = request.getParameter(“first”);

String num2 = request.getParameter(“second”);

// extracting numbers from request

int x = Integer.parseInt(num1);

int y = Integer.parseInt(num2);

int z = x / y; // dividing the numbers

out.print(“division of numbers is: ” + z); // result

% >


<% @page isErrorPage = “true” %>

<h1> Exception caught</ h1>

The exception is : <%= exception %>

  1. What are the advantages of JSP over servlet? Explain the use of web.xml with example.

There are many advantages of JSP over servlet. They are as follows:

  • Extension to Servlet

JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP that makes JSP development easy.

  • Easy to maintain

JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet technology, we mix our business logic with the presentation logic.

  • Fast Development: No need to recompile and redeploy

If JSP page is modified, we don’t need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application.

  • Less code than Servlet

In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can use EL, implicit objects etc.


web.xml defines mappings between URL paths and the servlets that handle requests with those paths. The web server uses this configuration to identify the servlet to handle a given request and call the class method that corresponds to the request method. For example: the doGet() method for HTTP GET requests.










Short Question

  1. What is applet? Write down its states.

Applet are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document.

States of Applets are as follow:

    • New born State
    • Running State
    • Idle State
    • End State
  1. List any four event classes.

Any four Event classes are as follow:

    • ActionEvent
    • KeyEvent
    • MouseEvent
    • TextEvent
  1. What is prepared Statement?

The prepared Statement interface extends the Statement interface which gives you added functionality with a couple of advantages over a generic statement object. This statement gives the flexibility of supplying arguments dynamically.

  1. What is session?

Session is way to identify a user across more than one page request or visit to a web site and to store information about the user.

  1. What is servlet?

A server side Java program that uses the above API is called as Servlet. In simple terms, a Servlet is a server side Java program that processes HTTP requests and generates HTTP response.

  1. What do you mean by Adapter class?

Java provides a special feature, called an adapter class,that can simplify the creation of event handlers in certain situations. An adapter class provides an empty implementation of all methods in an event listener interface.

  1. What is XML Schema?

XML Schema overcame all the limitations of DTD and had now become the standard for validating XML documents. The good thing about XML Schema is that it is closely associated with Object Oriented data models.

  1. What is web server?

Web server is a computer where the web content is stored. Basically web server is used to host the web sites but there exists other web servers also such as gaming, storage, FTP, email etc. Web server respond to the client request in either of the following two ways:

Sending the file to the client associated with the requested URL.

    • Generating response by invoking a script and communicating with database
  1. How is JTable Created?

JTable is a component that displays rows and column of data. At its core, JTable is conceptually simple. It is a component that consists of one or more columns of information. JTable has following constructor.

JTable (Object [][] data, Object[] colHeads)

Here, data is a two- dimensional array of the information to be presented, and colHeads is a one dimensional array with the column size.

  1. Differentiate between AWT and Swing.



The components in AWT are heavyweight The components in Swing are lightweight
Associated with native components called peers Same look and feel across platforms
Same behavior, but platform dependent look Supports pluggable and feel
The package is java.awt The package is javax.swing


Group B

2. Write a swing program to compute sum, difference and product of two numbers.

3.write an applet to check whether given word by user is of length 5 or not.

The HTML file for above applet is:

4.write a JSP program to compute sum of two numbers.

5. Write a program to set cookie in servlet.
Cookie.html file

6. Write a program to read the employee(eid,name,address,salary) from file and display.

Comprehensive Questions:

  1. Differentiate between FlowLayout and BorderLayout. Make user form with two textfield and two buttons.

FlowLayout: Flow layout manager is a default layout for applet and panel.  A flow layout arranges components in a left to right, much like lines of text in a paragraph. Components are laid out from the upper left corner, left to right and top to down. When no more components fit on a line, the next one appears on next line.

BorderLayout: The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region may contain one component only. It is the default of frame or window. The four sides are referenced to as north, south, east and west. The middle area is called the center. North, south, east and west are narrow fixed width regions whereas center is large region.

  1. Write a servlet program to compute factorial of a given positive number.



Brief Answers

  1. How can you pass parameter in applet?
    • Parametersare passedto applets in NAME=VALUE pairs in <PARAM> tags between the opening and closing APPLET
  1. How can you create a dropdown list and multiple selection list in swing?
    • Dropdown list.
    • Multiple selection

  1. What are adapter classes in event handling?
  • An adapter classprovides the default implementation of all methods in an event listener interface. Adapter classesare very useful when you want to process only few of the events that are handled by a particular event listener interface.
  1. What is Exception?
  • Exception are the abnormal conditions that occur in your program during execution which terminates the program.
  1. Which class is used to browse and open file?
  • JFileChooser() and showOpenDialog() class is used to browse and open a file.
  1. Which method are used to add mnemonic and shortcuts in menu?
  • setMnemonic() method and setShortcut() methods are used to add mnemonicand shortcuts in menu.
  1. Define JDBC and ODBC.
  • JDBCstands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database.
  • ODBC is an interface that allows applications to access data in database management systems (DBMS) using SQL as a standard for accessing the data.
  1. Why swing is called light-weight components?
  • Swingcomponents depend less on the target platform and use less of the native GUI resource. Hence the Swingcomponents that don’t rely on native GUI are referred to as lightweight.
  1. What is inner class?
  • Inner classmeans one classwhich is a member of another class.
  1. Write the steps to add icon in a label in swing.
  • Create a Label say JLabel lbl.
  • Then add the label to applet or Frame.
  • Set lbl.setIcon(new ImageIcon(“images/copy.jpeg”)).

Short Answers

  1. Write a program which creates a menu (File->open, save, close) in frame.
  2. Explain the delegation event model with example.
  • Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.


  1. Create a frame which contains a swing table with some data.
  2. What do you understand by Request Dispatching? Explain with example.
  • Request Dispatcheris an interface whose implementation defines an object which can dispatch the requestto any resources on the server. javax.servlet.RequestDispatcher interface is used to forward or include the response of a resource in a Servlet.


  1. Explain component and Container with example program.
  • A componentis an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examplesof components are the buttons, checkboxes, and scrollbars of a typical graphical user interface.


  • A containeris a component which can contain other components inside itself


  1. Create an Application using swing package which will search the student in the database and display the record in the respective fields. [Database schema is as- Student (Sid, sname, address)].

  2. Create a login form (web) and validate the user from database. Assume your own database parameters.
  1. Create a Jsp simple calculator. The result should be processed by a servlet.



Short Answer Qustions

  1. Write a statement to create a JTable.

JTable jt=new JTable(data,column);

  1. Mention the use of <jsp:getProperty>.

The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.
<jsp:useBean id=”myName” … />
<jsp:getProperty name=”myName” property=”someProperty” …/>

  1. How is DTD different from XML schema?

XML schemas are written in XML while DTD are derived from SGML syntax. XML schemas define datatypes for elements and attributes while DTD doesn’t support datatypes. XML schemas allow support for namespaces while DTD does not.

  1. Which method is used to set the maximum inactive time interval for a session?


  1. List the two key features of swing.
    Swing components are lightweight.
    – Swing supports pluggable look and feel.
  2. How can you create a combo box in AWT?

By using constructor choice()
Choice c1=new Choice();

  1. How can you pass a parameter to a applet from HTML?

To pass the parameters to the Applet we need to use param attribute of <applet> tag. To retrieve a parameter’s value, we need to use getParameter() method ofApplet class.

  1. Mention any two uses of page directive in JSP.
    It is used to import the classes.
    – It is used to set the content type.
  2. What are the benefits of 3-tier architecture?
    – Enhanced scalabilitydue to distributed deployment of application servers. Now,individual connections need not be made between client and server.
    – Data Integrityis maintained. Since there is a middle layer between client and server, data corruption can be avoided/removed.
  3. List two importance of XML.
    XML stands for EXtensible Markup Language and it serves two purposes. XML is used to structure data so that it can be stored and transported. The tags provides structure to the data.

Short Answer Questions:

2.Write a program to insert 3 records into a table “book” having columns(id,name,author,publishor and price).Assume database name yourself.

3.Create a jsp that takes an integer from HTML and display its reverse.


4.Create an applet to draw a circle and a rectangle filled with different colors.

5.Create a swing program with menu bar,menu and a menu item.When menu item is clicked,display “hello” in a message dialog.

6.Create a servlet to read cookie from client and display the name and value associated with the cookie.

Long Answer Questions:

8.What is a java bean?Explain.Write a program to use java bean in jsp.

A Java Bean is a java class that should follow following conventions:

-It should have a no-argument constructor.

-It should be Serializable.

-It should provide methods to set and get the values of the properties, known as getter and                  setter methods.




Short Answer Questions:

  1. How can you prevent the user from resizing the frame at runtime?
  2. Mention the use of <jsp:setProperty> .
    The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action.
    <jsp:useBean id=”myName” … />
    <jsp:setProperty name=”myName” property=”someProperty” …/>
  3. How can you store and retrieve the data stored in session?
    Saving in Session
    String username=request.getParameter(“txtusername”);
    HttpSession session = request.getSession(true);
    session.setAttribute(“username”, username);
    Getting from Session
    String username=(String) session.getAttribute(“username”);
  4. What are the advantages of 2-tier architecture?
    • Easy to maintain and modification is bit easy.
    • Communication is faster.
  5. Mention any four event classes.
    • MouseEvent,
    • KeyEvent
    • ItemEvent
    • WindowEvent
  6. What are the two ways of creating applet?
    • By extending JApplet class.
    • By extending Applet class.
  1. List two importance of XML.
    • XML stands for EXtensible Markup Language and it serves two purposes. XML is used to structure data so that it can be stored and transported. The tags provides structure to the data.
  1. What are the parameters taken by doGet() or doPost() methods in a servlet?
    • HTTPServletRequest request,HttpServletResponse response
  2. What is the role of adapter class in event handling?
    • If a class extends an Adapter Class, we can override some methods which is needed; It can simplify the creation of the Event handlers in certain situations; It provides an empty implementation of all methods in an EventListener Methods.
  1. What is the use of DriverManager?
    • The DriverManager provides a basic service for managing a set of JDBC drivers. As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in the “jdbc.drivers” system property. This allows a user to customize the JDBC Drivers used by their applications.

Short Answer Questions

2.Create a swing program to add two numbers.

3.Write a program to update price of book to 1200 whose name is “Head First Java” into a table “book”.

4.Create an applet to draw a circle and a rectangle filled with different colors.

5.Create a jsp to find the length of given string provided from HTML.


6.Create a servlet to write cookie to user computer and store it for 24 hours.

Long Answer Questions:

  1. What is a java bean?Explain.Write a program to use java bean in jsp.

A Java Bean is a java class that should follow following conventions:
-It should have a no-argument constructor.
-It should be Serializable.
-It should provide methods to set and get the values of the properties, known as getter and                  setter methods.



Group A

  1. Define Adapter?
    • An adaperclass provides the default implementation of all methods in an event listener interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface.
  1. When will you use Result Set Class?
    • It is used when it is required to retrieve numbers of rows that satisfies the condition of the query
  1. What is Swing Class?
    • Swing class is used to create a graphical user interface.
  1. Define Applet?
    • Applet are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document.
  1. When is ActionPerformed function defined?
    • When event is called to ActionListener interface.
  1. How is database connection object created in java?
    • Connection con= new Driver manager.getconnection( jdbc:mysql\\’localhost’\’root’, ‘ ’);
  1. Which package is used to make swing object?
    • Import javax.swing.*; is used to make swing object.
  1. What is JFrame?
    • Jframe is a container that provide the drag-and-drop  features that help us in easily create graphical user-interface. JFrame has the option to hide or close the window with the help of setDefaultCloseOperation(int) method.
  1. What are the parameters taken by dopost ( ) methods of servlet?
    • HttpServletRequest & HttpServletResponse
  1. What is JSP?
    • Java Server Pages (JSP) is a Java standard technology that enables you to write dynamic, data-driven pages for your Java web applications. JSP is built on top of the Java Servlet specification.

Group B

  1. Make an user interface to take name and address of user?
  2. Make a user interface to take name and address of user?
  3. Make an applet to display name of your college?
  4. Write a jsp program to display multiplication table to 2 (from 1 To 10).

Group C

  1. Differentiate between JSP and Servlet?



A servlet is a server-side program and written purely on Java. JSP is an interface on top of Servlets. In another way, we can say that JSPs are extension of servlets to minimize the effort of developers to write User Interfaces using Java programming.
Servlets run faster than JSP JSP runs slower because it has the transition phase for converting from JSP page to a Servlet file. Once it is converted to a Servlet then it will start the compilation
Executes inside a Web server, such as Tomcat A JSP program is compiled into a Java servlet before execution. Once it is compiled into a servlet, it’s life cycle will be same as of servlet. But, JSP has it’s own API for the lifecycle.
Receives HTTP requests from users and provides HTTP responses Easier to write than servlets as it is similar to HTML.
We can not build any custom tags One of the key advantage is we can build custom tags using JSP API (there is a separate package available for writing the custom tags) which can be available as the re-usable components with lot of flexibility
Servlet has the life cycle methods init(), service() and destroy() JSP has the life cycle methods of jspInit(), _jspService() and jspDestroy()
Written in Java, with a few additional APIs specific to this kind of processing. Since it is written in Java, it follows all the Object Oriented programming techniques. JSPs can make use of the Javabeans inside the web pages
  1. Explain layout manager?
    • The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers:
    • java.awt.BorderLayout
    • java.awt.FlowLayout
    • java.awt.GridLayout
    • java.awt.CardLayout
    • java.awt.GridBagLayout
    • javax.swing.BoxLayout
    • javax.swing.GroupLayout
    • javax.swing.ScrollPaneLayout
    • javax.swing.SpringLayout, etc.


Every content pane is initialized to use a BorderLayout. (As Using Top-Level Containers explains, the content pane is the main container in all frames, applets, and dialogs.) A BorderLayoutplaces components in up to five areas: top, bottom, left, right, and center. All extra space is placed in the center area. Tool bars that are created using JToolBar must be created within a BorderLayout container, if you want to be able to drag and drop the bars away from their starting positions


The CardLayout class lets you implement an area that contains different components at different times. A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays. An alternative to using CardLayout is using a tabbed pane, which provides similar functionality but with a pre-defined GUI.


FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row, starting a new row if its container is not sufficiently wide. Both panels in CardLayoutDemo, shown previously, use FlowLayout.



Set B

Q.N. 2

Q.N. 3


Q.N. 4