(US05CBCA25) Java Question Bank Solution

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

Question Bank Solution Java

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

3. _________package must import before use of JDBC in program.


A. java.awt.* B. java.util.*
C. java.sql.* D. java.net.*
4. Which method of DriverManager class is use to open a connection.

A. openConnection() B. setConnection()
C. makeConnection() D. getConnection()

5. Which one of the following is the proper for creating statement.


A. Statement st=con.createStatement() B. statement st=con.CreateStatement()
C. Statement st=createStatement() D. Statement st=CreateStatement()

6. Which of the following method is use to executing “select” query?


A. executeSelect() B. executeQuery()
C. executeUpdate() D. None

7. Which of following is/are the types of statements?


A. PreparedStatement B. CallableStatement
C. Both D. None

8. Which of the following is/are types of ResultSet.


A. TYPE_FORWARD_ONLY B. TYPE_SCROLL_INSENSITIVE
C. TYPE_SCROLL_SENSITIVE D. All of the above

9. Which of the following method is use to execute insert query.


A. executeUpdate() B. executeInsert()
C. executeQuery() D. None

10. The ________ method is used to successively step through the rows of the ResultSet object.
A. forward() B. next()
C. both() D. None()

11. Which of the following is not a component of JDBC API?


A. DriverManager B. Connection
C. Transaction D. Statement

12. List Interface is implemented by the classes of ____________


A. ArrayList B. Stack
C. Vector D. All of the above

13. List is the child interface of ________________


A. Collection B. ArrayList
C. LinkedList D. Vector

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

17. ListIteratorisusedtoiterateoverList element and it is___________ iterator.


A. bidirectional B. unidirectional
C. forward directional only D. backward directional only

18. Which of these packages contain all the collection classes?


A. java.lang B. java.util
C. java.net D. java.awt

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

20. Which of these statements aretrue about ArrayList class.


A. It can contain duplicate elements B. It is non synchronized
C. It allows random access D. All of the above

21. The wrapper class inJavaprovidesthemechanismtoconvertprimitiveintoobjectand objectinto


primitive.
A. True B.False

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.

2. List out the type of Driver available in JDBC API?

Ans:

1. JDBC-ODBC bridge plus ODBC driver, also called Type 1.

2. Native-API, partly Java driver, also called Type 2.

3. JDBC-Net, pure Java driver, also called Type 3.

4. Native-protocol, pure Java driver, also called Type 4.

3. Write a syntax or example for open a connection?

Ans: Requires using the DriverManager.getConnection()method to create a Connection object, which


represents a physical connection with the database.

OR

• Example to Connect Java Application with mysql database


1. create database db;
2. use db;
3. create table emp(id int(10),name varchar(40),age int(3));
(where, db is the database name, root is the username and password
both.)
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

4. Differentiate executeQuery() and executeUpdate()?

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().

5. What is ResultSet? List out types of ResultSet?

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?

Ans: Creatubg sql Statement:-

Syntax:- Statement st=con.createStatement(); // con is Connection object

Example:-
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);

7. List out the operation can be performed on List?

Ans: Operations On List:-

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.

9. What is java Iterator interface?

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.

10. Define Wrapper class?

Ans: Wrapper Class:-


• 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 andobject into
primitive.

11. Differentiate autoboxing and unboxing?

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. It helps us to connect to a data source, like a database.


2. It helps us in sending queries and updating statements to the database
3. Retrieving and processing the results received from the database in terms of answering query.

JDBC has four Components:

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.

2. Explain JDBC architecture in detail?


Ans: The primary function of the JDBC API is to provide a means for the developer to issue SQL
statements and process the results in a consistent, database-independent manner. JDBC provides rich,
object-oriented access to databases by defining classes and interfaces.

The JDBC API supports both two-tier and three-tier processing models for database access.

1. JDBC two-tier Architecture


In the two-tier model, a Java application talks directly to the data source. This requires a JDBC driver
that can communicate with the particular data source being accessed. A user's commands are
delivered to the database or other data source, and the results of those statements are sent back to
the user. The data source may be located on another machine to which the user is connected via a
network. This is referred to as a client/server configuration, with the user's machine as the client, and
the machine housing the data source as the server. The network can be an intranet, which, for
example, connects employees within a corporation, or it can be the Internet.
2. JDBC three-tier Architecture
In the three-tier model, commands are sent to a "middle tier" of services, which then sends the
commands to the data source. The data source processes the commands and sends the results back
to the middle tier, which then sends them to the user. MIS directors find the three-tier model very
attractive because the middle tier makes it possible to maintain control over access and the kinds of
updates that can be made to corporate data. Another advantage is that it simplifies the deployment
of applications. Finally, in many cases, the three-tier architecture can provide performance
advantages.

3. Explain types of JDBC Driver in detail?


Ans: Types of JDBC drivers
1. JDBC-ODBC bridge plus ODBC driver, also called Type 1.
2. Native-API, partly Java driver, also called Type 2.
3. JDBC-Net, pure Java driver, also called Type 3.
4. Native-protocol, pure Java driver, also called Type 4.

1. TYPE – 1: JDBC-ODBC Bridge


• This driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK,
Standard Edition. Type 1 is the simplest of all but platform specific i.e only to Microsoft platform.
• This driver converts JDBC method calls into ODBC function calls. Type 1 drivers are written in Native
code.
• In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine.
Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the target
database.
2. TYPE – 2 JDBC-Native API or Native Driver
• In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the
database. These drivers typically provided by the database vendors and used in the same manner as
the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.
• This type of driver converts JDBC calls into calls to the client API for that database.
• The native API should change if the Database is changed because it is specific to a database. Some
speed increase and provides more functionality and performance than the type 1 with a Type 2 driver,
because it eliminates ODBC's overhead.
• The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

3. Type 3: JDBC-Net pure Java or Middleware Driver


• The type 3 driver is written entirely in Java. In a Type 3 driver, a three-tier approach is used to
accessing databases.
• The JDBC clients use standard network sockets to communicate with an middleware application
server. The socket information is then translated by the middleware application server into the call
format required by the DBMS, and forwarded to the database server.
• This kind of driver is extremely flexible, since it requires no code installed on the client and a single
driver can actually provide access to multiple databases.
4. TYPE – 4: Native-protocol or Pure Java driver or Pure Driver
• The type 4 driver is written completely in Java and is hence platform independent. It is installed
inside the Java Virtual Machine of the client.
• It communicates directly with vendor's database through socket connection. This is the highest
performance driver available for the database and is usually provided by the vendor itself.
• MySQL's Connector driver is a Type 4 driver. Because of the proprietary nature of their network
protocols, database vendors usually supply type 4 drivers. Oracle thin driver - oracle.jdbc.driver.
OracleDriver which connect to jdbc:oracle:thin URL format.

4. Write a step of JDBC Program for executing any query?


Ans: Java Database Connectivity Steps
Before you can create a java jdbc connection to the database, you must first import the java.sql
package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be
imported.
There are following six steps involved in building a JDBC application:

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.

5. Explain Statement object and ResultSet object?


Ans: JDBC Statement object
Once a connection is obtained we can interact with the database. Connection interface defines
methods for interacting with the database via the established connection. To execute SQL statements,
you need to instantiate a Statement object from your connection object by using the
createStatement() method.
Statement statement = dbConnection.createStatement();
A statement object is used to send and execute SQL statements to a database.

Three kinds of Statements


• They also define methods that help bridge data type differences between Java and SQL data types
used in a database.
• Following table provides a summary of each type of statements.
Interfaces Recommended Use
Statement Use for general-purpose access to your database. Useful when you are
using static SQL statements at runtime. The Statement interface cannot
accept parameters.

Statement st=con.createStatement(); // con is Connection object

• 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.

JDBC Result Sets


• 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 ResultSet 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.

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.

6. Explain ArrayList in detail with example?


Ans: Java ArrayList class
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and
implements List interface.

The important points about Java ArrayList class are:


• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because array works at the index basis.
• In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any element is
removed from the array list.

Constructors of Java ArrayList


Constructor Description
ArrayList() It is used to build an empty array list.
ArrayList(Collection c) It is used to build an array list that is initialized
with the elements of the collection c
ArrayList(int capacity) It is used to build an array list that has the
specified initial capacity

Declaration of ArrayList ArrayList


ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

Java ArrayList Example


import java.util.*;
class ArrayList1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("ABC"); //Adding object in arraylist
list.add("PQR");
list.add("XYZ");
System.out.println(list); //Invoking arraylist object
}}}

7. Explain Vector in detail with example?


Ans: Java Vector Class
Java Vector class comes under the java.util package. The vector class implements a growable array of
objects. Like an array, it contains the component that can be accessed using an integer index.

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

Java Vector Class Constructors


Vector class supports four types of constructors. These are:
SN Constructor Description
1 vector() It constructs an empty vector with the default size as
10.
2 vector(int initialCapacity) It constructs an empty vector with the specified
initial capacity and with its capacity increment equal
to zero.
3 vector(int initialCapacity, int It constructs an empty vector with thespecified
capacityIncrement) initial capacity and capacity increment.
4 Vector( Collection c) It constructs a vector that contains the elements of
a collection c.

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.

Ways to iterate the elements of the collection in java


There are various ways to traverse the collection elements:
1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
5. By forEach() method.
6. By forEachRemaining() method.

1. Iterating Collection through Iterator interface


Let's see an example to traverse ArrayList elements using the Iterator interface.
import java.util.*;
class ArrayList2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("Ravi"); //Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay"); //Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

2. Iterating Collection through the for-each loop


Let's see an example to traverse the ArrayList elements using the for-each loop
import java.util.*;
class ArrayList3{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing list through for-each loop
for(String obj:al)
System.out.println(obj);
}
}

9. Explain Wrapper class? Also discuss the autoboxing and unboxing?

Ans: wrapper class

• 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.

Wrapper class Example: Primitive to Wrapper (Converting int into Integer )

//Java program to convert primitive into objects //Autoboxing example of int to Integer

public class WrapperExample1{

public static void main(String args[]){

int a=20;

Integer i=Integer.valueOf(a); //converting int into Integer explicitly

Integer j=a; //autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);

}}

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.

Wrapper class Example: Wrapper to Primitive (Converting Integer to int)

//Java program to convert object into primitives //Unboxing example of Integer to int

public class WrapperExample2{

public static void main(String args[]){

Integer a=new Integer(3);

int i=a.intValue(); //converting Integer to int explicitly

int j=a; //unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);

}}
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

2. The include()method of Request Dispatcher


[A]sends a request to another resource like servlet, jsp or html
[B]includes resource of file like servlet , jsp or html
[C]appends the request and response objects to the current servlet
[D]None of the above

3. What's the difference between servlets and applets?


1.Servlets executes on Servers, whereas Applets executes on Browser
2.Servlets have no GUI, whereas an Applet has GUI
3.Servlets creates static web pages, whereas Applets creates dynamic web pages
4.Servlets can handle only a single request, whereas Applet can handle multiple requests
[A]1,2,3arecorrect [B]1,2arecorrect [C]1,3arecorrect [D]1,2,3,4arecorrect

4. Which of the followingis true about servlets?


A-Servlets execute within the address space of a Web server.
B-Servlets are platform-independent because they are written in Java.
C-The full functionality of the Java class libraries is available to a servlet.
D-All of the above.
5. What is javax.servlet.Servlet?
A-interface B-abstract class C-concreate class D-None of the above.

6. Which of the following code is used to get cookies in servlet?


A- response.getCookies()
B-request.getCookies()
C-Cookies.getCookies()
D-None 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:

2. Explain init() method in brief.(servlet)?

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...

3. Explain service() method in brief.(servlet)?

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.

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException{

}
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...

5. Explain ServletConfig() method in brief.(servlet)?

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.

public ServletConfig getServletConfig()

// code..

6. Explain ServletInfo() method in brief.(servlet)?

Ans:

ServletInfo() - returns information about servlet such as writer, copyright, version etc.

public String getServletInfo()

// code..

}
LONG QUESTIONS
1. Explain Servlet in Brief and write a short note on Advantages of web-based applications?

Ans: Servlets

• Servlets provide a component-based, platform-independent method for building Web-based


applications,

• 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.

• Following diagram shows architecture of Servlet:

• 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

• Performance is significantly better.

• Servlets execute within the address space of a Web server. It is not necessary to create a separate
process to handle each client request.

• Servlets are platform-independent because they are written in Java.

• 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)?

Ans: HTTP servlets

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).

• Protocol dependent supports only http.

• Direct subclass of generic servlet.

• It is an abstract class which extends generic servlet and implements java.io.serializable

• uses doGet, doPost and doDelete methods

• Public void service and protected void service

doGet():

request results from a normal request for a URL or from an HTML form has no METHOD specified

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

}
Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP Actions Example</title>
</head>
<body>

<h1> Student Registration Page</h1>


<form action="<%= request.getContextPath() %>/StudentServlet" method="get">
First Name: <input type="text" name="firstName">
<br> <br>

Last Name: <input type="text" name="lastName">


<br> <br>
Email ID: <input type="email" name="emailId">
<br> <br>
Password: <input type="password" name="password"><br>
<br>
<input type="submit" value="register">
</form>
</body>
</html>

doPost():

request results from an HTML form that specifically lists POST as the METHOD

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP Actions Example</title>
</head>
<body>

<h1> Student Registration Page</h1>


<form action="<%= request.getContextPath() %>/StudentServlet" method="post">
First Name: <input type="text" name="firstName">
<br> <br>
Last Name: <input type="text" name="lastName">
<br> <br>
Email ID: <input type="email" name="emailId">
<br> <br>
Password: <input type="password" name="password"><br>
<br>
<input type="submit" value="register">
</form>
</body>
</html>

3. Explain Servlet Life Cycle in detail. (With Diagram)?

Ans: Servlet Life Cycle:

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.

1. The servlet is initialized by calling the init() method.

2. The servlet calls service() method to process a client's request.

3. The servlet is terminated by calling the destroy() method.

4. Finally, servlet is garbage collected by the garbage collector of the JVM.


Init() called only once when a user first invokes a URL corresponding to the servlet

public void init() throws ServletException {


// Initialization code...
}
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.

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException{
}
doGet() request results from a normal request for a URL or from an HTML form has no
METHOD specified

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}
doPost() request results from an HTML form that specifically lists POST as the METHOD

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}
destroy() called only once at the end of the life cycle of a servlet.

public void destroy() {


// Finalization code...
}

4. Explain servlet requests and response methods in detail?

Ans: ServletRequest interface:

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

These are some important methods provided by ServletRequest interface

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.

ServletResponse interface is present in javax.servlet package and passes as an argument of service()


method.

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.

5. Explain methods of HTTP response interface in detail?

Ans: HttpServletResponse is a predefined interface present in javax.servlet.http package. It can be


said that it is a mirror image of request object.

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?

Ans: Servlet Cookies Methods

Following is the list of useful methods which you can use while manipulating cookies in servlet

Sr. No. Method & Description


1 public void setDomain(String pattern)
This method sets the domain to which cookie applies, for example tutorialspoint.com.
2 public String getDomain()
This method gets the domain to which cookie applies, for example tutorialspoint.com.
3 public void setMaxAge(int expiry)
This method sets how much time (in seconds) should elapse before the cookie expires. If
you don't set this, the cookie will last only for the current session.
4 public int getMaxAge()
This method returns the maximum age of the cookie, specified in seconds, By default, -1
indicating the cookie will persist until browser shutdown.
5 public String getName()
This method returns the name of the cookie. The name cannot be changed after creation
6 public void setValue(String newValue)
This method sets the value associated with the cookie
7 public String getValue()
This method gets the value associated with the cookie.
8 public void setPath(String url)
This method sets the path to which this cookie applies. If you don't specify a path, the
cookie is returned for all URLs in the same directory as the current page as well as all
subdirectories.
9 public String getPath()
This method gets the path to which this cookie applies.
10 public void setSecure(boolean flag)
This method sets the boolean value indicating whether the cookie should only be sent over
encrypted (i.e. SSL) connections.
11 public void setComment(String purpose)
This method specifies a comment that describes a cookie's purpose. The comment is
useful if the browser presents the cookie to the user.
12 public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the
cookie has no comment.

Simple example of Servlet Cookies:

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 action="servlet1" method="post">

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

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

</form>
FirstServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String n=request.getParameter("userName");

out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object

response.addCookie(ck);//adding cookie in the response

//creating submit button

out.print("<form action='servlet2'>");

out.print("<input type='submit' value='go'>");

out.print("</form>");

out.close();

}catch(Exception e){System.out.println(e);}

SecondServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){

try{
response.setContentType("text/html");

PrintWriter out = response.getWriter();

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?

Ans: Session Tracking

• Session simply means a particular interval of time.

• 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.

Use Session Tracking

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies

2. Hidden Form Field

3. URL Rewriting

4. HttpSession

The HttpSession Object

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 –

HttpSession session = request.getSession();

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

4) Fast Development: No need to recompile and redeploy

5) Faster execution

6) Powerful

7) Less code than Servlet

3. Write the phase of JSP life cycle pages?

Ans:

The JSP pages follow these phases:

1. Translation of JSP Page

2. Compilation of JSP Page

3. Classloading (the classloader loads class file)

4. Instantiation (Object of the Generated Servlet is created).

5. Initialization ( the container invokes jspInit() method).

6. Request processing ( the container invokes _jspService() method).

7. Destroy ( the container invokes jspDestroy() method). a JSP

4. Draw the structure of JSP life cycle?


5. List the JSP Components?

Ans:

1. Directives

2. Declarations

3. Scriptlets

4. Comments

5. Expressions

6. Write a note on JSP Diective?

Ans:

• 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..%

7. Write a note on JSP Scriptlets?

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.

Syntax: <% Scriptles%>

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.

Syntax: <%! Declaration(s) %>

Examples: <%! int i=0; %>


9. Write a note on JSP Expression?

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.

• For writing expression in JSP, you can use tags.

Syntax: <%= … %>

10. List the directives used in JSP with syntax of it?

Ans:

There are three types of directives:

1. page directive

2. include directive

3. taglib directive

Syntax of JSP Directive: <%@ directive attribute=”value” %>

11. Which are the attributes of JSP page directives?

Ans:

Attributes of JSP page directive:

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

12. What is the use of errorPage attribute of JSP page directives?

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.

Example Of errorPage attribute:


//index.jsp
<html>
<body>
<%@page errorPage=”myerrorpage.jsp” %>
<%=100/0%>
</body>
</html>

13. What is the use of import attribute of JSP page directives?

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.

Example Of import attribute:


//index.jsp
<html>
<body>
<%@page import=”java.util.Date” %>
Today is: <%= new Date() %>
</body>
</html>

14. How can we stop errors on Display in a JSP Page?

Ans: In JSP, There Is the Way To Perform Exception Handling : By errorPage And isErrorPage Attributes
of page directives.

From that way we should stop errors on display in a JSP page.

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.

Example of errorPage attribute

//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.

Example of isErrorPage attribute

//myerrorpage.jsp
<html>
<body>
<%@page isErrorPage=”true” %>
Sorry an exception occurred!<br/>
The exception is: <%= exception %>
</body>
</html>

LONG QUESTIONS

1. What is JSP? What are the advantages of JSP? Explain?

Ans: Java Server Pages(JSP):

• (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.

2. Explain the Life cycle of JSP with one example?

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.

The JSP pages follow these phases:

1. Translation of JSP Page

2. Compilation of JSP Page

3. Classloading (the classloader loads class file)

4. Instantiation (Object of the Generated Servlet is created).

5. Initialization ( the container invokes jspInit() method).

6. Request processing ( the container invokes _jspService() method).

7. Destroy ( the container invokes jspDestroy() method). a JSP


1. JSP Compilation:

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.

The compilation process involves three steps-


•Parsing the JSP.
•Turning the JSP into a servlet.
• Compiling the servlet
2. JSP Initialization:

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>

Follow the steps to execute this JSP page:

1). Start the server


2). Put the JSP file in a folder and deploy on the server
3. Write a note on various attributes of page Directive?

Ans: Attributes of JSP page directive:

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.

Example of import attribute:

<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".

Example of contentType attribute

<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.

Example of info attribute

<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.

Example of buffer attribute

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

<%@ page isThreadSafe=”false” %>

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.

Example of errorPage attribute

//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.

Example of isErrorPage attribute

//myerrorpage.jsp

<html>
<body>
<%@page isErrorPage=”true” %>
Sorry an exception occurred!<br/>
The exception is: <%= exception %>
</body>
</html>

4. Write a difference between Servlet and 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 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 by default session management is not In JSP session management is automatically


enabled, user have to enable it explicitly. enabled.

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.

5. Explain the execution process of JSP in detail?

Ans: JSP Flow of Execution:


When we deploy the JSP Programs, it is the responsibility of the of the JSP Container to convert JSP
programs into corresponding Servlet code. Every JSP container is having a JSP Compiler. It is the
responsibility of the JSP compiler to convert/to run the JSP program.
The following figure shows the steps that will be carried out when we deploy the JSP on top of server.

JSP Program Flow of execution


1. The client sends the request to server.
2. JSP compiler generates (converts JSP into servlet) the servlet code of one.jsp and places it in a file
named one.jsp.java.
3. Now the Java Compiler comes into picture. JavaC converts the Java code into Byte code, i.e,
generates the .class file.
4. Now server creates the servlet object and process the clients request.
6. Explain JSP Scriptlet tag with proper example?

Ans: JSP Scriptlet Tag:

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

1. JSP scriptlet tag:

A scriptlet tag is used to execute java source code in JSP.

Syntax is as follows: <% java source code %>

Example of JSP scriptlet tag

In this example, we are displaying a welcome message.

<html>
<body>
<% out.println(“welcome to jsp”); %>
</body>
</html>

2. JSP expression tag:

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.

Syntax of JSP expression tag: <%= statement %>

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>

Example of JSP expression tag that prints current time

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 JSP declaration tag is used to declare fields and methods.

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.

Syntax of JSP declaration tag: <%! field or method declaration %>

Example of JSP declaration tag that declares field

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>

Example of JSP declaration tag that declares method

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>

7. Write a note on attributes JSP Page directive in detail?

Ans: Attributes of JSP page directive:

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.

Example of import attribute:

<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".

Example of contentType attribute

<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.

Example of info attribute

<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.

Example of buffer attribute

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

<%@ page isThreadSafe=”false” %>

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.

Example of errorPage attribute

//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.

Example of isErrorPage attribute

//myerrorpage.jsp

<html>
<body>
<%@page isErrorPage=”true” %>
Sorry an exception occurred!<br/>
The exception is: <%= exception %>
</body>
</html>

8. Write a note on components of JSP in detail?


Ans:

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.

Syntax: <%! declaration(s) %>


Example: <%! int I = 0; %>

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.

Syntax: <% Scriptles %>

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.

Syntax: <!__Type 1 comment -->, <%-- Type 2 comment --%>

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.

Syntax: <%= … %>

Print Today’s date: <%= (new java.util.Date()).toLocaleString() %>


Unit-4
MCQs

1. Which are the methods of the object class?


A. notify(); C. wait(long msces);

B. notifyAll(); D. All of them

2. Which will contain the body of the thread?


A. run(); C. start();

B. wait(); D. terminate();

3. Which is the name of the method used to start a thread execution?


A. wait(); C. terminate();

B. start(); D. notify();

4. Which class or interface defines the wait(), notify() and notifyAll() methods?
A. Runnable C. Object

B. Thread D. None of Above

5. What are the two valid constructor for Thread?


A. Thread() , Thread(int priority) C. Thread(), Thread(Runnable r, String name)

B. Thread() ,Thread(Runnable r, ThreadGroup g) D. Thread(), Thread(int pripority)

6. Which is not the method defined in class Thread?


A. wait(): C. start();

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();

8. What is the output in the following thread java program?


Class thread_example

public static void main(String args[])

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();

11.In java a thread can be created by ___________


A. Extended the thread class C. Implementing Runnable interface.

B. Both of above() D. None of these

12.Which method is called internally by Thread start() method?


A. run(); C. execute();

B. main(); D. launch();

13.Thread synchronization in a process will be required when ___________________


A. All thread sharing same address space C. All thread sharing same files

B. All thread sharing same global variable D. All of above

14.Which method is used to get current running thread object?


A. runningThread(); C. currentThread();

B. runnableThread(); D. None of Above

15.The life cycle of thread in java is controlled by ____________


A. JVM C. JRE

B. JDK D. None of Above

16.Min and Max priority of thread in java multithreading are_____________


A. 1, 10 C. 0, 255
B. 0, 10 D. 1, 256

17.Which method we implement from runnable interface?


A. start(); C. execute();

B. run(); D. call();

18.What is sometimes called a lightweight process?


A. Process C. JVM

B. Thread D All of above

19.Which method restart the thread?


A. start(); C. restartThread();

B. restart(); D. None of above.

20.Which method we implement from runnable interface?


A. StringBuilder C. StringBuffer

B. All of above D. None of Above

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.

2. Write down Thread characteristics?


Ans:

• Facility to allow multiple activities within a single process

• Referred as lightweight process

• A thread is a series of executed statements

• Each thread has its own program counter, stack and local variables

• A thread is a nested sequence of method calls

• Its shares memory, files and per-process state


3. List Thread implementation in java? Explain any one?
[ or explain Java Thread implementation By extending thread class / By Implementing Runnable
interface]

Ans: Thread implementation in java can be achieved in two ways:

1. Extending the java.lang.Thread class

2. Implementing the java.lang.Runnable Interface

By Implementing Runnable interface:

• The class should implement the Runnable interface

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

public class MyThread implements Runnable {

public void run(){

System.out.println("thread is running..");

public static void main(String[] args) {

Thread t = new Thread(new MyThread());

t.start();

4. List Java Thread Methods?


Ans: String getName(),void setName(String s), Thread.State getState(),void start(),void run(),void
join(), boolean isAlive()

Thread interruption methods (Java Concurrency):

void sleep(int time), void yield(),void wait(),void notify(),void notifyAll(),void interrupt(), boolean
interrupted()

Thread priority methods:

void setPriority(int p), int getPriority()


5. Define the following?
a. String getName():Retrieves the name of running thread in the current context in String
format.

b. void setName(String s): Setting thread name.

c. Thread.State getState():It returns the state of the thread.

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.

g. boolean isAlive():This method will check if thread is alive or dead.

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.

m. void interrupt():Interrupts this thread.

n. boolean interrupted():Tests whether the current thread has been interrupted.

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.

p. int getPriority():Return value of priority of current thread.


6. What is Thread Scheduling?
Ans:

• Execution of multiple threads on a single CPU, in some order, is called scheduling.

• 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.

• Allows on-demand processing

• Efficient use of CPU

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:

• Facility to allow multiple activities within a single process

• Referred as lightweight process

• A thread is a series of executed statements

• Each thread has its own program counter, stack and local variables

• A thread is a nested sequence of method calls

• Its shares memory, files and per-process state

Use Of Threads:

• To perform asynchronous or background processing

• Increases the responsiveness of GUI applications

• Take advantage of multiprocessor systems


• Simplify program logic when there are multiple independent entities

2. Draw Life Cycle of a Thread and explain in detail?


Ans: Life Cycle of a Thread

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.

Following are the stages of the life cycle –

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:

1. Extending the java.lang.Thread class

2. Implementing the java.lang.Runnable Interface

By extending thread class:

• The class should extend Java java.lang.Thread class.

• The class should override the run() method.

• The functionality that is expected by the Thread to be executed is written in the run() method.

• void start(): Creates a new thread and makes it runnable.

• void run(): The new thread begins its life inside this method.

Example:

public class MyThread extends Thread {

public void run(){

System.out.println("thread is running...");

public static void main(String[] args) {

MyThread obj = new MyThread();

obj.start();

By Implementing Runnable interface:

• The class should implement the Runnable interface

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

public class MyThread implements Runnable {

public void run(){

System.out.println("thread is running..");

public static void main(String[] args) {

Thread t = new Thread(new MyThread());


t.start();

4. List Thread methods and explain any five?


Ans: List Thread Method:

String getName(),void setName(String s), Thread.State getState(),void start(),void run(),void join(),


boolean isAlive()

Thread interruption methods (Java Concurrency):

void sleep(int time), void yield(),void wait(),void notify(),void notifyAll(),void interrupt(), boolean
interrupted()

Thread priority methods:

void setPriority(int p), int getPriority()

Explain Five Methods:

a. String getName():Retrieves the name of running thread in the current context in String
format.

b. void setName(String s): Setting thread name.

c. Thread.State getState():It returns the state of the thread.

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.

5. Explain Thread Synchronization and how to Implement synchronization with example?


Ans: Thread Synchronization:

• 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

The synchronization is mainly used to


• To prevent thread interference.

• To prevent consistency problem.

Types of Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

1). Mutual Exclusive

1.1). Synchronized method.

1.2). Synchronized block.

1.3). static synchronization.

2). Cooperation (Inter-thread communication in java)

1). Mutual Exclusive

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

Concept of Lock in Java

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.

From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Example: Synchronized Method

class Table{

synchronized void printTable(int n){

//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);}

}
}

class MyThread1 extends Thread{

Table t;

MyThread1(Table t){

this.t=t;

public void run(){

t.printTable(5);

class MyThread2 extends Thread{

Table t;

MyThread2(Table t){

this.t=t;

public void run(){

t.printTable(100);

public class TestSynchronization2

{ public static void main(String args[]){

Table obj = new Table(); //only one object

MyThread1 t1=new MyThread1(obj);

MyThread2 t2=new MyThread2(obj);

t1.start();

t2.start();

}
Output:

10

15

20

25

100

200

300

400

500

You might also like