You are on page 1of 19

SECTION A

a. What is bytecode?
Bytecode is program code that has been compiled from source code into low-level code
designed for a software interpreter. It may be executed by a virtual machine (such as a JVM)
or further compiled into machine code, which is recognized by the processor. A popular
example is Java bytecode, which is compiled from Java source code and can be run on a Java
Virtual Machine (JVM). Below are examples of Java bytecode instructions.
b. Define constructor.
A constructor is a special method that is used to initialize a newly created object and is
called just after the memory is allocated for the object. It can be used to initialize the objects
to desired values or default values at the time of object creation. It is not mandatory for the
coder to write a constructor for a class.If no user-defined constructor is provided for a class,
compiler initializes member variables to its default values.

c. What is a Instance Variable?


Instance variable in Java is used by Objects to store their states. Variables which are
defined without the STATIC keyword and are Outside any method declaration are
Object specific and are known as instance variables. They are called so because their
values are instance specific and are not shared among instances. Rules for Instance
variable in Java-
 Instance variables can use any of the four access levels.
 They can be marked final
 They can be marked transient
 They cannot be marked abstract
 They cannot be marked synchronized
 They cannot be marked strictfp
 They cannot be marked native
 They cannot be marked static

d. When is it appropriate to use frames?


Frames can make navigating a site much easier. If the main links to the site are located
in a frame that appears at the top or along the edge of the browser, the content for those
links can be displayed in the remainder of the browser window.
e. What is the use of alternative text in mage mapping?
The alt attribute specifies an alternate text for an area, if the image cannot be
displayed.The alt attribute provides alternative information for an image if a user for
some reason cannot view it (because of slow connection, an error in the src attribute, or
if the user uses a screen reader).The alt attribute is required if the href attribute is
present.
<!DOCTYPE html>
<html>
<body>
<p>Click on the sun or on one of the planets to watch it closer:</p>
<img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.htm">
<area shape="circle" coords="90,58,3" alt="Mercury" href="mercur.htm">
<area shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>
</body>
</html>

f. What are the two major protocols for accessing email from servers?
Post Office Protocol version 3 (POP3) is a standard mail protocol used to receive
emails from a remote server to a local email client. POP3 allows you to download email
messages on your local computer and read them even when you are offline.
The Internet Message Access Protocol (IMAP) is a mail protocol used for accessing email on
a remote web server from a local client. IMAP and POP3 are the two most commonly used
Internet mail protocols for retrieving emails. Both protocols are supported by all modern
email clients and web servers.
Simple Mail Transfer Protocol (SMTP) is the standard protocol for sending emails across the
Internet.
g. What do you mean by Checked Exceptions?
A checked exception is a type of exception that must be either caught or declared in the
method in which it is thrown. For example, the java.io.IOException is a checked exception.

SECTION B
a. Create an html page named as “Table.html” to display your class time table.
1) Provide the title as Time Table.
2) Provide various color options to the cells (Highlight the lab hours and elective hours, with
different colors.)
b. Compare Java and JavaScript. Write a JavaScript program to define a user defined function
for sorting the values in an array.
Ans:

JAVA JAVASCRIPT

Java is strongly typed language and

variable must be declare first to use in

program.In Java the type of a variable is JavaScript is weakly typed language and

checked at compile-time. have more relaxed syntax and rules.


JAVA JAVASCRIPT

Java is an object oriented programming JavaScript is an object based scripting

language. language.

Java applications can run in any virtual JavaScript code run on browser only as

machine(JVM) or browser. JavaScript is developed for browser only.

Objects of Java are class based even we

can’t make any program in java without

creating a class. JavaScript Objects are prototype based.

Java program has file extension “.Java” JavaScript file has file extension “.js” and

and translates source code into bytecodes it is interpreted but not compiled,every

which is executed by JVM(Java Virtual browser has the Javascript interpreter to

Machine). execute JS code.

contained within a web page and

Java is a Standalone laguage. integrates with its HTML content.

JavaScript requires less memory therefore

Java program uses more memory. it is used in web pages.

Java has a thread based approach to Javascript has event based approach to

concurrency. concurrency.

c. What is the difference applet and application? How is Java strongly associated with
internet? Draw a flowchart to show various java tools are used in application
development.
Ans:
Difference between Application and Applet

1. Definition of Application and Applet – Applets are feature rich application programs that
are specifically designed to be executed within an HTML web document to execute small
tasks or just part of it. Java applications, on the other hand, are stand-alone programs that are
designed to run on a stand-alone machine without having to use a browser.
2. Execution of Application and Applet– Applications require main method() to execute the
code from the command line, whereas an applet does not require main method() for
execution. An applet requires an HTML file before its execution. The browser, in fact,
requires a Java plugin to run an applet.
3. Compilation of Application and Applet–Application programs are compiled using the
“javac” command and further executed using the java command. Applet programs, on the
other hand, are also compiled using the “javac” command but are executed either by using the
“appletviewer” command or using the web browser.
4. Security Access of Application and Applet – Java application programs can access all the
resources of the system including data and information on that system, whereas applets
cannot access or modify any resources on the system except only the browser specific
services.
5. Restrictions of Application and Applet – Unlike applications, applet programs cannot be
run independently, thus require highest level of security. However, they do not require any
specific deployment procedure during execution. Java applications, on the other hand, run
independently and do not require any security as they are trusted.

Java is strongly associated with the internet because of the first application program written
in Java was hot Java.

Web browsers to run applets on internet.

Internet users can use Java to create applet programs & run then locally using a Java-
enabled browser such as hot Java.

Java applets have made the internet a true extension of the storage system of the local
computer.

d. Compare JSP and Servlet. Explain the lifecycle of a JSP page with a suitable diagram.
Also list any five action tags used in JSP.
Ans:

SERVLET JSP

Servlet is a java code. JSP is a html based code.

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 plays a controller role in MVC JSP is the view in MVC approach for

approach. showing output.

JSP is slower than Servlet because the first

step in JSP lifecycle is the translation of JSP

Servlet is faster than JSP. to java code and then compile.

Servlet can accept all protocol requests. JSP only accept http requests.

In Servlet, we can override the service() In JSP, we cannot override its service()

method. method.

In Servlet by default session management

is not enabled, user have to enable it In JSP session management is automatically

explicitly. enabled.

In Servlet we have to implement

everything like business logic and In JSP business logic is separated from

presentation logic in just one servlet file. presentation logic by using javaBeans.

Modification in Servlet is a time

consuming task because it includes

reloading, recompiling and restarting the JSP modification is fast, just need to click the

server. refresh button.

Following steps are involved in JSP life cycle:


 Translation of JSP page to Servlet
 Compilation of JSP page(Compilation of JSP into test.java)
 Classloading (test.java to test.class)
 Instantiation(Object of the generated Servlet is created)
 Initialization(jspInit() method is invoked by the container)
 Request processing(_jspService()is invoked by the container)
 JSP Cleanup (jspDestroy() method is invoked by the container)
JSP Action Tags Description

jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and include mostly.

jsp:fallback can be used to print the message if plugin is working. It is used in


jsp:plugin.
e. What are the uses of layout managers? Give the name of classes that represents the
layout managers. Explain any five layout managers.

Ans: 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:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west
and center. Each region (area) may contain one component only. It is the default layout of
frame or window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

Java GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns alongwith given horizontal and vertical gaps.

Java FlowLayout

The FlowLayout is used to arrange the components in a line, one after another (in a flow). It
is the default layout of applet or panel.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default
5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

he BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants. They are as follows:

Fields of BoxLayout class


1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS

Constructor of BoxLayout class


1. BoxLayout(Container c, int axis): creates a box layout that arranges the components
with the given axis.

Java CardLayout

The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout class
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.

Commonly used methods of CardLayout class


o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of the
given container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given
container.
o public void show(Container parent, String name): is used to flip to the specified
card with the given name.

SECTION C
3a. Explain the HTTP Protocol. Mention three-basic features of HTTP that make HTTP a
simple but powerful protocol. Give its architecture.
Ans:-The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed,
collaborative, hypermedia information systems. This is the foundation for data
communication for the World Wide Web (i.e. internet) since 1990. HTTP is a generic and
stateless protocol which can be used for other purposes as well using extensions of its request
methods, error codes, and headers.Basically, HTTP is a TCP/IP based communication
protocol, that is used to deliver data (HTML files, image files, query results, etc.) on the World
Wide Web.
There are three basic features that make HTTP a simple but powerful protocol:
 HTTP is connectionless: The HTTP client, i.e., a browser initiates an HTTP request
and after a request is made, the client waits for the response. The server processes the
request and sends a response back after which client disconnect the connection. So
client and server knows about each other during current request and response only.
Further requests are made on new connection like client and server are new to each
other.
 HTTP is media independent: It means, any type of data can be sent by HTTP as long
as both the client and the server know how to handle the data content. It is required for
the client as well as the server to specify the content type using appropriate MIME-
type.
 HTTP is stateless: As mentioned above, HTTP is connectionless and it is a direct
result of HTTP being a stateless protocol. The server and client are aware of each other
only during a current request. Afterwards, both of them forget about each other. Due
to this nature of the protocol, neither the client nor the browser can retain information
between different requests across the web pages.
Architecture- The HTTP protocol is a request/response protocol based on the client/server
based architecture where web browsers, robots and search engines, etc. act like HTTP clients,
and the Web server acts as a server.
Client
The HTTP client sends a request to the server in the form of a request method, URI, and
protocol version, followed by a MIME-like message containing request modifiers, client
information, and possible body content over a TCP/IP connection.
Server
The HTTP server responds with a status line, including the message's protocol version and a
success or error code, followed by a MIME-like message containing server information, entity
meta information, and possible entity-body content.

3b. What is XML? Create a XML document of 10 students of final CSE. Add their roll
numbers, marks obtained in 5 subjects, total marks and percentage. Save this XML document
at the server, write a program that accepts student’s roll number as input and returns the
students marks, total percentage by taking student information for XML document.
4a. Discuss how frames play a big role in advertising on web. What roles do form play in
making web page dynamic.
4b. What are exceptions and how they are handled? Explain with an example. How we define
a try and catch block? Is it essential to catch all types of exceptions?
Ans:Exception Handling is the mechanism to handle runtime malfunctions. We need to
handle such exceptions to prevent abrupt termination of program.
The term exception means exceptional condition, it is a problem that may arise during the
execution of program.
A bunch of things can lead to exceptions, including programmer error, hardware failures,
files that need to be opened cannot be found, resource exhaustion etc.
A Java Exception is an object that describes the exception that occurs in a program. When an
exceptional events occurs in java, an exception is said to be thrown.
The code that's responsible for doing something about the exception is called an exception
handler.All exception types are subclasses of class Throwable, which is at the top of
exception class hierarchy.

Try is used to guard a block of code in which exception may occur. This block of code is
called guarded region. A catch statement involves declaring the type of exception you are
trying to catch. If an exception occurs in guarded code, the catch block that follows the try is
checked, if the type of exception that occured is listed in the catch block then the exception is
handed over to the catch block which then handles it.

1. class Excp
2. {
3. public static void main(String args[])
4. {
5. int a,b,c;
6. try
7. {
8. a=0;
9. b=10;
10. c=b/a;
11. System.out.println("This line will not be executed");
12. }
13. catch(ArithmeticException e)
14. {
15. System.out.println("Divided by zero");
16. }
17. System.out.println("After exception is handled");
18. }
19. }

Output :

Divided by zero
After exception is handled.

5a. Create an html page named as “String Math.html” and within the script tag define some
string variables and use different string function to demonstrate the use of the predefined
functions. Do the same for the Math function.

5b. What are the advantages and drawback of Applet? Write a Java program to create an
Applet for calculator and also perform event handling on each button.
Ans:Advantages of Applets
 Very less response time as it works on the client side.
 Can be run using any browser, which has JVM running in it.
Drawback of Applet
 Plugin is required at client browser to execute applet.
 import java.awt.*;
 import java.awt.event.*;
 import java.applet.*;
 public class Cal extends Applet
 implements ActionListener
 {
 String msg=" ";
 int v1,v2,result;
 TextField t1;
 Button b[]=new Button[10];
 Button add,sub,mul,div,clear,mod,EQ;
 char OP;
 public void init()
 {
 Color k=new Color(120,89,90);
 setBackground(k);
 t1=new TextField(10);
 GridLayout gl=new GridLayout(4,5);
 setLayout(gl);
 for(int i=0;i<10;i++)
 {
 b[i]=new Button(""+i);
 }
 add=new Button("add");
 sub=new Button("sub");
 mul=new Button("mul");
 div=new Button("div");
 mod=new Button("mod");
 clear=new Button("clear");
 EQ=new Button("EQ");
 t1.addActionListener(this);
 add(t1);
 for(int i=0;i<10;i++)
 {
 add(b[i]);
 }
 add(add);
 add(sub);
 add(mul);
 add(div);
 add(mod);
 add(clear);
 add(EQ);
 for(int i=0;i<10;i++)
 {
 b[i].addActionListener(this);
 }
 add.addActionListener(this);
 sub.addActionListener(this);
 mul.addActionListener(this);
 div.addActionListener(this);
 mod.addActionListener(this);
 clear.addActionListener(this);
 EQ.addActionListener(this);
 }

 public void actionPerformed(ActionEvent ae)
 {
 String str=ae.getActionCommand();
 char ch=str.charAt(0);
 if ( Character.isDigit(ch))
 t1.setText(t1.getText()+str);
 else
 if(str.equals("add"))
 {
 v1=Integer.parseInt(t1.getText());
 OP='+';
 t1.setText("");
 }
 else if(str.equals("sub"))
 {
 v1=Integer.parseInt(t1.getText());
 OP='-';
 t1.setText("");
 }
 else if(str.equals("mul"))
 {
 v1=Integer.parseInt(t1.getText());
 OP='*';
 t1.setText("");
 }
 else if(str.equals("div"))
 {
 v1=Integer.parseInt(t1.getText());
 OP='/';
 t1.setText("");
 }
 else if(str.equals("mod"))
 {
 v1=Integer.parseInt(t1.getText());
 OP='%';
 t1.setText("");
 }
 if(str.equals("EQ"))
 {
 v2=Integer.parseInt(t1.getText());
 if(OP=='+')
 result=v1+v2;
 else if(OP=='-')
 result=v1-v2;
 else if(OP=='*')
 result=v1*v2;
 else if(OP=='/')
 result=v1/v2;
 else if(OP=='%')
 result=v1%v2;
 t1.setText(""+result);
 }
 if(str.equals("clear"))
 {
 t1.setText("");
 }
 }
 }

6a. What do you mean by CSS? Write a CSS rule that makes all the text 2.5 times larger than
the base font of the system. Mention how can you integrate CSS on a web page?
Ans: CSS stands for Cascading Style Sheets
 CSS describes how HTML elements are to be displayed on screen, paper, or in
other media
 CSS saves a lot of work. It can control the layout of multiple web pages all at once
 External stylesheets are stored in CSS files

CSS is used to define styles for your web pages, including the design, layout and variations in
display for different devices and screen sizes. Set Font Size With Em :-

{
font-size: 2.5em;
}
Three Ways to Integrate CSS on a webpage :

 External CSS
 Internal CSS
 Inline CSS

With an external style sheet, you can change the look of an entire website by changing just
one file.Each HTML page must include a reference to the external style sheet file inside the
<link> element, inside the head section.

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

"mystyle.css"
body {
background-color: lightblue;
}

h1 {
color: navy;
margin-left: 20px;
}

An internal style sheet may be used if one single HTML page has a unique style.The internal
style is defined inside the <style> element, inside the head section.

<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}

h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

An inline style may be used to apply a unique style for a single element.To use inline styles,
add the style attribute to the relevant element. The style attribute can contain any CSS
property.
<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;text-align:center;">This is a heading</h1>


<p style="color:red;">This is a paragraph.</p>

</body>
</html>

6b. What is difference between Session and Cookies? Write a servlet program for servlet
login and logout using cookies.
Ans:Session
A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.
A session ends when the user closes the browser or after leaving the site, the server will
terminate the session after a predetermined period of time, commonly 30 minutes duration.
Cookies
Cookies are text files stored on the client computer and they are kept of use tracking purpose.
Server script sends a set of cookies to the browser. For example name, age, or identification
number etc. The browser stores this information on a local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
LoginServlet.java-
1. package com.javatpoint;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.Cookie;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. public class LoginServlet extends HttpServlet {
10. protected void doPost(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14. request.getRequestDispatcher("link.html").include(request, response);
15. String name=request.getParameter("name");
16. String password=request.getParameter("password");
17. if(password.equals("admin123")){
18. out.print("You are successfully logged in!");
19. out.print("<br>Welcome, "+name);
20. Cookie ck=new Cookie("name",name);
21. response.addCookie(ck);
22. }else{
23. out.print("sorry, username or password error!");
24. request.getRequestDispatcher("login.html").include(request, response);
25. }
26. out.close();
27. }
28. }
LogoutServlet.java-
1. package com.javatpoint;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.Cookie;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. public class LogoutServlet extends HttpServlet {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14. request.getRequestDispatcher("link.html").include(request, response);
15. Cookie ck=new Cookie("name","");
16. ck.setMaxAge(0);
17. response.addCookie(ck);
18. out.print("you are successfully logged out!");
19. }
20. }

7a. What is JDBC? Explain the Drivers used in JDBC. Write a JDBC Program for insert and
display the record of employees using prepared statement.
Ans:JDBC (Java Database Connectivity) is the Java API that manages connecting to a
database, issuing queries and commands, and handling result sets obtained from the database.
There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
Type-1 driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
Type-1 driver is also called Universal driver because it can be used to connect to any of the
databases.
As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
 The ODBC bridge driver is needed to be installed in individual client machines.
 Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
Type-2 driver
The Native API driver uses the client -side libraries of the database. This driver converts
JDBC method calls into native calls of the database API. In order to interact with different
database, this driver needs their local API, that’s why data transfer is much more secure as
compared to type-1 driver.
 Driver needs to be installed separately in individual client machines
 The Vendor client library needs to be installed on client machine.
 Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
Type-3 driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. Here all the database
connectivity drivers are present in a single server, hence no need of individual client-side
installation.
 Type-3 drivers are fully written in Java, hence they are portable drivers.
 No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
 Network support is required on client machine.
 Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
Type-4 driver
Type-4 driver is also called native protocol driver. This driver interact directly with database.
It does not require any native database library, that is why it is also known as Thin Driver.
 Does not require any native library and Middleware server, so no client-side or server-
side installation.
 It is fully written in Java language, hence they are portable drivers.

import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("url","username","password");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
PreparedStatement stmt=con.prepareStatement("select * from emp");
ResultSet rs=stmt.executeQuery();
while(rs.next()){ System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

7b. What are XML Parsers? Explain the types of parsers with their advantages and
disadvantages.
Ans: XML parser is a software library or a package that provides interface for client
applications to work with XML documents. It checks for proper format of
the XML document and may also validate the XML documents. ... The goal of a parser is to
transform XML into a readable code.
Types of XML Parsers
These are the two main types of XML Parsers:
1. DOM
2. SAX
DOM (Document Object Model)
A DOM document is an object which contains all the information of an XML document. It is
composed like a tree structure. The DOM Parser implements a DOM API. This API is very
simple to use.
Features of DOM Parser
A DOM Parser creates an internal structure in memory which is a DOM document object and
the client applications get information of the original XML document by invoking methods on
this document object.
DOM Parser has a tree based structure.
Advantages
1) It supports both read and write operations and the API is very simple to use.
2) It is preferred when random access to widely separated parts of a document is required.
Disadvantages
1) It is memory inefficient. (consumes more memory because the whole XML document needs
to loaded into memory).
2) It is comparatively slower than other parsers.
SAX (Simple API for XML)
A SAX Parser implements SAX API. This API is an event based API and less intuitive.
Features of SAX Parser
It does not create any internal structure.
Clients does not know what methods to call, they just overrides the methods of the API and
place his own code inside method.
It is an event based parser, it works like an event handler in Java.
Advantages
1) It is simple and memory efficient.
2) It is very fast and works for huge documents.
Disadvantages
1) It is event-based so its API is less intuitive.
2) Clients never know the full information because the data is broken into piece.

You might also like