You are on page 1of 23

Paper V: Programming in Java-II

Chapter 1- Graphics Programming using Swing


1. Name the interface implemented by Graphic2D classes?
The interface implemented by Graphics2D classes is Shape interface
2. List the method in the Shape interface
boolean contains(Point2D pt)
boolean contains(Rectangle2D rect)
Rectangle2D getBounds2D()
boolean intersect(Rectangle2D rect)
3. List names of classes that implements Shape interface
1. Line2D
2. RectangularShape
3. GeneralPath
4. Polygon
4. List names of class that extends RectangularShape
1. Rectangle2D
2. RoundRectangle2D
3. Ellipse2D
4. Arc2D
5. Name the two types of subclasses of the Ellipse2D class?
1. Ellipse2D.Float(float left, float top, float width, float height)
2. Ellipse2D.Double(double left, double top, double width, double height)
6. List the different Arc2D closure values
1. Arc2D.OPEN
2. Arc2D.CHORD
3. Arc2D.PIE
7. Name the method used to display a shape?
Following methods of Graphics2D class can be used to display shape:
1. clip(Shape s)
2. draw(Shape s)
3. fill(Shape s)
8. List some predefined colors defined in the color class.
BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHTH_GRAY, MAGENTA, ORANGE,
RED, WHITE, YELLOW, PINK
9. Name the class which defines color for native GUI components.
The SystemColor class extends Color and defines symbolic names representing the colors of native
GUI objects on a system.
10. List different constructors of Color class
Color(int red, int green, int blue)
Color(int red, int green, int blue, int alpha)
Color(float red, float green, float blue)
Color(float red, float green, float blue, float alpha)
11. List different methods which take Color class object as argument.
void setColor(Color c)
void setPaint(Paint p)

net2net 1
void setBackground(Color c)
void setForeground(Color c)
12. What is a font? How is it described?
Fonts are used to display text in a particular way. Fonts are described by font family name, font logical
name and font face name.
13. Give constructor of Font class
Font(String name, int style, int size)
14. List different font styles
1. Font.BOLD
2. Font.ITALIC
3. Font.PLAIN
15. List some important methods of Font class
String getFontName()
String getFamily()
String getName()
int getSize()
int getStyle()
boolean isItalic()
boolean isBold()
boolean isPlain()
16. State the method to obtain all fonts on a machine.
To find out which fonts are available on a particular computer, call the
getAvailableFontFamilyNames() method of the GraphicsEnvironment class. The method returns an
array of strings that contains the names of all available fonts. To obtain an instance of the
GraphicsEnvironment class call the static method getLocalGraphicsEnvironment() method of the
GraphicsEnvironment class.
17. What are font metrics? How are they obtained?
Font metrics are attributes that describe a font. To obtain FontMetrics class instance call Graphics2D
class getFontMetrics() method.
18. List some attributes that describe a font.
1. Base line
2. Ascent
3. Descent
4. Leading
5. Height
19. List some methods of FontMetrics class
int charWidth(char c)
int stringWidth(String s)
int getAscent()
int getDescent()
int getHeight()
int getLeading()
Font getFont()
20. How is an image read?
The javax.imageio.imageIO class provides a read() method to read an image.
Image img=null;

net2net 2
try
{
img = ImageIO.read(new File("face.jpg"));
}catch(IOException e){}
21. Which method is used to display an image on a panel?
The java.awt.Component class provides a method drawImage() which draws an image at a specific
location. Since, it is a Component class method, all its subclasses have this method.
drawImage(Image img, int x, int y, ImageObserver observer)
22. What is the purpose of the copyArea method?
The Graphics2D class copyArea() method copies an image are.
copyArea(int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY)

Chapter 2: Multithreading
1. What is thread?
A multithreaded program contains 2 or more parts that can run concurrently. Each such part of a
program is called a thread, and each thread defines a separate path of execution.
2. Why synchronization is used to implement threading in Java?
If you want two threads to communicate and share a complicated data structure, such as a linked list,
you need some way to ensure that they dont conflict with each other. That is, you must prevent one
thread from writing data while another thread is in the middle of reading it. This can be done by
synchronization.
3. Explain the method suspend()
The suspend() prevents a thread from running for an indefinite amount of time. The suspend() method
moves a particular thread from runnable state into the blocked state until some other thread resumes it.
4. Explain method wait().
The wait() method allows a thread that is executing a synchronized method or statement block on that
object to release the lock and wait for a notification from another thread.
5. The method yield() can work only with same priority thread. State true or false with justification.
True - yield() will cause the current thread in the Running state to transit to the Ready-to-run state, thus
relinquishing the CPU. The thread is then at the mercy of the thread scheduler as to when it will run
again. If there are no threads waiting in the Ready-to-run state, this thread continues execution. If there
are other threads in the Ready-to-run state, their priorities determine which thread gets to execute.
6. Describe synchronization in respect to multithreading.
With respect to multithreading, synchronization is the capability to control the access of multiple threads
to shared resources. Without synchronization, it is possible for one thread to modify a shared variable
while another thread is in the process of using or updating same shared variable. This usually leads to
significant errors.
7. What are the two types of multitasking?
1. Process-based
2. Thread-based

net2net 3
8. What are the two ways to create the thread?
1. By implementing Runnable
2. By extending Thread
9. What is the signature of the constructor of a thread class?
Thread()
Thread(String threadName)
Thread(Runnable threadob);
Thread(Runnable threadob, String threadName)
10. What are all the methods available in the Runnable Interface?
run()
11. What is the data type for the method isAlive() and this method is available in which class?
boolean, Thread
12. List static methods of Thread class.
1. static Thread currentThread()
2. static int activeCount()
3. static void sleep(long millseconds)
4. static void yield()
13. List instance methods Thread class?
1. boolean isAlive()
2. void join()
3. void resume()
4. void suspend()
5. void stop()
6. void start()
7. void destroy()
14. What are all the methods used for Inter Thread communication and what is the class in which
these methods are defined?
1. wait(),notify() & notifyall()
2. Object class
15. What is the mechanism defined by java for the Resources to be used by only one Thread at a
time?
Synchronisation
16. What is the procedure to own the monitor by many threads?
Not possible
17. What is the unit for 1000 in the below statement?
ob.sleep(1000)
long milliseconds
18. What is the data type for the parameter of the sleep() method?

net2net 4
long
19. What are all the values for the following level?
max-priority
min-priority
normal-priority
10,1,5
20. What is the method available for setting the priority?
void setPriority( int priority)
21. Name the method to find out the thread priority
int getPriority()
22. What is the default thread at the time of starting the program?
main thread
23. The word synchronized can be used with only a method: True/ False
False
24. Which priority Thread can prompt the lower primary Thread?
Higher Priority
25. How many threads at a time can access a monitor?
One
26. What are all the four states associated in the thread?
1. new
2. Runnable
3. blocked
4. dead
27. The suspend()method is used to teriminate a thread? True /False
False
28. The run() method should necessary exists in classes created as subclass of thread? True /False
True
29. When two threads are waiting on each other and can't proceed the programe is said to be in a
deadlock? True/False
True
30. Which method waits for the thread to die?
join() method
31. Garbage collector thread belongs to which priority?
low-priority
32. What is the purpose of creating thread group?
Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating
those threads all at once, rather than individually. For example, you can start or suspend all the threads
within a group with a single method call.

net2net 5
33. What is meant by timeslicing or time sharing?
Timeslicing is the method of allocating CPU time to individual threads in a priority schedule.
34. What is difference between notify() and notifyAll()?
The notify() method wakes up the first thread that called wait() on the same object. The notifyAll()
method wakes up all the threads that called wait() on the same object.
35. What is meant by daemon thread? In java runtime, what is it's role?
Daemon thread is a low priority thread which runs intermittently in the background doing the garbage
collection operation for the java runtime system.
36. What is the purpose of the join() method?
The join() method causes the current thread to wait until the thread on which the join() method is called
terminates.
37. State any two methods to stop the thread.
1. A thread dies naturally when its run() method exits normally.
2. A thread killed when its stop() method is called
38. Multithreading is better than multitasking comment.
True Multithreading require less overhead than multitasking. Multitasking are heavyweight tasks that
require their own separate address spaces. Interprocess communication is expensive and limited.
Context switching from one process to another is also costly. Threads, on the other hand, are
lightweight. They share the same address space and cooperatively share the same heavyweight process.
Interthread communication is inexpensive, and context switching from one thread to the next is low
cost.
39. Java can control different types of multitasking True/False Justify.
False Java is having inbuilt support for thread based multitasking. Process-based multitasking is
mostly a function of the operating system.

Chapter 3: Database Programming


1. What is the use of JDBC API?
The primary use of JDBC API is to provide a means for the developer to issue SQL statements and
process the results in a consistent, database-independent manner.
2. What are the four types of drivers in JDBC?
a) JDBC-ODBC Bridge driver
b) Native API Partly-Java driver
c) JDBC-Net Pure Java driver
d) Native-Protocol Pure Java driver
3. Write the syntax of the database URL
jdbc:<subprotocol>:<databasename>
4. What is the purpose of Class.forName() method?
When we call forName() method on Class class
1) initially the class is loaded into the memory
2) then it calls the static method forName()

net2net 6
3) the static forName() method contains a static block. That static block register the loaded driver class
with the DriverManager class
5. Name the exception thrown when a connection cannot be established?
java.sql.SQLException
6. Which class do the commit(), rollback() methods belong?
Connection
7. What are the types of statements in JDBC?-
1. Statement: to be used createStatement() method for executing single SQL statement
2. PreparedStatement: to be used preparedStatement() method for executing same SQL statement over
and over.
3. CallableStatement To be used prepareCall() method for multiple SQL statements over and over.
8. When to use PreparedSstatement?
PreparedStatement objects are used for precompiled SQL statements that take parameters. However,
they can also be used with repeatedly executed SQL statements that do not accept parameters.
9. Which is the character used as placeholder in PreparedStatement?
The character used as placeholder in PreparedStatement is ?
PreparedStatement ps = con.prepareStatement("INSERT INTO Student VALUES(?,?,?)");
10. When to use executeUpdate()?
To change data (perform an insert, update, or delete) you use the executeUpdate() method.
executeUpdate() is similar to the executeQuery() used to issue a select, however it doesn't return a
ResultSet, instead it returns the number of records affected by the insert, update, or delete statement.
11. What is difference between Connection and Statement?
Connection A session between an application and a driver.
Statement A SQL statement to perform a query or an update operation.
12. When CallableStatement is used?
A CallableStatement object is used to call to a stored procedure;
eg. CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
13. What is the use of setAutoCommit()?
Sets the current connections auto-comit mode. If a connection is in auto-commit mode, then all its SQL
statements will be executed and committed as individual transactions. Otherwise, its SQL statements are
grouped into transactions that are terminated by a call to either the method commit() or the method
rollback().
14. State the significance of ResultSetMetaData.
The ResultSetMetaData provides information about the structure of a particular ResultSet. Information
provided includes the number of available columns, the names of columns, and the data type of each
column.
15. State the difference between statement and prepared statement interface.

net2net 7
A Statement object is used to execute simple SQL statements with no parameters; a
PreparedStatement object is used for precompiled SQL statements that may have IN parameters.
16. What is RowSet?
RowSets are a JDBC 2.0 extension to the java.sql.ResulSet interface. RowSets make it easy to send
tabular data over a network. A RowSet object contains a set of rows from a result set or some other
source of tabular data, like a file or spreadsheet.
17. Explain connect and disconnected RowSet
A connected rowset requires a database connection to be open. A disconnected rowset gets a connection
to a data source, fills itself with data or propagates changes back to the data source and doesnt require
the connection after that. While it is disconnected it doesnt require a JDBC driver or the full JDBC API,
so it requires very little resources.
18. List the interfaces that extend RowSet interface
1. CachedRowSet
2. JDBCRowSet
3. WebRowSet
4. FilteredRowSet
5. JoinRowSet
19. What is metadata? How is it obtained?
Metadata means information about data. It can be obtained using different metadata interfaces. Different
metadata references can be obtained by calling getMetadata() method of Connection, ResultSet,
PreparedStatement or RowSet object.
20. List the metadata interfaces
1. ResultSetMetaData
2. DatabaseMetaData
3. RowSetMetaData
4. ParameterMetaData
21. What is savepoint? How is it created?
A savepoint allows operations to be rollback to a specific operation in a transaction.
conn.setAutoCommit(false);
Savepoint sp = conn.setSavePoint("sp1");
:
conn.rollback(sp);
22. What is scrollable ResultSet?
The scrollable result set in JDBC 2 lets us move forward and backward through a result set and jump to
any position in the result set.
Statement stmt = con.createStatement(type,concurrency)
PreparedStatement ps = con.prepareStatement(command,type,concurrency)
Type
TYPE_SCROLL_INSENSITIVE scrollable but generally not sensitive to changes made by others.
TYPE_SCROLL_SENSITIVE scrollable and generally sensitive to changes made by others.
23. What is updatable ResultSet?
If we want to be able to edit result set data and have the changes automatically reflect in the database,
we need to create updatable result set. Updatable result set need not be scrollable.

net2net 8
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
24. Explain the absolute( ) method of ResultSet.
public boolean absolute(int row)
Moves the cursor to the given row number in this ResultSet object. If the row number is positive, the
cursor moves to the given row number with respect to the beginning of the result set. The first row is
row 1, the second is row 2, and so on. If the given row number is negative, the cursor moves to an
absolute row position with respect to the end of the result set. For example, calling the method absolute(-
1) positions the cursor on the last row; calling the method absolute(-2) moves the cursor to the next-to-
last row, and so on. An attempt to position the cursor beyond the first/last row in the result set leaves the
cursor before the first row or after the last row. Calling absolute(1) is the same as calling first().
Calling absolute(-1) is the same as calling last().
25. What is the use of method getAutoCommit( )?
boolean getAutoCommit()
Retrieves the current auto-commit mode for this Connection object.

Chapter 4: Collections
1. What is Collection?
A collection sometimes called a container is simply an object that groups multiple elements into a
single unit.
2. Why collections are used?
Collections are used to store, retrieve and manipulate data, and to transmit data from one method to
another.
3. What is collection framework?
A collections framework is a unified architecture for representing and manipulating collections.
Collection framework consists of interfaces, implementations & algorithms.
4. List some advantages of collection framework
1. Reduces programming effort
2. Increases program speed and quality
3. Allows interoperability among unrelated APIs
4. Reduces effort to learn and to use new APIs
5. Reduces effort to design new APIs
6. Allows for software reuse.
5. Which interface is at the top of the collection framework?
Collection
6. State the difference between ArrayList and LinkedList
1. ArrayList provides random access while LinkedList only provides sequential access.
2. Insertion and deletion from an ArrayList is slow whereas insertion and deletion is fast in LinkedList
3. ArrayList not synchronized whereas LinkedList is synchronized.

net2net 9
4. ArrayList stores objects in consecutive locations whereas LinkedList stores objects in doubly linked
list.
7. State the difference between ArrayList and Vector
1. Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe.
2. Data growth - A Vector grows by doubling the size of its array, while the ArrayList increases its
array size by 50 percent.
8. What is the advantage of using an Iterator?
Java provides a standard mechanism to traverse any collection in an implementation independent
manner using an Iterator. The Iterator interface provides methods using which we can traverse any
collection.
9. State the Hashset class.
An unsorted, unordered set. It uses hashcode() of the object being inserted.
10. State the Set interface.
The Set interface is the foundation of classes such as HashSet and TreeSet and it is used by the
collection frame work to implement sets. Sets do not allow duplicate elements.
11. State the Map interface
Map represents an object that maps keys to values. A map cannot contain duplicate keys; each key can
map to at most one value.
12. What is use of LinkedList class?
The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the
links at the point of insertion. Therefore, the LinkedList is used when we want fast insertions and
deletions.
13. State the TreeSet class.
TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored
in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent
choice when storing large amounts of sorted information that must be found quickly.
14. State the enumeration interface.
The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the
elements in a collection of objects. This legacy interface has been superseded by Iterator.
15. What is the use of comparator?
The java.util.Comparator interface can be used to create objects to pass to sort methods or sorting data
structures. A Comparator must define a compare function which takes two Objects and returns a -1, 0, or
1
16. State four constructors of Hashset class.
HashSet()
HashSet(Collection c)
HashSet(int initialCapacity)
HashSet(int initialCapacity, float loadFactor)
17. List the interfaces in collection framework

net2net 10
1. Collection
2. List
3. Set
4. Queue
5. SortedSet
6. Map
7. SortedMap
18. List the classes in collection framework
1. ArrayList
2. LinkedList
3. Vector
4. HashSet
5. LinkedHashSet
6. TreeSet
7. HashMap
8. LinkedHashMap
9. TreeMap
10. Hashtable
19. What is difference between HashMap and HashTable?
1. Hashmap is not synchronized where as Hashtable is synchronized.
2. Iterator in the HashMap is fail-safe while the Enumerator for the Hashtable isn't.
3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as
null.
20. List the classes implementing List interface
1. ArrayList
2. Vector
3. LinkedList
21. List the classes implementing Set interface
1. HashSet
2. TreeSet
3. LinkedHashSet
22. List the classes implementing Map interface
1. HashMap
2. TreeMap
3. LinkedHashMap
4. Hashtable
23. What is difference between List and Set?
1. List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.

net2net 11
2. List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the
sequence in which data can be retrieved.(Except HashSet)
24. What is difference between Array and ArrayList?
1. Arrays are created of fix size whereas ArrayList is of not fix size.
2. The size of array cannot be incremented or decremented. But with arrayList the size is variable.
3. Once the array is created elements cannot be added or deleted from it. But with ArrayList the
elements can be added and deleted at runtime.
4. ArrayList is one dimensional but array can be multidimensional.
25. State the use of Iterator and ListIterator
Iterator: Enables you to cycle through a collection, obtaining or removing elements
ListIterator :It extends Iterator allow bidirectional traversal of list & the modification of element
26. Name the interface similar to the Iterator interface
Enumerator
27. Name the class which implements Queue interface
PriorityQueue
28. What are the differences between array and collection?
Array is the one which can save similar data typed elements and the size is limited. Collection is capable
of saving different data typed objects and is growable
29. Order in with elements are added to the collection, in same order they will be displayed when
collection? Justify.
False Collections like ArrayList, LinkedList and Vector retrieves elements in same order the order in
which they were added but collection like HashSet, HashTable retrieves elements in unordered way
whereas TreeSet retrieves elements according to value.

Chapter 5: Servlets
1. Which technologies are provided by Java to develop Web Application?
a. Java Servlet API
b. Java Server Pages
c. Java Server Faces
d. Java Message Service API
e. Java Mail API
f. Java API for XML processing
2. What is servlet?
Servlets are Java technologys answer to CGI programming. They are programs that run on a web server
and build dynamic web page on fly.
3. What servlet can do?
1. Read the explicit data sent by the client.
2. Read the implicit HTTP request data sent by the browser.
3. Generate the results.

net2net 12
4. Send the explicit data (i.e., the document) to the client.
5. Send the implicit HTTP response data.
4. What are characteristics of a Servlet?
1. Efficient
2. Robust.
3. Portable.
4. Persistance.
5. What are two types of servlets?
1. GenericServlet
2. HttpServlet
6. What is servlet container?
The servlet container is a part of a Web server or application server that provides the network services
over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based
responses. A servlet container also contains and manages servlets through their lifecycle.
7. Which are the two packages that make up the servlet architecture?
javax.servlet and javax.servlet.http
8. List the important interfaces in javax.servlet package
1. Servlet
2. ServletConfig
3. ServletResponse
4. ServletRequest
9. List the important classes in javax.servlet package
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
10. List the important interfaces in javax.servlet.http package
1. HttpServletResponse
2. HttpServletRequest
3. HttpSession
11. List the important classes in javax.servlet.http package
1. HttpServlet
2. Cookie
12. List the servlet lifecycle methods
1. init()
2. service()
3. destroy()
13. How to create HTTP servlet?
Create a subclass of HttpServlet and override doGet() or doPost() method.

net2net 13
14. What are the parameters of the doGet() method?
1. HttpServletRequest
2. HttpServletResponse
15. Name the method used to get all values from the html form to servlet
String [] getParameterValues(String parameterName)
16. Name the method used to get the value of specific parameter from the HTML form to the Servlet.
String getParameter(String parameterName)
17. Name the method to redirect the servlet to another html or servlet
void sendRedirect(String url)
18. Explain the doGet method.
The doGet() method is called by the service() method when it receives a GET request. This method is
called when a user clicks on a link, enters a URL into the browser's address bar, or submits an HTML
form with METHOD="GET" specified in the FORM tag.
19. State the destroy() method.
Cleans up whatever resources are being held and makes sure that any persistent state is synchronized
with the servlets current in-memory state.
20. Explain the session tracking.
HTTP is a stateless protocol. Each request is independent of the previous one. However, in some
applications, it is necessary to save state information so that information can be collected from several
interactions between a browser and a server. Sessions provide such a mechanism.
21. Which method is used to send a cookie to the client from servlet? Give syntax.
The method addCookie() of HttpServletResponse is used to send a cookie to the client from servlet.
void addCookie(Cookie cookie)
22. What are different ways of session tracking?
1. Cookies
2. HttpSession
3. URL rewriting
4. Hidden form fields
23. What is session?

The session is an object used by a servlet to track of user's interaction with a Web application across
multiple HTTP requests. The session is stored on the server.
24. Difference between GET and POST
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is
limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL.
In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is
more secure.
25. What is servlet mapping?
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to
map requests to Servlets.

net2net 14
26. What is servlet context?
The servlet context is an object that contains a information about the Web application and container.
Using the context, a servlet can log events, obtain URL references to resources, and set and store
attributes that other servlets in the context can use
27. State any two difference between GenericServlet and Httpservlet.
A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet
and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(),
doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.
28. What is the difference between ServletContext and ServletConfig?
ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container,
for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext
object is contained within the ServletConfig object, which the Web server provides the servlet when the
servlet is initialized.
ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is
created to pass initialization information to the servlet.
29. What is preinitialization of a servlet?
A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a
request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-
on-startup> element, which can be specified in the deployment descriptor to make the servlet container
load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request
comes in is called preloading or preinitializing a servlet.
30. What is difference between doGet() and doPost()?
A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation.
A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are
stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a
servlet only looking at a request string.
31. Explain the directory structure of a web application
The directory structure of a web application consists of two parts.
1. A private directory called WEB-INF.
2. A public resource directory which contains public resource folder.
WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory
32. If a servlet is not properly initialized, what exception may be thrown?
During initialization or service of a request, the servlet instance can throw an UnavailableException or a
ServletException.
33. Differentiate between Servlet and Applet.
Servlets are server side components that execute on the server whereas applets are client side
components and executes on the web browser. Applets have GUI interface but there is not GUI interface
in case of Servlets.
34. List methods of HttpServlet
1. doGet() is used to handle the GET, conditional GET, and HEAD requests
2. doPost() is used to handle POST requests
3. doPut() is used to handle PUT requests
4. doDelete() is used to handle DELETE requests
5. doOptions() is used to handle the OPTIONS requests and
6. doTrace() is used to handle the TRACE requests

35. What is Session ID?

net2net 15
A session ID is an unique identification string usually a long, random and alpha-numeric string, that is
transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in
case url rewriting) and hidden fields of Web pages.
36. What is HTTPSession?
HttpSession interface provides a way to identify a user across across multiple request. The servlet
container uses HttpSession interface to create a session between an HTTP client and an HTTP server.
The session lives only for a specified time period, across more than one connection or page request from
the user.
37. How to track a user session in Servlets?
The interface HttpSession can be used to track the session in the Servlet. Following code can be used to
create session object in the Servlet: HttpSession session = req.getSession(true);
38. How you can destroy the session in Servlet?
You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate();
39. List the methods used to store and obtain information from a HttpSession object
Object getAttribute(String name)
void setAttribute(String name, Object value)
40. Explain sendError() method
void sendError(int errorCode)
Sends an error response to the client using the specified status code and a default message.
void sendError(int errorCode, String message)
Sends an error response to the client using the specified status code and descriptive message.
41. What is cookie?
A cookie is a small amount of text information sent by a web server to a web browser, saved by the
browser, and later sent back to the server.
42. What are different attributes of cookie?
Name, value, comment, path, domain, maximum age, and a version number
43. Give constructor of cookie class?
Cookie(String name, String value)
44. How to read cookies from client?
Use getCookies() method of HttpServletRequest to read all the cookies from client.
Cookie []c = request.getCookies();
45. How to set life of the cookie? Give proper syntax.
Life of cookie can be set by calling setMaxAge() method of cookie class.
void setMaxAge(int age)
Sets the maximum age of the cookie in seconds.

Chapter 6: Java Server Pages


1. What is JSP?
JSP enables web developers to quickly and easily embed Java code into HTML or XML pages to create
dynamic web pages.
2. List the JSP elements

net2net 16
1. Directives
2. Scripting elements
3. Standard actions
4. Implicit objects
3. What is the purpose of JSP directives?
JSP directives are JSP elements that provide global information about a JSP page.
4. State the directives in JSP.
1. page : lets to do things like import classes, customize the servlet superclass etc
2. include : lets to insert a file into the servlet class at the time the JSP file is translated into a servlet
3. taglib: specify custom tags
5. Write the syntax of the page directive.
<% @ page attribute= "value" ... %>
6. What are standard actions?
The JSP standard actions affect the overall runtime behavior of a JSP page and also the response
sent back to the client. They can be used to include a file at the request time, to find or instantiate a
JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.

7. List any four attribute of page directive.


1. language="java"
2. extends="package.class"
3. import="{ package.class | package.* }, ..."
4. session="true|false"
5. buffer="none|8kb|sizekb"
6. autoFlush="true|false"
7. isThreadSafe="true|false"
8. info="text"
9. errorPage="relativeURL"
10. contentType="mimeType"
11. isErrorPage="true|false"
8. Lists implicit objects used in JSP.
1. application
2. config
3. exception
4. out
5. page
6. pageContext
7. request
8. response
9. session
9. List different JSP scripting element
1. Declarations
2. Scriplets
3. Expressions

net2net 17
4. Comments
10. List the JSP servers.
1. Blazix from Desiderata Software
2. TomCat from Apache
3. WebLogic from BEA Systems
4. WebSphere from IBM
11. What are the different scope valiues for the <jsp:useBean>?
The different scope values for <jsp:useBean> are
1. page
2. request
3. session
4. application
12. What is the different between JSP and Servlet?
Servlet JSP
1. HTML Code in Java 1. Java-like code in HTML
2. Not easy to author 2. Very easy to author
3. Code is compiled into servlet
13. What is an Expression?
An expression tag contains a scripting language expression that is evaluated, converted to a String, and
inserted where the expression appears in the JSP file. Because the value of an expression is converted to
a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= new java.util.Date() %>
You cannot use a semicolon to end an expression
14. What is a Declaration?
JSP Declaratives are the JSP tag used to declare variables and methods. Declaratives are enclosed in the
<%! %> tag. You declare variables and functions in the declaration tag and can use anywhere in the JSP.
<%!
int cnt=0;
private int getCount(){
cnt++;
return cnt;
}
%>
<p>Value of Cnt is:</p>
<p><%=getCount()%></p>
15. What is a Scriptlet?

net2net 18
JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages. Scriptlets begins
with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is
invoked.
Example:
<%
String userName=null;
userName=request.getParameter("userName");
%>
16. What are JSP life cycle methods?
1. _jspInit()
2. _jspDestroy()
3. _jspservice()
17. What is a output comment?
A comment that is sent to the client in the viewable page source. The JSP engine handles an output
comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client.
You can see the comment by viewing the page source from your Web browser.
JSP Syntax
<!-- comment [ <%= expression %> ] -->
<!-- This is a comment sent to client on <%=new java.util.Date()%> -->
Displays in the page source:
<!-- This is a comment sent to client on January 24, 2004 -->
18. What is a Hidden Comment?
A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden
comment, and does not process any code within hidden comment tags. A hidden comment is not sent to
the client, either in the displayed JSP page or the HTML page source.
JSP Syntax
<%-- comment --%>
19. What is the difference between <jsp:include page = ... > and <%@ include file = ... >?.
Both the tag includes the information from one page in another. <jsp:include page = ... > is like a
function call from one jsp to another jsp. The included page is executed and the generated html content
is included in the content of calling jsp each time the client page is accessed by the client.
In case of <%@ include file = ... > the content of the included file is textually embedded in the page that
have <%@ include file=".."> directive. In this case if the included file changes, the changed content will
not included in the output.
20. What is the difference between <jsp:forward page = ... > and response.sendRedirect(url)?
The <jsp:forward> element forwards the request object containing the client request information from
one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long
as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new
request to go the redirected page. The response.sendRedirect kills the session variables.
21. What is JSP Custom tags?

net2net 19
JSP Custom tags are user defined JSP language element. JSP custom tags are user defined tags that can
encapsulate common functionality. For example you can write your own tag to access the database and
performing database operations. You can also write custom tag for encapsulate both simple and complex
behaviors in an easy to use syntax and greatly simplify the readability of JSP pages.
22. What is the role of JSP in MVC Model?
JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model.
23. What are three phases of JSP lifecycle?
1. Translation phase
2. Compilation phase
3. Execution phase
24. What do you understand by JSP translation?
It is first phase of JSP lifecycle, where JSP pages get translated to servlet code.
25. What do you understand by JSP compilation?
It is second phase of JSP lifecycle, where the servlet code is compiled. The compilation is done only if
the page is requested for the first time or it has been modified.
26. What do you understand by JSP execution?
It is last phase of JSP lifecycle, where the jsp servlet methods are executed. These are _jspInit(),
_jspService(), _jspDestroy()
27. What you will handle the runtime exception in your jsp page?
The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and
then forwarded to an error processing page.
For example:
<%@ page errorPage="customerror.jsp" %>
above code forwards the request to "customerror.jsp" page if an uncaught exception is encountered
during request processing. Within "customerror.jsp", you must indicate that it is an error-processing
page, via the directive: <%@ page isErrorPage="true" %>
28. Can you extend JSP technology?
JSP technology lets the programmer to extend the jsp to make the programming easier. JSP can be
extended and custom actions and tag libraries can be developed.

Chapter 7: Networking
1. What is a socket?
A socket represents the end-point of the network communication. It provides a simple read/write
interface and hides the implementation details of network and transport layer protocols. It is used to
indicate one of the two end-points of a communication link between two processes. When client
wishes to make connection to a server, it will create a socket at its end of the communication link.
2. What is the port number?
A port number identifies a specific application running in the machine. A port number is a number
in the range 1-65535.
Reserved Ports: TCP/IP protocol reserves port number in the range 1-1023 for the use of specified
standard services, often referred to as well-known services.
net2net 20
3. Define Client and server
A server is a machine that has some resource that can be shared. A server may also be a proxy
server. Proxy server is a machine that acts as an intermediate between the client and the actual
server. It performs a task like authentications, filtering and buffering of data etc. it communicates
with the server on behalf of the client.
A client is any machine that wants to use the services of a particular server. The server is a
permanently available resource, while the client is free to disconnect after its job is done.
4. What is a protocol?
A protocol is a set of rules and standards for communication. A protocol specifies the format of data
being sent over the Internet, along with how and when it is sent.
5. List the important protocol used in internet
1. IP
2. TCP
3. UDP
6. Difference between TCP and UDP
TCP (Transmission Control Protocol): This protocol is used for connection-oriented
communication between two applications on two different machines. It is most reliable and
implements a connection as a stream of bytes from source to destination.
UDP (User Datagram Protocol): It is a connection less protocol and used typically for request and
reply services. It is less reliable but faster than TCP.
7. What is domain name service?
The mapping between the domain name and the IP address is done by a service called DNS.
8. What package is used for implementing networking?
java.net package is used for implementing networking applications
9. What does an InetAddress object represent?
This InetAddress class object is used to represent numerical IP addresses and domain name for that
address i.e. it supports both numeric IP address and hostnames.
10. List the factory methods of InetAddress class
1. static InetAddress getLocalHost()
2. static InetAddress getByName(String hostname)
3. static InetAddress[] getAllByName(String hostname)
11. List some instance methods of InetAddress class
1. byte[] getAddress()
2. String getHostAddress()
3. String getHostName()
12. What types of sockets can be created in java?
1. Datagram Socket (UDP Socket)
2. Stream Sockets (TCP Socket)
13. What is the difference between datagram socket and stream socket?
Datagram socket Stream Socket
Used for sending UDP datagrams Used for sending TCP packets
Unreliable (may be dropped, duplicated, and Reliable (if data lost on the way, TCP
delivered out of order) automatically re-sends)
Less overheads More overheads
Applications DNS Lookup, PING and SNMP Applications FTP
14. A stream socket perform operations faster than datagram socket. True or False? Justify.
False A stream socket communication is reliable. Data arrives reliably in the same order that it was
sent. This requires more resources. Therefore it is slower than datagram socket.

net2net 21
15. List some well known ports numbers.
1. Domain Name System (DNS): 53
2. File Transfer Protocol (FTP): 21
3. Hypertext Transfer Protocol (HTTP): 80
4. Network News Transfer Protocol (NNTP):119
5. Post Office Protocol (POP3): 110
6. Simple Mail Transfer Protocol (SMTP): 25
7. Telnet: 23
16. What is the difference between the URL and URLConnection class?
The URL has a number of component parts. The URL locates a resource over the internet. The URL
class encapsulates Internet URLs. In a way, it does for the Internet resources what the File class does for
local files. URL instance represents the location of a resource, and a URLConnection instance represents
a link for accessing or communicating with the resource at the location.
17. List constructors of URL class
URL(String url_str)
URL(String protocol, String host, String path)
URL(String protocol, String host, int port, String path)
URL(URL urlObject, String urlSpecifier)
18. List instance methods of URL class
String getProtocol()
String getAuthority()
String getHost()
int getPort()
String getPath()
String getQuery()
String getFile()
String getRef()
19. The URL object can be used to read contents of a webpage. Sate True/False and Justify.
True - You can call the URL's openStream() method to get a stream from which you can read the
contents of the URL. The openStream() method returns a java.io.InputStreamobject, so reading from
a URL is as easy as reading from an input stream
20. Name the classes needed to create a client and server stream socket.
1. Socket class to create stream socket for client
2. ServerSocket class for server
21. List some constructors of ServerSocket class
1. ServerSocket(int port)
2. ServerSocket(int port, int numberOfClients)
3. ServerSocket(int port, int numberOfClients, InetAddress address)

Chapter 8: Javabeans Component


1. Define a bean
A bean is defined as: A reusable software component that can be manipulated visually in a builder
tool.
2. What is JavaBeans?

net2net 22
JavaBeans is a portable, platform-independent component model written in the Java programming
language. JavaBean components are known as beans.
3. What are the bean features?
1. Properties
2. Methods
3. Events
4. What is meant by introspection?
Builder tools discover a beans features (that is, its properties, methods, and events) by a process known
as introspection
5. What is meant by bean persistence?
Bean persistence enables beans to save and restore their state. After changing a beans properties, you
can save the state of the bean and restore that bean at a later time.
6. Name any one IDE used as builder tool for beans.
1. Bean Development Kit (BDK)
2. NetBeans
7. What is JAR file?
A JAR file enables you to bundle multiple files into a single archive file. To make any bean usable in a
builder tool, all class files that are used by the bean code should be packaged into a JAR file.
8. What is manifest file?
Manifest file is the configuration of the javabean application document.
It has following format:
manifest-version :1.1
name :test.class
java-bean:true
Save it with extension .mf
9. Which interface should a bean class implement?
Bean class should implement java.io.Serializable interface
10. What should a bean class contain?
The bean class must have a no-argument constructor, should have accessor and mutator methods.
11. List different types of Java Beans.
1. Enterprise Java Beans
2. Standard edition of Java Beans

net2net 23

You might also like