Está en la página 1de 15

Jdbc Interview Question

What is Jdbc ?

JDBC (Java Database Connectivity) is uses for connect java application with database. It is
Java SE technology, which is install automatically with the jdk software.

How many packages have Jdbc API ?

Jdbc API consists of two packages

java.sql package

javax.sql package

When you connect java appplication with database using Jdbc it's become
database dependent ?

No, Jdbc ia an API (Application programming interface) used to communicate Java


application to database in database independent and platform independent manner.

Difference between ODBC and JDBC

ODBC JDBC
Odbc is platform dependent and database Jdbc is both platform and database
1
independent. independent.
1 Odbc implemented in C language with pointer. Jdbc implemented in java without pointer.

What is DSN (Data Source Name) ?

DSN (Data Source Name) is a file which stores a database name. Read more.....

What is Jdbc Driver ?

Jdbc API contains a set of classes and Interfaces where classes definition is provided by Sun
Micro System and Interfaces Implementation are not provided. For interface Implementation
classes will be provided by vendors, these set of classes are called Jdbc Driver Software.
Read more.....

Explain types of Jdbc Driver ?

JDBC Driver is a software component that enables java application to communicate with the
database.There are 4 types of JDBC drivers, they are:

Jdbc-Odbc Bridge Driver


Native-API driver (partially java driver)

Network Protocol driver (fully java driver)

Thin driver (fully java driver)

Why use Jdbc ?

In yearly days for communicate front end application to database, front end application used
a set of function given by database vendor, to connect with a database.

Even today C and C++ application are connecting with oracle database using a set of function
given by oracle corporation in a orcl.h header file.

But problem with the above communication is a front end application become as a database
dependent application, because every database vendor give its own set of function for
communication.

To overcome the database dependent problem ODBC (Open database connectivity)


community formed by Microsoft with Simba technologies. ODBC community has provided
ODBC API, to connect with any database in a database independent manner.

Why Odbc not use in Java Application ? ?

ODBC API is written in C language woth pointer but Java application does not contain
pointer so internally non pointers java code is converted to C pointers code this conversion is
a time consuming process so the connectivity is very slow.

Java application is platform independent but if it is combined with ODBC then it become
platform dependent but this is against of java motto or principal. To solved the above
problems Sum MicroSystem introduced JDBC technology. Jdbc technology makes java
applications as platform independent and database independent.

In which formate image are store in database ?

In database images are store in binary form.

Difference between Scrollable ResultSet and Non-Scrollable ResultSet ?

Non-Scrollable ResultSet Scrollable ResultSet


Cursor can move both forward and
1 Cursor move only in forward direction
backward direction
Slow performance, If we want to move nth record Fast performance, directly move on
1
then we need to n+1 iteration any record.
Non-Scrollable ResultSet cursor can not move Scrollable ResultSet cursor can move
1
randomly randomly

Why use ResultSetMetaData ?


While executing a select operation on a database, if the table structure is already known for
the programmer then a programmer of Jdbc can read the data from ResultSet object directly.
If the strucure of table is unknown then need ResultSetMetaData.

Difference between PreparedStatement and Statement ?

Statement PreparedStatement
Statement interface is slow because it PreparedStatement interface is faster,
1
compile the program for each execution because its compile the command for once.
We can not use ? symbol in sql command so
We can use ? symbol in sql command, so
2 setting dynamic value into the command is
setting dynamic value is simple.
complex
We can not use statement for writing or We can use PreparedStatement for reading or
3
reading binary data (picture) writing binary data.

Difference between Statement and PreparedStatement ?

Statement PreparedStatement
Statement interface is slow because it PreparedStatement interface is faster,
1
compile the program for each execution because its compile the command for once.
We can not use ? symbol in sql command so
We can use ? symbol in sql command, so
2 setting dynamic value into the command is
setting dynamic value is simple.
complex
We can not use statement for writing or We can use PreparedStatement for reading or
3
reading binary data (picture) writing binary data.

What is Batch Processing ?

Instead of executing a single query, we can execute a batch (group) of queries using batch
processing. Read more.....

Why need of Batch Processing ?

In a Jdbc program if multiple sql operations are there, then each operation is individually
transfer to the database. This approach will increase the number of round trips between java
program (application) and database. If the number of round trips are increased between an
application and database, then it will reduce the performance of an application. To overcome
these problem we use Batch Processing.

What is main Advantage of Batch Processing ?

Increase the performance of an application.

What is Properties Files ?

A property file is one type of the file which organizing the data in the form of (key, value)
pair. Read more.....
How to Insert Images in Database ?

you can not Insert a picture in database directly. but you can store binary data of picture file.
To insert image in database we need a column of type BLOB (Binary Large Object). Read
more.....

How to Retrieve Images from Database ?

you can not retrieve a picture from database directly. While retrieving a image from a
database, the binary data of image will be selected from the database.

While retrieving a image from a database, the binary data of image will be selected from the
database.

Important Points
Again we need to convert binary data to image, because in database binary data of
image is store.

When we select image from database, it will be store in a ResultSet object..

From ResultSet object we need to read the binary data and we need to store in a
InputStream object.

Convert binary data into image


To convert binary data into a image again we write the data into a file using
FileOutputStream object.

Example to Retrieve Image from database


import java.sql.*;
import java.util.*;
import java.io.*;
class PhotoSelect
{
Connection con;
public void openCon()throws Exception
{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@rama-
pc:1521:xe","system","system");
System.out.println("connection is opened");
}
public void select()throws Exception
{
Scanner s=new Scanner(System.in);
PreparedStatement pstmt=con.prepareStatement("select photo from emp_info
where empid=?");
System.out.println("enter emp id");
int empid=s.nextInt();
pstmt.setInt(1,empid);
ResultSet rs=pstmt.executeQuery();
rs.next();
InputStream is=rs.getBinaryStream(1);
rs.close();
FileOutputStream fos=new FileOutputStream("c:/img001.gif");
int k;
while((k=is.read())!=-1)
{
fos.write(k);
}
System.out.println("picture is ready open c:drive");
pstmt.close();
fos.close();
}//end of
public void closeCon()throws Exception
{
con.close();
}//end of select

public static void main(String[] args)throws Exception


{
PhotoSelect ps= new PhotoSelect();
ps.openCon();
ps.select();
ps.closeCon();
}//end of main
}//end of class

Servlet Interview Questions

Interview Questions
Why a Servlet class should be a public ?

A web container internally calls newInstance() method for creating an object of a Servlet
class newInstance() method first checks whether a Servlet class is public or not if public then
create an object otherwise it does not create an object. Because of the above reason a Servlet
class must be public..

What is container ?
Container provides runtime environment for Java2ee (j2ee) applications. A web container is a
predefined application provided by a server, its takes care of Servlet and JSP.

Container
Container provides runtime environment for Java2ee (j2ee) applications. A web container is
a predefined application provided by a server, its takes care of Servlet and JSP.

In console based java applications a class which contains main method acts as a container for
other classes.

Example
class Vachile
{
void speed()
{
System.out.println("Speed limit is 40 km/hr");
}
}
class Mainclass
{
public static void main(String args[])
{
Vachile v=new Vachile();
v.speed();
}
}

Output
Speed limit is 40 km/hr

Explanation: Here Mainclass is providing run-time support for vehicle class so main class is
called a container.

In GUI based applications a frame acts as a container for other awt components like button,
textfield etc.

Operations of Container.
Life Cycle Management

Communication Support

Multithreaded support

Security etc.
1. Life cycle management: Servlet and JSP are dynamic resources of java based web
application. The Servlet or JSP will run on a server and at server side. A container will take
care about life and death of a Servlet or JSP.
A container will instantiate, Initialize, Service and destroy of a Servlet or JSP. It means life
cycle will be managed by a container.

2. Communication Support: If Servlet or JSP wants to communicate with server than its
need some communication logic like socket programming. Designing communication logic is
increase the burden on programmers, but container act as a mediator between a server and a
Servlet or JSP and provides communication between them.

3. Multithreading: A container creates a thread for each request, maintains the thread and
finally destroy it whenever its work is finished.

4. Security: A programmer is not required to write security code in a Servlet/JSP. A container


will automatically provide security for a Servlet/JSP.

Explain work of container.

Life Cycle Management

Communication Support

Multithreaded support

Security etc.

Difference between GenericServlet and HttpServlet


GenericServlet HttpServlet
An abstract class that simplifies writing HTTP
The GenericServlet is an abstract class that
servlets. It extends the GenericServlet base
1 is extended by HttpServlet to provide HTTP
class and provides an framework for handling
protocol-specific methods.
the HTTP protocol.
The GenericServlet does not include
The HttpServlet subclass passes generic
protocol-specific methods for handling
2 service method requests to the relevant
request parameters, cookies, sessions and
doGet() or doPost() method.
setting response headers.
GenericServlet is not specific to any HttpServlet only supports HTTP and HTTPS
3
protocol. protocol.

How can the session in Servlet can be destroyed?


An existing session can be destroyed in the following two ways:

Programatically : Using session.invalidate() method, which makes the container


abandon the session on which the method is called.
When the server itself is shutdown.

What is servlet lazy loading?

A container does not initialize the Servlet as soon as it starts up, it initializes a Servlet when it
receives a request for that Servlet first time. This is called lazy loading.

What is servlet early loading?


The Servlet specification defines the <load-on-startup> element, which can be specified in
the deployment descriptor (web.xml) to make the Servlet container load and initialize the
Servlet as soon as it starts up.
The process of loading a Servlet before any request comes in is called early loading or
preloading or preinitializing a Servlet

We can change the directory or extension name of web.xml ?

No, we can not change the directory or extension name of this web.xml because it is standard
name to recognized by container at run-time.

Forward SendRedirect
Forward action is within the SendRedirect redirect to another web resources which are in
1
same web application. the same web application or other web application.
Forward uses some request
2 SendRedirect use new request and response object.
and response object.

Why need Session Tracking ?

Http protocol is stateless, to make stateful between client and server we need Session
Tracking.

Session Tracking is useful for online shopping, mailing application, E-Commerce


application to track the conversion.

Limitation of Cookies

It will not work if cookie is disabled from the browser.

Cookies are text files, It does not provides security. Any one can change this file.

With cookies need client support that means if client disable the cookies then it does
not store the client location.

Why Http is design as stateless protocol ?

If Http is stateful protocol for multiple requests given by client to web application single
connection will be used between browser and web server across the multiple requests. This
may make clients to engage connection with web server for long time event though the
connection are ideal. Due to this the web server reach to maximum connections even though
most of its connection are idle. To overcome this problem Http is given as stateless.

Why doxxx() methods are empty method in Servlet ?

The main reason doxxx() methods are empty is to reduce the burden on Servlet programmer,
If HttpServlet developer provided seven doxxx() methods as abstract then whenever we
extending the class from HttpServlet, we need to override all seven methods are mandatory, it
increase the burden on Servlet Programmer.

Early loading ?

A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when
it receives a request for that servlet first time. This is called lazy loading.

Lazy loading ?

The servlet specification defines the element, which can be specified in the deployment
descriptor (web.xml) to make the servlet container load and initialize the servlet as soon as it
starts up.

The process of loading a servlet before any request comes in is called early loading or
preloading or preinitializing a servlet

Difference between forward and redirect

ForwardRedirect In forwarding, the destination resource must be java enabled resource


only.In redirection, the destination resource can be either java or non-java resource also. In
forwarding, both source and destination resource must run within the same server. It is not
possible to communicate across the server.In redirection, it is possible to communicate, either
within the serve or even across the server. In forwarding, both the data and control are
forwarded to destination (by default).In redirection, only control is redirected, but not the data
(by default).

JSP Interview Questions


What is JSP ?

JSP technology is used to create dynamic web application same like Servlet technology. It is
another web technology given by Sun MicroSystem for the development of dynamic web
pages on the client browser. It provides a tag based approach to develop java web
components.

What is basis aim of jsp ?

The basis aim of JSP technology is to design any java based web application in easy way.

Why Use JSP ?


The first technology given for the development of web application is CGI. In CGI have some
drawback, So Sun MicroSystem develop a new technology is servlet. But working with
Servlet Sun MicroSystem identify some problem, Servlet technology need in depth java code
and Servlet is failed to attract the programmer.

To overcome the problem with Servlet technology we use jsp technology.

Why jsp is called as a pages ?

A JSP is called as page but not program because a JSP contains totally tags.

Why we not configure JSP file in web.xml ?

Configuring a JSP into a web.xml file is optional because JSP is a public file to the web
application.

Why JSP is called a public file and servlet called private file ?

A JSP called a public file and servlet is called a private file of the web application. Because
JSP files stored in root directory of the web application and Servlet class file stored in sub
directory of the web application. Because JSP is the public file, we can directly send a request
from a browser by using its file name.

When we need Servlet ?

For hug request processing logic with less response generation logic we need Servlet

When we use JSP ?

With less request processing logic with more response generation logic we need JSP.

What are Problem with Servlet

If any changes in static html code of Servlet, the entire Servlet need recompilation,
redeployment, needs server restart.

Any modification in Servlet needs recompilation because both request processing logic and
response generation logic are tight coupled.

Why jsp is browser and j2ee server independent ?

JSP tags will process and execute by the server side web container, So that these are browser
independent and j2ee server independent.

Why no need to configuring a JSP into a web.xml file ?

Configuring a JSP into a web.xml file is optional because JSP is a public file to the web
application.
What is difference between jsp tag and html tag ?

A JSP page contains both html tags and JSP tags. Html tags will produce static output and
JSP tags will produced dynamic output. Because of JSP tags we called as JSP is dynamic web
page.

Difference Between Servlet and JSP

Servlet JSP
JSP is slower than Servlet because it first
1 Servlet is faster than jsp
translate into java code then compile.
In Servlet, if we modify the code then In JSP, if we do any modifications then just we
we need recompilation, reloading, need to click on refresh button and
2
restarting the server> It means it is time recompilation, reloading, restart the server is not
consuming process. required.
3 Servlet is a java code. JSP is tag based approach.
In Servlet, there is no such method for In JSP, we can use the client side validations
4
running JavaScript at client side. using running the JavaScript at client side.
To run a Servlet you have to make an For running a JSP there is no need to make an
entry of Servlet mapping into the entry of Servlet mapping into the web.xml file
5
deployment descriptor file i.e. web.xml externally, you may or not make an entry for JSP
file externally. file as welcome file list.
Coding of jsp is easier than Servlet because it is
6 Coding of Servlet is harden than jsp.
tag based.
In MVC pattern, Servlet plays a In MVC pattern, JSP is used for showing output
7
controller role. data i.e. in MVC it is a view.
8 Servlet accept all protocol request. JSP will accept only http protocol request.
In Servlet, aervice() method need to
9 In JSP no need to override service() method.
override.
In Servlet, by default session
In JSP, session management is automatically
10 management is not enabled we need to
enabled.
enable explicitly.
In Servlet we do not have implicit
object. It means if we want to use an
11 In JSP, we have implicit object support.
object then we need to get object
explicitly form the servlet.
In Servlet, we need to implement In JSP, we can separate the business logic from
12 business logic, presentation logic the presentation logic by uses javaBean
combined. technology.
In Servlet, all package must be imported In JSP, package imported anywhere top, middle
13
on top of the servlet. and bottom.

Difference between life cycle init() of servlet and life cycle method of init() of
jsp.

Servlet init() contains ServletConfig object as a parameter but JspInit() does not contain any
parameter..
config object is accessible in Servlet init(), but it is not accessible in JspInit().

Servlet init() throws ServletException and JspInit() does not throw any exception.

Why JSP Comment called hidden Comment

JSP Comments are not visible on any phase of JSP program execution due to this they are
called hidden Comment

Difference Between JSP and HTML

Html is a Client side Technology and JSP is a Server side Technology. Some other differences
are given below;

HTML JSP
Html is given by w3c (World Wide Web
1 JSP is given by SunMicro System.
Consortium).
2 Html generated static web pages. JSP generated dynamic web pages.
It do not allow to place java code inside Html JSP allows to place java code inside JSP
3
pages. pages.
4 It is Client side technology It is a Server side technology.
5 Need Html Interpreter to execute these code. Need JSP container to execute jsp code.
It does not allow to place custom tag or third It allow to place custom tag or third party
6
party tag. tag.

Why JSP suppor all the feature of Servlet ?

JSP have all the features of Servlet because it is internally Servlet.

Difference between get and post method.

Http protocol mostly use either get() or post() methos to transfer the request.

Get method Post method


Request sends the request parameter as query Post request send the request parameters
1
string appended at the end of the request. as part of the http request body.
Get method is visible to every one (It will be Post method variables are not displayed
2
displayed in the address bar of browser ). in the URL.
Restriction on form data, only ASCII characters No Restriction on form data, Binary data
3
allowed. is also allowed.
Get methods have maximum size is 2000 Post methods have maximum size is 8
4
character. mb.
Restriction on form length, So URL length is
5 No restriction on form data.
restricted
6 Remain in browser history. Never remain the browser history.

What is JSP life Cycle ?


A JSP life cycle can be defined as the entire process from its creation till the destruction
which is similar to a Servlet life cycle with an additional step which is required to translate a
JSP into Servlet. Read more.........

Give Life cycle of a JSP Page

Translation of JSP Page to Servlet

Compilation of JSP Page

Classloading (class file is loaded by the classloader)

Instantiation (Object of the Generated Servlet is created).

Initialization ( jspInit() method is invoked by the container).

Reqeust processing ( _jspService() method is invoked by the container).

Destroy ( jspDestroy() method is invoked by the container).

What are Life cycle method of JSP ?

jspInit()

_jspService()

jspDestroy()

You can override _jspService() method ?

No, we can not override _jspService() method but we can override jspInti() and jspDestroy().

How to inform programer which method can not override ?

To inform the programmer that you should not override the service() method the method
name is started with '_' symbol.

What is Scripting Element in JSP ?

In JSP, java code can be written inside the jsp page using the scriptlet tag. JSP Scripting
element are written inside <% %> tags. These code inside <% %> tags are processed by the
JSP engine during translation of the JSP page. Read more.......

What is JSP Declaration Tag ?

This is used to declare variable and methods in jsp page will be translate and define as class
scope declaration in .java file. Read more.......
What is JSP Expression Tag ?

Expression tag is used, to find the result of the given expression and send that result back to
the client browser. In other words; These are used to show or express the result or response
on browser. We can use this as a display result of variable and invoking method. Read
more.......

What is JSP Scriptlet Tag ?

It use to define or insert java code in a jsp. Every java statement should followed by
semicolon (;). It will be place into jspService() method. Read more.......

What is Request Implicit Object ?

The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp
request by the web container. It can be used to get request information such as parameter,
header information, remote address, server name, server port, content type, character
encoding etc. Read more.........

What is Response Implicit Object ?

In JSP, response is an implicit object of type HttpServletResponse. The instance of


HttpServletResponse is created by the web container for each jsp request. Read more......

What is JSP Directive Elements ?

The directive elements are used to do page related operation during page translation time. JSP
supports 3 types of directive elements, they are;.

Page directive

Include directive

Taglib directive

What is Include Directive ?

It is used to include some other pages into the JSP document, it may be jsp file, html file or
text file. This is known as static include because the target page is located and included at the
time of page compilation.

Why use Include Directive in jsp ?

For Code Re-usability

What is Page Directive ?


The page directive defines attributes that apply to an entire JSP page. This element is used to
define default of explicit operation to the jsp. Read more..........

Taglib Directive ?

This is used to use custom tags in JSP page, here the custom tag may be user defined ot JSTL
tag or strust, JSF,..... etc. Read more..........

Difference between Include Directive and Include Action

Include Directive Include Action


In Include directive, the code of one jsp page is Include Action, the response of one page
1 inserted into another jsp. It is called as compile will be inserted into another page. It is
time or static including. called as run-time or dynamic including.
In Include directive, for both source and
In Include action, individually Servlet are
destination pages, only a single Servlet will be
2 generated for each jsp page. So it
generated internally so number of Servlet object
increases the number of servlet object.
are reduced.
In Include directive, the destination must be jsp In Include action, the destination resource
3
page only. can be a jsp or Servlet or html.
In jsp include directive, we have both html and In include action, we have only xml
4
xml syntax for the tag. syntax but there is one html syntax.
5 <%@include file=" "%> <%JSP:include page=" "%>
In include action the page may exits either
In include directive, the file must be available
6 within same application or another web
in the within some application.
application of server.

También podría gustarte