(US05CBCA25) Java Question Bank Solution
(US05CBCA25) Java Question Bank Solution
(US05CBCA25) Java Question Bank Solution
Unit – 1
MCQs
1. ___________ is a java API which enables the java programs to execute SQL statements.
A. JDBC B. JDK
C. JRE D. Applet
2. The JDBC _______ class defines objects which can connect Java applications to a JDBC driver.
A. Statement B. DriverManager
C. ResultSet D. SQLManager
A. openConnection() B. setConnection()
C. makeConnection() D. getConnection()
10. The ________ method is used to successively step through the rows of the ResultSet object.
A. forward() B. next()
C. both() D. None()
14. Which of the List method is use to returns element at the specified index?
A. add() B. get()
C. set() D. remove()
15. Which of the List method is use to replaces element at given index with new element?
A. add() B. get()
C. set() D. remove()
16. the indexOf() method returns the _________ if element is not present in list.
A. 0 B. True
B. False D. -1
19. _________ is use for implements a synchronized dynamic array that means it can grow or shrink
as required.
A. Array B. ArrayList
C. Vector D. All of above
22. The automatic conversion from primitive data type to its corresponding wrapper class is known
as ___________.
A. unboxing B. autoboxing
C. Both D. None
23. The automatic conversion from wrapper type to its corresponding primitive type is known
as_________.
A. unboxing B. autoboxing
C. Both D. None
24. which is true for converting primitive to wrapper?
int a=20;
A. int i=Integer.valueOf(a); B. Integer i=Integer.valueOf(a);
C. Integer i=int.valueOf(a); D. int i=int.valueOf(a);
Short Question
1. Define JDBC?
Ans: JDBC (Java Database Connectivity) is a java API which enables the java programs to execute SQL
statements. It is an application programming interface that defines how a java programmer can access
the database in tabular format from Java code using a set of standard interfaces and classes written
in the Java programming language.
Ans:
OR
Ans: executeQuery() method is used for select statement while executeUpdate() is used for create or
modify tables. Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate().
Ans: • The SQL statements that read data from a database query return the data in a result set. The
SELECT statement is the standard way to select rows from a database and view them in a result set.
• A Result Set object maintains a cursor that points to the current row in the result set. The term
"result set" refers to the row and column data contained in a ResultSet object.
• The next() method is used to successively step through the rows of the tabular results.
Type of ResultSet:
1. ResultSet.TYPE_FORWARD_ONLY
2. ResultSet.TYPE_SCROLL_INSENSITIVE
3. ResultSet.TYPE_SCROLL_SENSITIVE
6. Write a syntax or example for creating and executing any sql statement?
Example:-
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
1. Positional Access
2. Search
3. Iteration
4. Range-View
8. Write two differences between ArrayList and Vector?
Ans:
ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.
ArrayList increments 50% of current array size if Vector increments 100% means doubles the
the number of elements exceeds from its array size if the total number of elements
capacity. exceeds than its capacity.
ArrayList is not a legacy class. It is introduced in Vector is a legacy class.
JDK 1.2.
ArrayList is fast because it is nonsynchronized. Vector is slow because it is synchronized, i.e., in
a multithreading environment, it holds the other
threads in runnable or non-runnable state until
current thread releases the lock of the object.
ArrayList uses the Iterator interface to traverse A Vector can use the Iterator interface or
the elements. Enumeration interface to traverse the elements.
• An iterator is an interface that is used in place of Enumerations in the Java Collection Framework.
Moreover, an iterator differs from the enumerations in two ways:
• Iterator permits the caller to remove the given elements from the specified collection
during the iteration of the elements.
Methods Description
forEachRemaining(Consumeraction) Performs the given action on each of the
element
hasNext() Returns a true value if the more number of
elements are encountered during iteration
next() Returns the next specified element during the
iteration
remove() Removes the last element from the collection as
provided by the iterator.
• These are known as wrapper classes, because they "wrap" the primitive data type into an object of
that class.
• The wrapper classes are part of the java.lang package, which is imported by default into all• Java
programs.
• The wrapper class in Java provides the mechanism to convert primitive into object andobject into
primitive.
Ans:
Autoboxing Unboxing
The automatic conversion of primitive data type The automatic conversion of wrapper type into
into its corresponding wrapper class is known as its corresponding primitive type is known as
autoboxing. unboxing.
assed as an argument to a function which is Passed as an argument to a function which is
expecting a wrapper class object. expecting a primitive data type variable.
assigned to a variable of the type of wrapper assigned to a variable of the type of primitive
class. data type variable.
for example, byte to Byte, char to Character, int For example conversion of integer to int.
to Integer, long to Long, float to Float, boolean
to Boolean, double to Double, and short to
Short.
LONG QUESTIONS
1. What is Java Database Connectivity? Explain component of JDBC?
Ans: Java Database Connectivity:
JDBC (Java Database Connectivity) is a java API which enables the java programs to execute SQL
statements. It is an application programming interface that defines how a java programmer can access
the database in tabular format from Java code using a set of standard interfaces and classes written
in the Java programming language.
JDBC has been developed under the Java Community Process (JCP) that allows multiple
implementations to exist and be used by the same application. JDBC provides methods for querying
and updating the data in Relational Database Management system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading the correct
Java packages and drivers and registering them with the JDBC Driver Manager that is used as a
connection factory for creating JDBC connections which supports creating and executing statements
such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture.
In short JDBC helps the programmers to write java applications that manage these three programming
activities:
1. The JDBC API: The JDBC API provides programmatic access to relational data from the Java
programming language.
The JDBC API is part of the Java platform, which includes the Java Standard Edition (Java SE) and the
Java Enterprise Edition (Java EE). The JDBC 4.0 API is divided into two packages: java.sqland javax.sql.
Both packages are included in the Java SE and Java EE platforms.
2. JDBC Driver Manager: The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver.
3. JDBC Test Suite: The JDBC driver test suite helps you to determine that JDBC drivers will run your
program
4. JDBC-ODBC Bridge: The Java Software bridge provides JDBC access via ODBC drivers. Note that you
need to load ODBC binary code onto each client machine that uses this driver. As a result, the ODBC
driver is most appropriate on a corporate network where client installations are not a major problem,
or for application server code written in Java in a three-tier architecture.
The JDBC API supports both two-tier and three-tier processing models for database access.
1). Import the packages: Requires that you include the packages containing the JDBC classes needed
for database programming. Most often, using import java.sql.* will suffice.
2). Register the JDBC driver: Requires that you initialize a driver so you can open a communications
channel with the database.
3). Open a connection: Requires using the DriverManager.getConnection()method to create a
Connection object, which represents a physical connection with the database.
4). Execute a query: Requires using an object of type Statement for building and submitting an SQL
statement to the database.
5). Extract data from result set: Requires that you use the appropriate ResultSet.getXXX() method to
retrieve the data from the result set.
6). Clean up the environment: Requires explicitly closing all database resources versus relying on the
JVM's garbage collection.
• This statement will allow to move in only one direction (From BOF to
EOF), you cannot move reverse in records. Means once you are on 5th
record, you cannot move back to record number 4,2,1 or 3.
• To make it possible pass following static parameters to method
st=con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
PreparedStatement Use when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use when you want to access database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
1. Type of ResultSet:
• The possible result set type are given below, If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set
ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forwards and backwards, and the
result set is not sensitive to changes made by others to
the database that occur after the result set was
created.
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forwards and backwards, and the
result set is sensitive to changes made by others to the
database that occur after the result set was created.
Vector is very useful if we don't know the size of an array in advance or we need one that can change
the size over the lifetime of a program.
Vector implements a dynamic array that means it can grow or shrink as required. It is similar to the
ArrayList, but with two differences-
Vector is synchronized.
The vector contains many legacy methods that are not the part of a collections framework
Example:
import java.util.*;
public class VectorExample1 {
public static void main(String args[]) {
//Create an empty vector with initial capacity 4
Vector vec = new Vector(4);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
System.out.println("Vector element is: "+vec);
}
}
8. What is Iterator interface? Explain way to iterate the elements of the collection in java?
Ans: Java Iterator interface
• An iterator is an interface that is used in place of Enumerations in the Java Collection Framework.
Moreover, an iterator differs from the enumerations in two ways:
• Iterator interface is a member connected with Java Collections Framework.
• Iterator permits the caller to remove the given elements from the specified collection during the
iteration of the elements.
Methods Description
forEachRemaining(Consumeraction) Performs the given action on each of the
element
hasNext() Returns a true value if the more number of
elements are encountered during iteration.
next() Returns the next specified element during the
iteration.
remove() Removes the last element from the collection as
provided by the iterator.
• Each of Java's eight primitive data types has a class dedicated to it.
• These are known as wrapper classes, because they "wrap" the primitive data type into an object of
that class.
• The wrapper classes are part of the java.lang package, which is imported by default into all Java
programs.
• The wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive.
• Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into
primitives automatically. The automatic conversion of primitive into an object is known as autoboxing
and vice-versa unboxing
1. Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and short to Short.
//Java program to convert primitive into objects //Autoboxing example of int to Integer
int a=20;
}}
2. Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing.
It is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of
wrapper classes to convert the wrapper type into primitives.
//Java program to convert object into primitives //Unboxing example of Integer to int
}}
Unit – 2
MCQs
1. The life cycle of a servlet is managed by
[A]servlet context [B]servlet container [C]the supporting protocol [D]all of the above
7. Which of the following code retrieves the Internet Protocol(IP) address of the client that sent the
request?
A-request.getRemoteAddr()
B-response.getRemoteAddr()
C-Header.getRemoteAddr()
D-None of the above.
8. Which of the following code indicates whether the named response header has already been set?
A-response.contains Header(headerName)
B-request.contains Header(headerName)
C-Header.contains Header(headerName)
D-None of the above.
9. Which of the following code can be used to clear any data that exists in the buffer as well as the
status code and headers?
A-request.reset() B-response.reset() C-response.resetBuffer() D-Noneoftheabove.
10. Which of the following code can be used to set the content type for the body of the response?
A-request.setContentType(type) B-response.setContentType(type)
C-header.setContentType(type) D-None of the above.
Short Questions
1. Draw the web Based Architecture?
Ans:
Ans:
Init() - called only once when a user first invokes a URL corresponding to the servlet.
Init method is a predefined method to initialize an object after its creation. Init method is
a life cycle method for servlets for java. It is started by the browser when java program is
loaded and run by the browser. Init method is a predefine method to initialize an object after
its creation.
public void init() throws ServletException {
// Initialization code...
Ans:
service() - perform the actual task handle requests coming from the client( browsers).
Each time the server receives a request for a servlet, the server generate a new thread and calls
service.
The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet,
doPost, doPut, doDelete, etc. methods as appropriate.
}
4. Explain Destroy() method in brief.(servlet)?
Ans:
destroy() - called only once at the end of the life cycle of a servlet. destroy() Called by the servlet
container to indicate to a servlet that the servlet is being taken out of service. This
method is only called once all threads within the servlet's service method have exited or after
a timeout period has passed
public void destroy()
// Finalization code...
Ans:
ServeletConfig() - An object of ServletConfig is created by the web container for each servlet. This
object can be used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change the servlet.
So it is easier to manage the web application if any specific content is modified from time to time.
// code..
Ans:
ServletInfo() - returns information about servlet such as writer, copyright, version etc.
// code..
}
LONG QUESTIONS
1. Explain Servlet in Brief and write a short note on Advantages of web-based applications?
Ans: Servlets
• Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise
databases.
• Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard
part of the Java's enterprise edition (J2EE)
• Java Servlets are programs that run on a Web or Application server and act as a middle layer between
a request coming from a Web browser or other HTTP client and databases or applications on the HTTP
server.
• Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
• A number of Web Servers that support servlets are available in the market. Some web servers are
freely downloadable and Tomcat is one of them.
• Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages
technologies
• 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, then send response back to the web server.
Advantages of Servlet
• Servlets execute within the address space of a Web server. It is not necessary to create a separate
process to handle each client request.
• Java security manager on the server enforces a set of restrictions to protect the resources on a server
machine. So servlets are trusted.
• The full functionality of the Java class libraries is available to a servlet. It can communicate with
applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.
• Java servlets have been created and compiled just like any other Java class. After you install the
servlet packages and add them to your computer's Classpath, you can compile servlets with the JDK's
Java compiler or any other current compiler.
2. Write a short note on the HTTP Servlet Class with doGet() and doPost() method. (Give Example)?
HTTP servlets are sub classes of javax.servlet.HttpServlet. It has built-in HTTP protocol support. The
doGet and doPost methods are used to handle client requests (GET or POST requests).
doGet():
request results from a normal request for a URL or from an HTML form has no METHOD specified
// Servlet code
}
Example:
doPost():
request results from an HTML form that specifically lists POST as the METHOD
// Servlet code
Example:
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet.
ServletRequest is an interface whose object is used to provide the information of each request to servle.
This information may be any name, type, value or other attribute. This interface is present in
javax.servlet package. Servlet container is responsible to create ServletRequest object which is given
with service() method argument.
Methods of ServletRequest
Method Description
String getParameter(String name) This method returns the value given in requires
as a String
Object getAttribute(String name) This method provides the attribute of request as
an object.
String getServerName() This method provides the server name to which
request is sent.
Int getServerPort() This method returns the port number to which
request is sent.
Boolean isSecure() This method indicates whether the server is
secure or not.
ServletResponse interface:
The object of ServletResponse interface is used to send the responses to the cients. The information
send in responses can be a binary or character data.
Methods of ServletResponse
Method Description
PrintWriter getWriter() This method is used to send character data in
response.
Int getBufferSize() This method returns the capacity of buffer in
sent response.
ServletOutputStream getOutputStream() This method is used to send binary data in
response.
Boolean isCommited() This method indicates the completion of
response.
Void reset() This method is used to remove the data present
in buffer.
Void setContentType(String type) This method is used to set the type of content.
The response object is where the servlet can write information about the data it will send back.
Whereas the majority of the methods in the request object start with GET, indication that they get a
value, many of the important methods in the response object start with SET, indicating that they
change some property.
Method Description
public void addCookie(Cookie cookie) Adds The Specified cookie to the response. This
method can be called multiple times to set more
than one cookie.
public void addDateHeader(String name, long Adds a response header with the given name
date) and date-value.
public void addHeader(String name, String value) Adds a response header with the given name
and value.
public void addIntHeader(String name, int value) Adds a response header with the given name
and integer value.
public boolean containsHeader(String name) Returns a boolean indicating whether the
named response header has already been se.
public String encodeRedirectURL(String url) Encodes the specified URL for use in the
sendRedirect method or, if encoding is not
needed, returns the URL unchanged.
public String encodeURL(String url) Encodes the specified URL by including the
session ID in it, or , if encoding is not needed,
returns the URL unchanges.
public String sendError(int sc) throws Sends an error response to the client using the
IOException specified status code and clearing the buffer.
public void sendError(int Be, String mag) throws Sends an error response to the client using the
IOException specified status clearing the buffer.
public void sendRedirect(string location) throws Sends a temporary redirect response to the
IOException client using the specified redirect location URL.
public void setDateHeader(String name, long Sets a response header with the given name and
date) date-value,
public void setHeader(String name, String value) Sets a response header with the given name and
value.
public void setIntHeadeR(String name, int value) Sets a response header with the given name and
integer value.
public void setStatus(int sc) Sets the status code for this response.
6. Explain Cookies with Servlet with example?
Following is the list of useful methods which you can use while manipulating cookies in servlet
In this example, we are storing the name of the user in the cookie object and accessing it in another
servlet. As we know well that session corresponds to the particular user. So if you access it from too
many browsers with different values, you will get the different value.
index.html
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action='servlet2'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
7. Explain Session API in detail?
• Session Tracking is a way to maintain state (data) of an user. It is also known as session management
in servlet.
• Http protocol is a stateless so we need to maintain state using session tracking techniques. Each
time user requests to the server, server treats the request as the new request. So we need to maintain
the state of an user to recognize to particular user.
1. Cookies
3. URL Rewriting
4. HttpSession
servlet provides HttpSession Interface which provides a way to identify a user across more than one
page request or visit to a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP
server. The session persists for a specified time period, across more than one connection or page
request from the user.
You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as
below –
You need to call request.getSession() before you send any document content to the client.
Unit-3
MCQs
1) Which tag should be used to pass information from JSP to included JSP?
a) Using <%jsp:page> tag
b) Using <%jsp:param> tag
c) Using <%jsp:import> tag
d) Using <%jsp:useBean> tag
2) Which one is the correct order of phases in JSP life cycle?
a) Initialization, Cleanup, Compilation, Execution
b) Initialization, Compilation, Cleanup, Execution
c) Compilation, Initialization, Execution, Cleanup
d) Cleanup, Compilation, Initialization, Execution
3) “request” is instance of which one of the following classes?
a) Request
b) HttpRequest
c) HttpServletRequest
d) ServletRequest
4) Application is instance of which class?
a) javax.servlet.Application
b) javax.servlet.HttpContext
c) javax.servlet.Context
d) javax.servlet.ServletContext
5) Which is not a directive?
a) include
b) page
c) export
d) taglib
6) TLD Stands For____
a) Tag Library Data
b) Tag Library Domain
c) Tag Library Descriptor
d) Tag Library Description
7) Which of the following is true about Initialization phase in JSP life cycle?
a) When a container loads a JSP it invokes the jspInit() method before servicing any
requests.
b) Container invokes _jspService() method during Initialization phase.
c) Both of the above.
d) None of the above.
8) What is the use of <c:remove > tag?
a) It removes a item from a list
b) It removes the data row from the database.
c) It removes a variable from either a specified scope or the first scope where the
variable is found
d) None of the above.
9) The difference between Servlets and JSP is the ________
a) Translation
b) Compilation
c) Syntax
d) Both A and B
10) Which http method sends by browser that asks the server to get the page only?
a) get
b) post
c) option
d) put
11) JSP Stands for
a) Java Saving Page
b) Java Server Page
c) Java Server Protocol
d) Java ServicePage
12) Using JSP, developer can make ________ type of application.
A) Web based Application
B) Console based Application
C) Mobile Application
D) None of these
13) <%@--- %> tag used for ______
a) Declaration
b) Scriptlets
c) Comments
d) Directives
14) <%!---%> tag used for ____________
a) Declaration
b) Scriptlets
c) Comments
d) Directives
15) <%---%> tag used for ___________
a) Declaration
b) Scriptlets
c) Comments
d) Directives
16) ________comment is for output comment which is appeared in the output stream on the
browser.
a) <%-- Comments --%>
b) <!-- Comments --%>
c) <!-- Comments --!>
d) <%!—Comments --%>
17) <%= ----%> used to define expression in JSP.
a) True
b) False
SHORT QUESTIONS
1. What is JSP?
Ans:
• (JSP) is a server-side programming technology that enables the creation of dynamic, platform-
independent method for building Web-based applications. JSP have access to the entire family of Java
APIs, including the JDBC API to access enterprise databases.
• It helps developers insert java code in HTML pages by making use of special JSP tags, most of which
start with .
• A Java Server Pages component is a type of Java servlet that is designed to fulfill the role of a user
interface for a Java web application.
• JSP tags can be used for a variety of purposes, such as retrieving information from a database or
registering user preferences, accessing JavaBeans components, passing control between pages and
sharing information between requests, pages etc.
2. List out the advantages of JSP and explain any one?
Ans:
1) Extension to Servlet
2) Performance
3) Easy to maintain
5) Faster execution
6) Powerful
Ans:
Ans:
1. Directives
2. Declarations
3. Scriptlets
4. Comments
5. Expressions
Ans:
• You can import packages, define error handling pages or the session information of the JSP page.
Ans: In this tag we can insert any amount of valid java code and these codes are placed in _jspService
method by the JSP engine. Scriptlets can be used anywhere in the page. Scriptlets are defined by using
tags.
8. How to Declare variables and methods in JSP? Explain with Syntax and Example?
Ans:
Declaration declares one or more variables or methods that you can use This tag is used for defining
the functions and variables to be used in the JSP. This element of JSPs contains the java variables and
methods which you can call in expression block of JSP page. Declarations are defined by using tags.
Whatever you declare within these tags will be visible to the rest of the page.
Ans:
• JSP expression element contains a scripting language expression that is evaluated, converted to a
String, Expressions in JSPs is used to output any data on the generated page.
• These data are automatically converted to string and printed on the output stream.
• It is an instruction to the web container for executing the code within the expression and replace it
with the resultant output content.
Ans:
1. page directive
2. include directive
3. taglib directive
Ans:
1. import
2. contentType
3. extends
4. info
5. buffer
6. language
7. isELIgnored
8. isThreadSafe
9. autoFlush
10. session
11. pageEncoding
12. errorPage
13. isErrorPage
Ans: The errorPage attribute is used to define the error page, if exception occurs in the current page,
it will be redirected to the error page.
Ans: The import attribute is used to import class, interface or all the members of a package. It is similar
to import keyword in java class or interface.
Ans: In JSP, There Is the Way To Perform Exception Handling : By errorPage And isErrorPage Attributes
of page directives.
errorPage : The errorPage attribute is used to define the error page, if exception occurs in the current
page, it will be redirected to the error page.
//index.jsp
<html>
<body>
<%@page errorPage=”myerrorpage.jsp” %>
<%=100/0%>
</body>
</html>
isErrorPage : The isErrorPage attribute is used to declare that the current page is the error page.
//myerrorpage.jsp
<html>
<body>
<%@page isErrorPage=”true” %>
Sorry an exception occurred!<br/>
The exception is: <%= exception %>
</body>
</html>
LONG QUESTIONS
• (JSP) is a server-side programming technology that enables the creation of dynamic, platform-
independent method for building Web-based applications. JSP have access to the entire family of Java
APIs, including the JDBC API to access enterprise databases.
• It helps developers insert java code in HTML pages by making use of special JSP tags, most of which
start with .
• A Java Server Pages component is a type of Java servlet that is designed to fulfill the role of a user
interface for a Java web application.
• JSP tags can be used for a variety of purposes, such as retrieving information from a database or
registering user preferences, accessing JavaBeans components, passing control between pages and
sharing information between requests, pages etc.
Advantages of JSP:
1) Extension to Servlet: JSP technology is the extension to Servlet technology. We can use all the
features of the 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.
2) Performance: JSP has significantly better because JSP allows embedding Dynamic Elements in HTML
Pages itself instead of having a separate files.
3) 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.
4) 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.
5) Faster execution: JSP are always compiled before it's processed by the server
6) Powerful: Java Server Pages are built on top of the Java Servlets API, so like Servlets; JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
7) Less code than Servlet: In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.
Ans:
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 compile a JSP into servlet.
When a browser asks for a JSP, the JSP engine first checks to see If the page has never been compiled,
or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need
to perform JSP-specific initialization, override the jspInit() method:
public void jspInit(){
// Initialization code...
}
JSP Execution:
• This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
• Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.
•The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its
parameters as follows:
void _jspService(HttpServletRequest request, HttpServletResponse response)
{
// Service handling code...
}
• The _jspService() method of a JSP is invoked once per a request and is responsible for generating
the response for that request and this method is also responsible for generating responses to all seven
of the HTTP methods ie. GET, POST, DELETE etc.
3. JSP Cleanup:
The destruction phase represents when a JSP is being removed from use by a container.
public void jspDestroy()
{}
Example for JSP:
To create the first JSP page, write some HTML code as given below, and save it by .jsp extension. We
have saved this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory in
apache tomcat to run the JSP page.
<html>
<head> <title> Hello World! </title> </head>
<body>
Hello World! <br/>
<%
out.println(“My First Program n JSP”)
out.println(“Your IP address is ” + request.gerRemoteAddr());
%>
</body>
</html>
1. autoFlush
2. session
3. pageEncoding
4. import: The import attribute is used to import class, interface or all the members of a package. It is
similar to import keyword in java class or interface.
<html>
<body>
<%@ page import=”java.util.Date” %>
Today is: <%= new Date() %>
</body>
</html>
5. contentType : The contentType attribute defines the MIME(Multipurpose Internet Mail Extension)
type of the HTTP response.The default value is "text/html;charset=ISO-8859-1".
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>
6. extends : The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.
7. info : This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
<html>
<body>
<%@ page info=”composed by ABCD” %>
Today is: <%= new java.util.Date() %>
</body>
</html>
8. buffer : The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.
<html>
<body>
<%@ page buffer=”16kb” %>
Today is: <%= new java.util.Date() %>
</body>
</html>
9. language : The language attribute specifies the scripting language used in the JSP page. The default
value is "java".
10. isELIgnored : We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By
default its value is false i.e. Expression Language is enabled by default. We see Expression Language
later. //Now EL will be ignored
11. isThreadSafe : Servlet and JSP both are multithreaded. If you want to control this behaviour of
JSP page, you can use isThreadSafe attribute of page directive. The value of isThreadSafe value is true.
If you make it false, the web container will serialize the multiple requests, i.e. it will wait until the JSP
finishes responding to a request before passing another request to it. If you make the value of
isThreadSafe attribute like:
12. errorPage : The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.
//index.jsp
<html>
<body>
<%@page errorPage=”myerrorpage.jsp” %>
<%=100/0%>
</body>
</html>
13. isErrorPage : The isErrorPage attribute is used to declare that the current page is the error page.
//myerrorpage.jsp
<html>
<body>
<%@page isErrorPage=”true” %>
Sorry an exception occurred!<br/>
The exception is: <%= exception %>
</body>
</html>
Servlet JSP
Servlet is a java code. JSP is a html based code.
Writing code for servlet is harder than JSP as it JSP is easy to code as it is java in html.
is html in java.
Servlet plays a controller role in MVC approach. JSP is the view in MVC approach for showing
output.
Servlet is faster than JSP. JSP is slower than Servlet because the first step
in JSP lifecycle is the translation of 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 we have to implement everything like In JSP business logic is separated from
business logic and presentation logic in just one presentation logic by using javaBeans.
servlet file.
Modification in Servlet is a time consuming task JSP modification is fast, just need to click the
because it includes reloading, recompiling and refresh button.
restarting the server.
The scripting elements provide the ability to insert java code inside the jsp. There are three types of
scripting elements:
1. scriptlet tag
2. expression tag
3. declaration tag
<html>
<body>
<% out.println(“welcome to jsp”); %>
</body>
</html>
The code placed within JSP expression tag is written to the output stream of the response. So you
need not write out.print() to write data. It is mainly used to print the values of variable or method.
Example of JSP expression tag In this example of jsp expression tag, we are simply displaying a
welcome message.
<html>
<body>
<% = “welcome to jsp” %>
</body>
</html>
To display the current time, we have used the getTime() method of Calendar class. The getTime() is an
instance method of Calendar class, so we have called it after getting the instance of Calendar class by
the getInstance() method.
Index.jsp
<html>
<body>
Current Time: <% = java.util.Calendar.getnstance().getTime() %>
</body>
</html>
3. JSP Declaration Tag:
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet. So it doesn't get memory at each request.
In this example of JSP declaration tag, we are declaring the field and printing the value of the declared
field using the jsp expression tag.
Index.jsp
<html>
<body>
<%! Int data=50; %>
<%= “Value of the variable is:” +data %>
</body>
</html>
In this example of JSP declaration tag, we are defining the method which returns the cube of given
number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag to
call the declared method.
Index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= “Cube of 3 is:” +cube(3) %>
</body>
</html>
1. autoFlush
2. session
3. pageEncoding
4. import: The import attribute is used to import class, interface or all the members of a package. It is
similar to import keyword in java class or interface.
<html>
<body>
<%@ page import=”java.util.Date” %>
Today is: <%= new Date() %>
</body>
</html>
5. contentType : The contentType attribute defines the MIME(Multipurpose Internet Mail Extension)
type of the HTTP response.The default value is "text/html;charset=ISO-8859-1".
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>
6. extends : The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.
7. info : This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
<html>
<body>
<%@ page info=”composed by ABCD” %>
Today is: <%= new java.util.Date() %>
</body>
</html>
8. buffer : The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.
<html>
<body>
<%@ page buffer=”16kb” %>
Today is: <%= new java.util.Date() %>
</body>
</html>
9. language : The language attribute specifies the scripting language used in the JSP page. The default
value is "java".
10. isELIgnored : We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By
default its value is false i.e. Expression Language is enabled by default. We see Expression Language
later. //Now EL will be ignored
11. isThreadSafe : Servlet and JSP both are multithreaded. If you want to control this behaviour of
JSP page, you can use isThreadSafe attribute of page directive. The value of isThreadSafe value is true.
If you make it false, the web container will serialize the multiple requests, i.e. it will wait until the JSP
finishes responding to a request before passing another request to it. If you make the value of
isThreadSafe attribute like:
12. errorPage : The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.
//index.jsp
<html>
<body>
<%@page errorPage=”myerrorpage.jsp” %>
<%=100/0%>
</body>
</html>
13. isErrorPage : The isErrorPage attribute is used to declare that the current page is the error page.
//myerrorpage.jsp
<html>
<body>
<%@page isErrorPage=”true” %>
Sorry an exception occurred!<br/>
The exception is: <%= exception %>
</body>
</html>
JSPs are comprised of standard HTML tags and JSP tags. The structure of JavaServer pages are simple
and easily handled by the servlet engine. In addition to HTML ,you can categorize JSPs as following –
1. Directives
2. Declarations
3. Scriptlets
4. Comments
5. Expressions
1. Directives:
JSP directive affects the overall structure of the servlet class. A directives tag always appears at the
top of your JSP file. It is global definition sent to the JSP engine. Directives contain special processing
instructions for the web container. You can import packages, define error handling pages or the
session information of the JSP page.
Syntax: <%@ page.. %>, <%@ include.. %>, <%@ taglib.. %>
2. Declarations:
Declaration declares one or more variables or methods that you can use This tag is used for defining
the functions and variables to be used in the JSP. This element of JSPs contains the java variables and
methods which you can call in expression block of JSP page. Declarations are defined by using tags.
Whatever you declare within these tags will be visible to the rest of the page.
3. Scriptlets:
In this tag we can insert any amount of valid java code and these codes are placed in _jspService
method by the JSP engine. Scriptlets can be used anywhere in the page. Scriptlets are defined by using
tags.
4. Comments:
comment marks text or statements that the JSP container should ignore Comments help in
understanding what is actually code doing. JSPs provides two types of comments for putting comment
in your page.
• First type of comment is for output comment which is appeared in the output stream on the
browser. It is written by using the tags.
• Second type of comment is not delivered to the browser. It is written by using the tags.
5. Expressions:
JSP expression element contains a scripting language expression that is evaluated, converted to a
String, Expressions in JSPs is used to output any data on the generated page. These data are
automatically converted to string and printed on the output stream. It is an instruction to the web
container for executing the code within the expression and replace it with the resultant output
content. For writing expression in JSP, you can use tags.
B. wait(); D. terminate();
B. start(); D. notify();
4. Which class or interface defines the wait(), notify() and notifyAll() methods?
A. Runnable C. Object
B. run(); D. stop();
7. Which method of the thread class is used to find out the priority given to a thread?
A. get(); C. getPriority();
B. threadPriority(); D. getThreadPriority();
Thread t = Thread.currentThread();
System.out.println(t.isAlive());
A. 0 C. false
B. 1 D. true
9. Which function of pre defined class Thread is used to check if current thread being checked is still
running?
A. join(); C. alive();
B. isRunning(); D. isAlive();
10.When a class extends the thread class, it should override ____________ method of thread class to
start the thread.
A. start(); C. run();
B. go(); D. init();
B. main(); D. launch();
B. run(); D. call();
Short Questions
1. What is Java Thread?
Ans:
• Multithreading in Java allows concurrent execution of two or more parts of a program for maximum
utilization of CPU. Each part of such program is called a thread.
• Each of the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
• Multi-threading enables you to write in a way where multiple activities can proceed concurrently in
the same program.
• Every java program creates at least one thread [ main() thread ]. Additional threads are created
through the Thread constructor or by instantiating classes that extend the Thread class.
• Each thread has its own program counter, stack and local variables
• The class should implement the run() method in the Runnable interface
• The functionality that is expected by the Thread to be executed is put in the run() method
Example:
System.out.println("thread is running..");
t.start();
void sleep(int time), void yield(),void wait(),void notify(),void notifyAll(),void interrupt(), boolean
interrupted()
d. void start():This method will start a new thread of execution by calling run() method of
Thread/runnable object.
e. void run():This method is the entry point of the thread. Execution of thread starts from this
method.
f. void join():This method used to queue up a thread in execution. Once called on thread,
current thread will wait till calling thread completes its execution.
h. void sleep(int time): This method suspend the thread for mentioned time duration in
argument (sleeptime in milliseconds).
i. void yield():By invoking this method the current thread pause its execution temporarily
and allow other threads to execute.
j. void wait():when wait() method is invoked on an object, the thread executing that code
gives up its lock on the object immediately and moves the thread to the wait state.
k. void notify():This wakes up threads that called wait() on the same object and moves the
thread to ready state.
l. void notifyAll():This wakes up all the threads that called wait() on the same object.
o. void setPriority(int p): modify a thread’s priority at any time after its creation.
MIN_PRIORITY (1), NORM_PRIORITY and MAX_PRIORITY (10) . The higher the integer, the higher the
priority.Normally the thread priority will be 5.
• In general, the runnable thread with the highest priority is active (running)
• Java is priority-preemptive. If a high-priority thread wakes up, and a low-priority thread is running
then the high-priority thread gets to run immediately.
Long Questions
1. What is Threads? Which are the Characteristics of Thread and why we use Thread?
Ans:
Java Threads:
• Multithreading in Java allows concurrent execution of two or more parts of a program for maximum
utilization of CPU. Each part of such program is called a thread.
• Each of the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
• Multi-threading enables you to write in a way where multiple activities can proceed concurrently in
the same program.
• Every java program creates at least one thread [ main() thread ]. Additional threads are created
through the Thread constructor or by instantiating classes that extend the Thread class.
Thread Characteristics:
• Each thread has its own program counter, stack and local variables
Use Of Threads:
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and
then dies. The following diagram shows the complete life cycle of a thread.
New − A new thread begins its life cycle in the new state. It remains in this state until the program
starts the thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state
is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task. A thread transitions back to the runnable state only when another thread
signals the waiting thread to continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time.
A thread in this state transitions back to the runnable state when that time interval expires or when
the event it is waiting for occurs. This state can be achieved by sleep() method.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
3. Explain Thread creation in Java?
Ans: Thread implementation in java can be achieved in two ways:
• The functionality that is expected by the Thread to be executed is written in the run() method.
• void run(): The new thread begins its life inside this method.
Example:
System.out.println("thread is running...");
obj.start();
• The class should implement the run() method in the Runnable interface
• The functionality that is expected by the Thread to be executed is put in the run() method
Example:
System.out.println("thread is running..");
void sleep(int time), void yield(),void wait(),void notify(),void notifyAll(),void interrupt(), boolean
interrupted()
a. String getName():Retrieves the name of running thread in the current context in String
format.
d. void start():This method will start a new thread of execution by calling run() method of
Thread/runnable object.
e. void run():This method is the entry point of the thread. Execution of thread starts from this
method.
• Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
• Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
Use Synchronization
Types of Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be
done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
Synchronization is built around an internal entity known as the lock or monitor. Every object has an
lock associated with it. By convention, a thread that needs consistent access to an object's fields has
to acquire the object's lock before accessing them, and then release the lock when it's done with them.
class Table{
//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
Table t;
MyThread1(Table t){
this.t=t;
t.printTable(5);
Table t;
MyThread2(Table t){
this.t=t;
t.printTable(100);
t1.start();
t2.start();
}
Output:
10
15
20
25
100
200
300
400
500