0% found this document useful (0 votes)
54 views

Java Cie2 Ans Key

The document provides answers to 6 questions about Java concepts. Question 1 explains the Java collection framework with an example using an ArrayList. Question 2 discusses different iterators (Enumeration, Iterator, ListIterator) that can be used to access collection elements with an example. Question 3 provides a program to copy one file to another using the Files class. Question 4 explains the different JDBC drivers (Type 1-4). Question 5 demonstrates an Applet program and discusses the Applet lifecycle methods (init(), start(), stop(), destroy(), paint()). Question 6 explains the Servlet lifecycle in detail with the init(), service(), destroy() methods.

Uploaded by

Mohd Saif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Java Cie2 Ans Key

The document provides answers to 6 questions about Java concepts. Question 1 explains the Java collection framework with an example using an ArrayList. Question 2 discusses different iterators (Enumeration, Iterator, ListIterator) that can be used to access collection elements with an example. Question 3 provides a program to copy one file to another using the Files class. Question 4 explains the different JDBC drivers (Type 1-4). Question 5 demonstrates an Applet program and discusses the Applet lifecycle methods (init(), start(), stop(), destroy(), paint()). Question 6 explains the Servlet lifecycle in detail with the init(), service(), destroy() methods.

Uploaded by

Mohd Saif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

JAVA CIE-2 ANSWERS :

Q1) Explain the java collection frame work with an example ?


A) The Java collections framework is a set of interfaces and classes that provide a
common way to store and manipulate groups of objects. The collections framework
has the following benefits:

1. It reduces the programming effort by providing ready-made data structures


and algorithms for common tasks.

2. It increases the performance by providing efficient implementations of data


structures and algorithms.

3. It promotes reusability by allowing different types of collections to work with


the same algorithms.

4. The standard data structure in Java can be implemented in Java using some
library classes and methods. These classes are present in java.util package.

5. Collection is a group of objects which are designed to perform certain task.


These tasks are associated with data structure

Example :

// Import the List interface and the ArrayList class

import java.util.List;

import java.util.ArrayList;

// Import the Collections class for sorting

import java.util.Collections;

public class Example {

public static void main(String[] args) {

// Create a list of names using the ArrayList implementation

List<String> names = new ArrayList<>();

// Add some names to the list using the add method


names.add("Alice");

names.add("Bob");

names.add("Charlie");

names.add("David");

names.add("Eve");

// Print the list before sorting

System.out.println("List before sorting: " + names);

// Sort the list using the sort method of the Collections class

Collections.sort(names);

// Print the list after sorting

System.out.println("List after sorting: " + names);

Q2) Explain different iterators used for accessing the elements with an example?

A) Iterators are objects that allow us to traverse through a collection of elements


in a sequential manner. They provide methods to check if there are more elements,
to get the next element, and to remove the current element. There are three types of
iterators in Java:

• Enumeration: It is only used for two collections such as Vector and


Hashtable. It can only traverse in the forward direction and cannot remove
elements. It has two methods: hasMoreElements() and nextElement().

• Iterator: It can be used for any collection that implements the Collection
interface, such as List, Set, Queue, etc. It can traverse in the forward direction
and can remove elements. It has three methods: hasNext(), next(), and
remove().
• ListIterator: This is a special iterator introduced in JDK 1.2. It can only be
used for lists that implement the List interface, such as ArrayList, LinkedList,
etc. It can traverse in both forward and backward directions and can add,
remove, and modify elements. It has several methods, such as hasNext(),
add(), set(), remove(), etc.

Example :

import java.util.Iterator;

public class Example {

public static void main(String[] args) {

Iterator<Integer> it = numbers.iterator(); // create an iterator for the list

while (it.hasNext()) { // check if there is a next element

int num = it.next(); // get the next element

System.out.println(num); // print the element

Q3) Write a program to copy one program to copy one file to another ?
A) // Import the Path and Files classes
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;

// Import the StandardCopyOption enum


import java.nio.file.StandardCopyOption;
public class Example {
public static void main(String[] args) {

// Create Path objects for the source and destination files


Path source = Paths.get("source.txt");
Path destination = Paths.get("destination.txt");

// Copy the source file to the destination file, replacing it if it exists


try {
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully.");
} catch (Exception e) {
System.out.println("Failed to copy file: " + e.getMessage());
}
}
}

Q4) What is JDBC Driver ? Explain each one of them in detail.

• Java Database Connectivity (JDBC) is an Application Programming Interface


(API) used to connect Java application with Database. JDBC is used to
interact with various types of Database such as Oracle, MS Access, My SQL
and SQL Server.

• JDBC can also be defined as the platform-independent interface between a


relational database and Java Programming. It allows java program to execute
SQL statement and retrieve result from database.

• In short JDBC helps the programmers to write java applications that manage
these three programming activities: 1. Connect to a a data source, like a
database. 2. Send queries and update statements to the data base. 3.
Retrieve and process the results received from the database in answer to the
query.

• The JDBC driver manager ensures that the correct driver is used to access
each data source. The driver manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous databases.

There are 4 types of JDBC drivers:

• Type 1: JDBC-ODBC bridge driver. This driver uses the ODBC driver to connect
to the database. It converts JDBC method calls into ODBC function calls. This
driver is discouraged because of performance and compatibility issues. It is
also removed from Java 8

• Type 2: Native-API driver. This driver uses the client-side libraries of the
database. It converts JDBC method calls into native calls of the database
API. This driver is not written entirely in Java and requires installation on the
client machine2

• Type 3: Network Protocol driver. This driver uses a middleware (application


server) that converts JDBC calls into the vendor-specific database protocol.
This driver is fully written in Java and does not require installation on the
client machine. However, it requires network support and database-specific
coding on the middleware

• Type 4: Thin driver. This driver converts JDBC calls directly into the vendor-
specific database protocol. This driver is fully written in Java and does not
require any installation or configuration on the client or server side. It is the
most recommended driver for Java applications2.

Q5) Write a program to demonstrate Applet and discusses about it’s life cycle
A) Program :
import java.applet.Applet;

import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}

}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
c:\>javac First.java
c:\>appletviewer First.java

Life cycle of an Applet:


An applet is a special type of program embedded in the web page to generate
dynamic content. Applet is a class in Java.

init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization.
start(): The start() method contains the actual code of the applet and starts the
applet. It is invoked immediately after the init() method is invoked. Every time the
browser is loaded or refreshed, the start() method is invoked
stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked.
destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the webpage
is closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.

Q6) Explain the Life cycle of servlet in detail.


A) The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage it.

Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four
stages,
Loading a Servlet.
Initializing the Servlet.
Request handling.
Destroying the Servlet.
The following figure depicts a typical servlet life-cycle scenario.
The servlet is initialized by calling the init() method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
The init method is called only once. It is called only when the servlet is created, and
not called for any user requests afterwards. So, it is used for one-time initializations,
just as with the init method of applets.
public void init() throws ServletException {
// Initialization code...
}

The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming
from the client( browsers) and to write the formatted response back to the client.
A GET request results from a normal request for a URL or from an HTML form that
has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The destroy() method is called only once at the end of the life cycle of a servlet.
After the destroy() method is called, the servlet object is marked for garbage
collection.
public void destroy() {
// Finalization code...
}

Q7) Write a program to demonstrate JLabel, JTextField, JcheckBok with ImageIcon.


A) import javax.swing.*;
import java.awt.*;

public class GUIExample {


public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("GUI Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
// Create a JPanel
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 1));

// Create a JLabel
JLabel label = new JLabel("Enter your name:");
panel.add(label);

// Create a JTextField
JTextField textField = new JTextField(20);
panel.add(textField);

// Create a JCheckBox with an ImageIcon


ImageIcon icon = new ImageIcon("path/to/image.png"); // Replace with the
actual path to your image file
JCheckBox checkBox = new JCheckBox("Check me", icon);
panel.add(checkBox);

// Add the panel to the frame


frame.add(panel);

// Set the frame to be visible


frame.setVisible(true);
}
}

Q14) Discuss about handling HTTP requests and responses in servlet.


A) ServletRequest: This ServletRequest interface in which examining the methods
for all objects as encapsulating data information about its all requests i.e. made to
the servers, this object of the ServletRequest interface is used to retrieve the
information data from the user.
ServletResponse: An interface examining the methods for all objects which are
returning their allowed responses from the servers and object of this current
interfacing objects is used to estimate the response to the end-user on the system.
Let's discuss the process of handling HTTP requests and responses in a servlet:
1. Servlet Lifecycle: When a client makes an HTTP request to a servlet, the
servlet container (e.g., Apache Tomcat) creates an instance of the servlet and
invokes its methods to handle the request and response. The key methods
involved in this lifecycle are init(), service(), and destroy().

2. doGet() and doPost(): These are the most commonly used methods for
handling HTTP requests in a servlet. The doGet() method is invoked for HTTP
GET requests, while doPost() is invoked for HTTP POST requests. You can
override these methods in your servlet to process the incoming requests.

3. Request Parameters: Servlets can access request parameters sent by the


client. For GET requests, the parameters are usually included in the URL query
string, while for POST requests, they are sent as part of the request body. You
can use methods like getParameter() to retrieve individual parameters or
getParameterMap() to retrieve all parameters.

4. Request Headers: Servlets can access various request headers sent by the
client, such as User-Agent, Referer, Cookie, etc. These headers provide
additional information about the client or the request itself. You can use
methods like getHeader() or getHeaders() to retrieve specific headers or
iterate over all headers.

5. Request Attributes: Servlets can set and retrieve request attributes. Request
attributes are objects that are specific to a particular request and can be
accessed by other servlets or JSPs involved in processing the request.
Request attributes are useful for passing data between components during
request processing.

6. HTTP Response: Servlets generate HTTP responses to send back to the


client. You can set response headers using methods like setHeader() or
addHeader(). The servlet can also set the response content type using
setContentType() to specify the format of the response data, such as text,
HTML, JSON, etc.

7. Response Output: Servlets can use the getOutputStream() or getWriter()


methods to obtain an output stream or writer, respectively, to write the
response content. You can write plain text, HTML markup, or any other format
as required.

You might also like