You are on page 1of 70

Core Java

1. Meaning - Abstract classes, abstract methods


2. Difference - Java,C++
3. Difference between == and equals method
4. Explain Java security model
5. Explain working of Java Virtual Machine (JVM)
6. Difference: Java Beans, Servlets
7. Difference: AWT, Swing
8. Disadvantages of Java
9. What is BYTE Code ?
10. What gives java it’s “write once and run anywhere” nature?
11. Does Java have “goto”?
12. What is the meaning of “final” keyword?
13. Can I create final executable from Java?
14. Explain Garbage collection mechanism in Java
15. Why Java is not 100% pure object oriented language?
16. What are interfaces? or How to support multiple inhertance in Java?
17. How to use C++ code in Java Program?
18. Difference between “APPLET” and “APPLICATION”
19. What is the difference between procedural and object-oriented programs?-
a) In procedural program, programming logic follows certain procedures and the
instructions are executed one after another. In OOP program, unit of program is
object, which is nothing but combination of data and code. b) In procedural
program, data is exposed to the whole program whereas in OOPs program, it is
accessible with in the object and which in turn assures the security of the code.
20. What are Encapsulation, Inheritance and Polymorphism?- Encapsulation is
the mechanism that binds together code and data it manipulates and keeps both
safe from outside interference and misuse. Inheritance is the process by which one
object acquires the properties of another object. Polymorphism is the feature that
allows one interface to be used for general class actions.
21. What is the difference between Assignment and Initialization?- Assignment
can be done as many times as desired whereas initialization can be done only
once.
22. What is OOPs?- Object oriented programming organizes a program around its
data, i. e. , objects and a set of well defined interfaces to that data. An object-
oriented program can be characterized as data controlling access to code.
23. What are Class, Constructor and Primitive data types?- Class is a template for
multiple objects with similar features and it is a blue print for objects. It defines a
type of object according to the data the object can hold and the operations the
object can perform. Constructor is a special kind of method that determines how
an object is initialized when created. Primitive data types are 8 types and they are:
byte, short, int, long, float, double, boolean, char.
24. What is an Object and how do you allocate memory to it?- Object is an
instance of a class and it is a software unit that combines a structured set of data
with a set of operations for inspecting and manipulating that data. When an object
is created using new operator, memory is allocated to it.
25. What is the difference between constructor and method?- Constructor will be
automatically invoked when an object is created whereas method has to be called
explicitly.
26. What are methods and how are they defined?- Methods are functions that
operate on instances of classes in which they are defined. Objects can
communicate with each other using methods and can call methods in other
classes. Method definition has four parts. They are name of the method, type of
object or primitive type the method returns, a list of parameters and the body of
the method. A method’s signature is a combination of the first three parts
mentioned above.
27. What is the use of bin and lib in JDK?- Bin contains all tools such as javac,
appletviewer, awt tool, etc., whereas lib contains API and all packages.
28. What is casting?- Casting is used to convert the value of one type to another.
29. How many ways can an argument be passed to a subroutine and explain
them?- An argument can be passed in two ways. They are passing by value and
passing by reference. Passing by value: This method copies the value of an
argument into the formal parameter of the subroutine. Passing by reference: In
this method, a reference to an argument (not the value of the argument) is passed
to the parameter.
30. What is the difference between an argument and a parameter?- While
defining method, variables passed in the method are called parameters. While
using those methods, values passed to those variables are called arguments.
31. What are different types of access modifiers?- public: Any thing declared as
public can be accessed from anywhere. private: Any thing declared as private
can’t be seen outside of its class. protected: Any thing declared as protected can
be accessed by classes in the same package and subclasses in the other packages.
default modifier : Can be accessed only to classes in the same package.
32. What is final, finalize() and finally?- final : final keyword can be used for class,
method and variables. A final class cannot be subclassed and it prevents other
programmers from subclassing a secure class to invoke insecure methods. A final
method can’t be overridden. A final variable can’t change from its initialized
value. finalize() : finalize() method is used just before an object is destroyed and
can be called just prior to garbage collection. finally : finally, a key word used in
exception handling, creates a block of code that will be executed after a try/catch
block has completed and before the code following the try/catch block. The
finally block will execute whether or not an exception is thrown. For example, if a
method opens a file upon exit, then you will not want the code that closes the file
to be bypassed by the exception-handling mechanism. This finally keyword is
designed to address this contingency.
33. What is UNICODE?- Unicode is used for internal representation of characters
and strings and it uses 16 bits to represent each other.
34. What is Garbage Collection and how to call it explicitly?- When an object is
no longer referred to by any variable, java automatically reclaims memory used
by that object. This is known as garbage collection. System. gc() method may be
used to call it explicitly.
35. What is finalize() method?- finalize () method is used just before an object is
destroyed and can be called just prior to garbage collection.
36. What are Transient and Volatile Modifiers?- Transient: The transient modifier
applies to variables only and it is not stored as part of its object’s Persistent state.
Transient variables are not serialized. Volatile: Volatile modifier applies to
variables only and it tells the compiler that the variable modified by volatile can
be changed unexpectedly by other parts of the program.
37. What is method overloading and method overriding?- Method overloading:
When a method in a class having the same method name with different arguments
is said to be method overloading. Method overriding : When a method in a class
having the same method name with same arguments is said to be method
overriding.
38. What is difference between overloading and overriding?- a) In overloading,
there is a relationship between methods available in the same class whereas in
overriding, there is relationship between a superclass method and subclass
method. b) Overloading does not block inheritance from the superclass whereas
overriding blocks inheritance from the superclass. c) In overloading, separate
methods share the same name whereas in overriding, subclass method replaces the
superclass. d) Overloading must have different method signatures whereas
overriding must have same signature.
39. What is meant by Inheritance and what are its advantages?- Inheritance is the
process of inheriting all the features from a class. The advantages of inheritance
are reusability of code and accessibility of variables and methods of the super
class by subclasses.
40. What is the difference between this() and super()?- this() can be used to invoke
a constructor of the same class whereas super() can be used to invoke a super
class constructor.
41. What is the difference between superclass and subclass?- A super class is a
class that is inherited whereas sub class is a class that does the inheriting.
42. What modifiers may be used with top-level class?- public, abstract and final
can be used for top-level class.
43. What are inner class and anonymous class?- Inner class : classes defined in
other classes, including those defined in methods are called inner classes. An
inner class can have any accessibility including private. Anonymous class :
Anonymous class is a class defined inside a method without a name and is
instantiated and declared in the same place and cannot have explicit constructors.
44. What is a package?- A package is a collection of classes and interfaces that
provides a high-level layer of access protection and name space management.
45. What is a reflection package?- java. lang. reflect package has the ability to
analyze itself in runtime.
46. What is interface and its use?- Interface is similar to a class which may contain
method’s signature only but not bodies and it is a formal set of method and
constant declarations that must be defined by the class that implements it.
Interfaces are useful for: a)Declaring methods that one or more classes are
expected to implement b)Capturing similarities between unrelated classes without
forcing a class relationship. c)Determining an object’s programming interface
without revealing the actual body of the class.
47. What is an abstract class?- An abstract class is a class designed with
implementation gaps for subclasses to fill in and is deliberately incomplete.
48. What is the difference between Integer and int?- a) Integer is a class defined in
the java. lang package, whereas int is a primitive data type defined in the Java
language itself. Java does not automatically convert from one to the other. b)
Integer can be used as an argument for a method that requires an object, whereas
int can be used for calculations.
49. What is a cloneable interface and how many methods does it contain?- It is
not having any method because it is a TAGGED or MARKER interface.
50. What is the difference between abstract class and interface?- a) All the
methods declared inside an interface are abstract whereas abstract class must have
at least one abstract method and others may be concrete or abstract. b) In abstract
class, key word abstract must be used for the methods whereas interface we need
not use that keyword for the methods. c) Abstract class must have subclasses
whereas interface can’t have subclasses.
51. Can you have an inner class inside a method and what variables can you
access?- Yes, we can have an inner class inside a method and final variables can
be accessed.
52. What is the difference between String and String Buffer?- a) String objects are
constants and immutable whereas StringBuffer objects are not. b) String class
supports constant strings whereas StringBuffer class supports growable and
modifiable strings.
53. What is the difference between Array and vector?- Array is a set of related
data type and static whereas vector is a growable array of objects and dynamic.
54. What is the difference between exception and error?- The exception class
defines mild error conditions that your program encounters. Exceptions can occur
when trying to open the file, which does not exist, the network connection is
disrupted, operands being manipulated are out of prescribed ranges, the class file
you are interested in loading is missing. The error class defines serious error
conditions that you should not attempt to recover from. In most cases it is
advisable to let the program terminate when such an error is encountered.
55. What is the difference between process and thread?- Process is a program in
execution whereas thread is a separate path of execution in a program.
56. What is multithreading and what are the methods for inter-thread
communication and what is the class in which these methods are defined?-
Multithreading is the mechanism in which more than one thread run independent
of each other within the process. wait (), notify () and notifyAll() methods can be
used for inter-thread communication and these methods are in Object class. wait()
: When a thread executes a call to wait() method, it surrenders the object lock and
enters into a waiting state. notify() or notifyAll() : To remove a thread from the
waiting state, some other thread must make a call to notify() or notifyAll() method
on the same object.
57. What is the class and interface in java to create thread and which is the most
advantageous method?- Thread class and Runnable interface can be used to
create threads and using Runnable interface is the most advantageous method to
create threads because we need not extend thread class here.
58. What are the states associated in the thread?- Thread contains ready, running,
waiting and dead states.
59. What is synchronization?- Synchronization is the mechanism that ensures that
only one thread is accessed the resources at a time.
60. When you will synchronize a piece of your code?- When you expect your code
will be accessed by different threads and these threads may change a particular
data causing data corruption.
61. What is deadlock?- When two threads are waiting each other and can’t precede
the program is said to be deadlock.
62. What is daemon thread and which method is used to create the daemon
thread?- Daemon thread is a low priority thread which runs intermittently in the
back ground doing the garbage collection operation for the java runtime system.
setDaemon method is used to create a daemon thread.
63. Are there any global variables in Java, which can be accessed by other part
of your program?- No, it is not the main method in which you define variables.
Global variables is not possible because concept of encapsulation is eliminated
here.
64. What is an applet?- Applet is a dynamic and interactive program that runs inside
a web page displayed by a java capable browser.
65. What is the difference between applications and applets?- a)Application must
be run on local machine whereas applet needs no explicit installation on local
machine. b)Application must be run explicitly within a java-compatible virtual
machine whereas applet loads and runs itself automatically in a java-enabled
browser. d)Application starts execution with its main method whereas applet
starts execution with its init method. e)Application can run with or without
graphical user interface whereas applet must run within a graphical user interface.
66. How does applet recognize the height and width?- Using getParameters()
method.
67. When do you use codebase in applet?- When the applet class file is not in the
same directory, codebase is used.
68. What is the lifecycle of an applet?- init() method - Can be called when an applet
is first loaded start() method - Can be called each time an applet is started. paint()
method - Can be called when the applet is minimized or maximized. stop()
method - Can be used when the browser moves off the applet’s page. destroy()
method - Can be called when the browser is finished with the applet.
69. How do you set security in applets?- using setSecurityManager() method
70. What is an event and what are the models available for event handling?- An
event is an event object that describes a state of change in a source. In other
words, event occurs when an action is generated, like pressing button, clicking
mouse, selecting a list, etc. There are two types of models for handling events and
they are: a) event-inheritance model and b) event-delegation model
71. What are the advantages of the model over the event-inheritance model?-
The event-delegation model has two advantages over the event-inheritance model.
They are: a)It enables event handling by objects other than the ones that generate
the events. This allows a clean separation between a component’s design and its
use. b)It performs much better in applications where many events are generated.
This performance improvement is due to the fact that the event-delegation model
does not have to be repeatedly process unhandled events as is the case of the
event-inheritance.
72. What is source and listener?- source : A source is an object that generates an
event. This occurs when the internal state of that object changes in some way.
listener : A listener is an object that is notified when an event occurs. It has two
major requirements. First, it must have been registered with one or more sources
to receive notifications about specific types of events. Second, it must implement
methods to receive and process these notifications.
73. What is adapter class?- An adapter class provides an empty implementation of
all methods in an event listener interface. Adapter classes are useful when you
want to receive and process only some of the events that are handled by a
particular event listener interface. You can define a new class to act listener by
extending one of the adapter classes and implementing only those events in which
you are interested. For example, the MouseMotionAdapter class has two methods,
mouseDragged()and mouseMoved(). The signatures of these empty are exactly as
defined in the MouseMotionListener interface. If you are interested in only mouse
drag events, then you could simply extend MouseMotionAdapter and implement
mouseDragged() .
74. What is meant by controls and what are different types of controls in AWT?-
Controls are components that allow a user to interact with your application and
the AWT supports the following types of controls: Labels, Push Buttons, Check
Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are
subclasses of Component.
75. What is the difference between choice and list?- A Choice is displayed in a
compact form that requires you to pull it down to see the list of available choices
and only one item may be selected from a choice. A List may be displayed in such
a way that several list items are visible and it supports the selection of one or
more list items.
76. What is the difference between scrollbar and scrollpane?- A Scrollbar is a
Component, but not a Container whereas Scrollpane is a Conatiner and handles its
own events and perform its own scrolling.
77. What is a layout manager and what are different types of layout managers
available in java AWT?- A layout manager is an object that is used to organize
components in a container. The different layouts are available are FlowLayout,
BorderLayout, CardLayout, GridLayout and GridBagLayout.
78. How are the elements of different layouts organized?- FlowLayout: The
elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders
(North, South, East and West) and the center of a container. CardLayout: The
elements of a CardLayout are stacked, on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using
the square of a grid. GridBagLayout: The elements of a GridBagLayout are
organized according to a grid. However, the elements are of different size and
may occupy more than one row or column of the grid. In addition, the rows and
columns may have different sizes.
79. Which containers use a Border layout as their default layout?- Window,
Frame and Dialog classes use a BorderLayout as their layout.
80. Which containers use a Flow layout as their default layout?- Panel and Applet
classes use the FlowLayout as their default layout.
81. What are wrapper classes?- Wrapper classes are classes that allow primitive
types to be accessed as objects.
82. What are Vector, Hashtable, LinkedList and Enumeration?- Vector : The
Vector class provides the capability to implement a growable array of objects.
Hashtable : The Hashtable class implements a Hashtable data structure. A
Hashtable indexes and stores objects in a dictionary using hash codes as the
object’s keys. Hash codes are integer values that identify objects. LinkedList:
Removing or inserting elements in the middle of an array can be done using
LinkedList. A LinkedList stores each object in a separate link whereas an array
stores object references in consecutive locations. Enumeration: An object that
implements the Enumeration interface generates a series of elements, one at a
time. It has two methods, namely hasMoreElements() and nextElement().
HasMoreElemnts() tests if this enumeration has more elements and nextElement
method returns successive elements of the series.
83. What is the difference between set and list?- Set stores elements in an
unordered way but does not contain duplicate elements, whereas list stores
elements in an ordered way but may contain duplicate elements.
84. What is a stream and what are the types of Streams and classes of the
Streams?- A Stream is an abstraction that either produces or consumes
information. There are two types of Streams and they are: Byte Streams: Provide
a convenient means for handling input and output of bytes. Character Streams:
Provide a convenient means for handling input & output of characters. Byte
Streams classes: Are defined by using two abstract classes, namely InputStream
and OutputStream. Character Streams classes: Are defined by using two abstract
classes, namely Reader and Writer.
85. What is the difference between Reader/Writer and InputStream/Output
Stream?- The Reader/Writer class is character-oriented and the
InputStream/OutputStream class is byte-oriented.
86. What is an I/O filter?- An I/O filter is an object that reads from one stream and
writes to another, usually altering the data in some way as it is passed from one
stream to another.
87. What is serialization and deserialization?- Serialization is the process of
writing the state of an object to a byte stream. Deserialization is the process of
restoring these objects.
88. What is JDBC?- JDBC is a set of Java API for executing SQL statements. This
API consists of a set of classes and interfaces to enable programs to write pure
Java Database applications.
89. What are drivers available?- a) JDBC-ODBC Bridge driver b) Native API
Partly-Java driver c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java
driver
90. What is the difference between JDBC and ODBC?- a) OBDC is for Microsoft
and JDBC is for Java applications. b) ODBC can’t be directly used with Java
because it uses a C interface. c) ODBC makes use of pointers which have been
removed totally from Java. d) ODBC mixes simple and advanced features
together and has complex options for simple queries. But JDBC is designed to
keep things simple while allowing advanced capabilities when required. e) ODBC
requires manual installation of the ODBC driver manager and driver on all client
machines. JDBC drivers are written in Java and JDBC code is automatically
installable, secure, and portable on all platforms. f) JDBC API is a natural Java
interface and is built on ODBC. JDBC retains some of the basic features of
ODBC.
91. What are the types of JDBC Driver Models and explain them?- There are two
types of JDBC Driver Models and they are: a) Two tier model and b) Three tier
model Two tier model: In this model, Java applications interact directly with the
database. A JDBC driver is required to communicate with the particular database
management system that is being accessed. SQL statements are sent to the
database and the results are given to user. This model is referred to as
client/server configuration where user is the client and the machine that has the
database is called as the server. Three tier model: A middle tier is introduced in
this model. The functions of this model are: a) Collection of SQL statements from
the client and handing it over to the database, b) Receiving results from database
to the client and c) Maintaining control over accessing and updating of the above.
92. What are the steps involved for making a connection with a database or how
do you connect to a database?a) Loading the driver : To load the driver, Class.
forName() method is used. Class. forName(”sun. jdbc. odbc. JdbcOdbcDriver”);
When the driver is loaded, it registers itself with the java. sql. DriverManager
class as an available database driver. b) Making a connection with database: To
open a connection to a given database, DriverManager. getConnection() method is
used. Connection con = DriverManager. getConnection (”jdbc:odbc:somedb”,
“user”, “password”); c) Executing SQL statements : To execute a SQL query,
java. sql. statements class is used. createStatement() method of Connection to
obtain a new Statement object. Statement stmt = con. createStatement(); A query
that returns data can be executed using the executeQuery() method of Statement.
This method executes the statement and returns a java. sql. ResultSet that
encapsulates the retrieved data: ResultSet rs = stmt. executeQuery(”SELECT *
FROM some table”); d) Process the results : ResultSet returns one row at a time.
Next() method of ResultSet object can be called to move to the next row. The
getString() and getObject() methods are used for retrieving column values:
while(rs. next()) { String event = rs. getString(”event”); Object count = (Integer)
rs. getObject(”count”);
93. What type of driver did you use in project?- JDBC-ODBC Bridge driver (is a
driver that uses native(C language) libraries and makes calls to an existing ODBC
driver to access a database engine).
94. What are the types of statements in JDBC?- Statement: to be used
createStatement() method for executing single SQL statement PreparedStatement
— To be used preparedStatement() method for executing same SQL statement
over and over. CallableStatement — To be used prepareCall() method for
multiple SQL statements over and over.
95. What is stored procedure?- Stored procedure is a group of SQL statements that
forms a logical unit and performs a particular task. Stored Procedures are used to
encapsulate a set of operations or queries to execute on database. Stored
procedures can be compiled and executed with different parameters and results
and may have any combination of input/output parameters.
96. How to create and call stored procedures?- To create stored procedures: Create
procedure procedurename (specify in, out and in out parameters) BEGIN Any
multiple SQL statement; END; To call stored procedures: CallableStatement csmt
= con. prepareCall(”{call procedure name(?,?)}”); csmt.
registerOutParameter(column no. , data type); csmt. setInt(column no. , column
name) csmt. execute();
97. What is servlet?- Servlets are modules that extend request/response-oriented
servers, such as java-enabled web servers. For example, a servlet might be
responsible for taking data in an HTML order-entry form and applying the
business logic used to update a company’s order database.
98. What are the classes and interfaces for servlets?- There are two packages in
servlets and they are javax. servlet and
99. What is the difference between an applet and a servlet?- a) Servlets are to
servers what applets are to browsers. b) Applets must have graphical user
interfaces whereas servlets have no graphical user interfaces.
100. What is the difference between doPost and doGet methods?- a)
doGet() method is used to get information, while doPost() method is used for
posting information. b) doGet() requests can’t send large amount of information
and is limited to 240-255 characters. However, doPost()requests passes all of its
data, of unlimited length. c) A doGet() request is appended to the request URL in
a query string and this allows the exchange is visible to the client, whereas a
doPost() request passes directly over the socket connection as part of its HTTP
request body and the exchange are invisible to the client.
101. What is the life cycle of a servlet?- Each Servlet has the same life cycle:
a) A server loads and initializes the servlet by init () method. b) The servlet
handles zero or more client’s requests through service() method. c) The server
removes the servlet through destroy() method.
102. Who is loading the init() method of servlet?- Web server
103. What are the different servers available for developing and deploying
Servlets?- a) Java Web Server b) JRun g) Apache Server h) Netscape Information
Server i) Web Logic
104. How many ways can we track client and what are they?- The servlet
API provides two ways to track client state and they are: a) Using Session
tracking and b) Using Cookies.
105. What is session tracking and how do you track a user session in
servlets?- Session tracking is a mechanism that servlets use to maintain state
about a series requests from the same user across some period of time. The
methods used for session tracking are: a) User Authentication - occurs when a
web server restricts access to some of its resources to only those clients that log in
using a recognized username and password. b) Hidden form fields - fields are
added to an HTML form that are not displayed in the client’s browser. When the
form containing the fields is submitted, the fields are sent back to the server. c)
URL rewriting - every URL that the user clicks on is dynamically modified or
rewritten to include extra information. The extra information can be in the form of
extra path information, added parameters or some custom, server-specific URL
change. d) Cookies - a bit of information that is sent by a web server to a browser
and which can later be read back from that browser. e) HttpSession- places a limit
on the number of sessions that can exist in memory. This limit is set in the
session. maxresidents property.
106. What is Server-Side Includes (SSI)?- Server-Side Includes allows
embedding servlets within HTML pages using a special servlet tag. In many
servlets that support servlets, a page can be processed by the server to include
output from servlets at certain points inside the HTML page. This is accomplished
using a special internal SSINCLUDE, which processes the servlet tags.
SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is
requested. So HTML files that include server-side includes must be stored with an
. shtml extension.
107. What are cookies and how will you use them?- Cookies are a
mechanism that a servlet uses to have a client hold a small amount of state-
information associated with the user. a) Create a cookie with the Cookie
constructor: public Cookie(String name, String value) b) A servlet can send a
cookie to the client by passing a Cookie object to the addCookie() method of
HttpServletResponse: public void HttpServletResponse. addCookie(Cookie
cookie) c) A servlet retrieves cookies by calling the getCookies() method of
HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().
108. Is it possible to communicate from an applet to servlet and how many
ways and how?- Yes, there are three ways to communicate from an applet to
servlet and they are: a) HTTP Communication(Text-based and object-based) b)
Socket Communication c) RMI Communication
109. What is connection pooling?- With servlets, opening a database
connection is a major bottleneck because we are creating and tearing down a new
connection for every page request and the time taken to create connection will be
more. Creating a connection pool is an ideal approach for a complicated servlet.
With a connection pool, we can duplicate only the resources we need to duplicate
rather than the entire servlet. A connection pool can also intelligently manage the
size of the pool and make sure each connection remains valid. A number of
connection pool packages are currently available. Some like DbConnectionBroker
are freely available from Java Exchange Works by creating an object that
dispenses connections and connection Ids on request. The ConnectionPool class
maintains a Hastable, using Connection objects as keys and Boolean values as
stored values. The Boolean value indicates whether a connection is in use or not.
A program calls getConnection() method of the ConnectionPool for getting
Connection object it can use; it calls returnConnection() to give the connection
back to the pool.
110. Why should we go for interservlet communication?- Servlets running
together in the same server communicate with each other in several ways. The
three major reasons to use interservlet communication are: a) Direct servlet
manipulation - allows to gain access to the other currently loaded servlets and
perform certain tasks (through the ServletContext object) b) Servlet reuse - allows
the servlet to reuse the public methods of another servlet. c) Servlet collaboration
- requires to communicate with each other by sharing specific information
(through method invocation)
111. Is it possible to call servlet with parameters in the URL?- Yes. You can
call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).
112. What is Servlet chaining?- Servlet chaining is a technique in which two
or more servlets can cooperate in servicing a single request. In servlet chaining,
one servlet’s output is piped to the next servlet’s input. This process continues
until the last servlet is reached. Its output is then sent back to the client.
113. How do servlets handle multiple simultaneous requests?- The server
has multiple threads that are available to handle requests. When a request comes
in, it is assigned to a thread, which calls a service method (for example: doGet(),
doPost() and service()) of the servlet. For this reason, a single servlet object can
have its service methods called by many threads at once.
114. What is the difference between TCP/IP and UDP?- TCP/IP is a two-
way communication between the client and the server and it is a reliable and there
is a confirmation regarding reaching the message to the destination. It is like a
phone call. UDP is a one-way communication only between the client and the
server and it is not a reliable and there is no confirmation regarding reaching the
message to the destination. It is like a postal mail.
115. What is Inet address?- Every computer connected to a network has an IP
address. An IP address is a number that uniquely identifies each computer on the
Net. An IP address is a 32-bit number.
116. What is Domain Naming Service(DNS)?- It is very difficult to
remember a set of numbers(IP address) to connect to the Internet. The Domain
Naming Service(DNS) is used to overcome this problem. It maps one particular
IP address to a string of characters. For example, www. mascom. com implies
com is the domain name reserved for US commercial sites, moscom is the name
of the company and www is the name of the specific computer, which is
mascom’s server.
117. What is URL?- URL stands for Uniform Resource Locator and it points
to resource files on the Internet. URL has four components: http://www. address.
com:80/index.html, where http - protocol name, address - IP address or host
name, 80 - port number and index.html - file path.
118. What is RMI and steps involved in developing an RMI object?-
Remote Method Invocation (RMI) allows java object that executes on one
machine and to invoke the method of a Java object to execute on another
machine. The steps involved in developing an RMI object are: a) Define the
interfaces b) Implementing these interfaces c) Compile the interfaces and their
implementations with the java compiler d) Compile the server implementation
with RMI compiler e) Run the RMI registry f) Run the application
119. What is RMI architecture?- RMI architecture consists of four layers and
each layer performs specific functions: a) Application layer - contains the actual
object definition. b) Proxy layer - consists of stub and skeleton. c) Remote
Reference layer - gets the stream of bytes from the transport layer and sends it to
the proxy layer. d) Transportation layer - responsible for handling the actual
machine-to-machine communication.
120. what is UnicastRemoteObject?- All remote objects must extend
UnicastRemoteObject, which provides functionality that is needed to make
objects available from remote machines.
121. Explain the methods, rebind() and lookup() in Naming class?- rebind()
of the Naming class(found in java. rmi) is used to update the RMI registry on the
server machine. Naming. rebind(”AddSever”, AddServerImpl); lookup() of the
Naming class accepts one argument, the rmi URL and returns a reference to an
object of type AddServerImpl.
122. What is a Java Bean?- A Java Bean is a software component that has
been designed to be reusable in a variety of different environments.
123. What is a Jar file?- Jar file allows to efficiently deploying a set of classes
and their associated resources. The elements in a jar file are compressed, which
makes downloading a Jar file much faster than separately downloading several
uncompressed files. The package java. util. zip contains classes that read and
write jar files.
124. What is BDK?- BDK, Bean Development Kit is a tool that enables to
create, configure and connect a set of set of Beans and it can be used to test Beans
without writing a code.
125. What is JSP?- JSP is a dynamic scripting capability for web pages that
allows Java as well as a few special tags to be embedded into a web file
(HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web
server that the file is a JSP files. JSP is a server side technology - you can’t do any
client side validation with it. The advantages are: a) The JSP assists in making the
HTML more functional. Servlets on the other hand allow outputting of HTML but
it is a tedious process. b) It is easy to make a change and then let the JSP
capability of the web server you are using deal with compiling it into a servlet and
running it.
126. What are JSP scripting elements?- JSP scripting elements lets to insert
Java code into the servlet that will be generated from the current JSP page. There
are three forms: a) Expressions of the form <%= expression %> that are evaluated
and inserted into the output, b) Scriptlets of the form<% code %>that are inserted
into the servlet’s service method, and c) Declarations of the form <%! Code
%>that are inserted into the body of the servlet class, outside of any existing
methods.
127. What are JSP Directives?- A JSP directive affects the overall structure
of the servlet class. It usually has the following form:<%@ directive
attribute=”value” %> However, you can also combine multiple attribute settings
for a single directive, as follows:<%@ directive attribute1=”value1″ attribute
2=”value2″ . . . attributeN =”valueN” %> There are two main types of directive:
page, which lets to do things like import classes, customize the servlet superclass,
and the like; and include, which lets to insert a file into the servlet class at the
time the JSP file is translated into a servlet
128. What are Predefined variables or implicit objects?- To simplify code in
JSP expressions and scriptlets, we can use eight automatically defined variables,
sometimes called implicit objects. They are request, response, out, session,
application, config, pageContext, and page.
129. What are JSP ACTIONS?- JSP actions use constructs in XML syntax to
control the behavior of the servlet engine. You can dynamically insert a file, reuse
JavaBeans components, forward the user to another page, or generate HTML for
the Java plugin. Available actions include: jsp:include - Include a file at the time
the page is requested. jsp:useBean - Find or instantiate a JavaBean.
jsp:setProperty - Set the property of a JavaBean. jsp:getProperty - Insert the
property of a JavaBean into the output. jsp:forward - Forward the requester to a
newpage. Jsp: plugin - Generate browser-specific code that makes an OBJECT or
EMBED
130. How do you pass data (including JavaBeans) to a JSP from a servlet?-
(1) Request Lifetime: Using this technique to pass beans, a request dispatcher
(using either “include” or forward”) can be called. This bean will disappear after
processing this request has been completed. Servlet: request.
setAttribute(”theBean”, myBean); RequestDispatcher rd = getServletContext().
getRequestDispatcher(”thepage. jsp”); rd. forward(request, response); JSP
PAGE:<jsp: useBean id=”theBean” scope=”request” class=”. . . . . ” />(2) Session
Lifetime: Using this technique to pass beans that are relevant to a particular
session (such as in individual user login) over a number of requests. This bean
will disappear when the session is invalidated or it times out, or when you remove
it. Servlet: HttpSession session = request. getSession(true); session.
putValue(”theBean”, myBean); /* You can do a request dispatcher here, or just let
the bean be visible on the next request */ JSP Page:<jsp:useBean id=”theBean”
scope=”session” class=”. . . ” /> 3) Application Lifetime: Using this technique to
pass beans that are relevant to all servlets and JSP pages in a particular app, for all
users. For example, I use this to make a JDBC connection pool object available to
the various servlets and JSP pages in my apps. This bean will disappear when the
servlet engine is shut down, or when you remove it. Servlet: GetServletContext().
setAttribute(”theBean”, myBean); JSP PAGE:<jsp:useBean id=”theBean”
scope=”application” class=”. . . ” />
131. How can I set a cookie in JSP?- response. setHeader(”Set-Cookie”,
“cookie string”); To give the response-object to a bean, write a method
setResponse (HttpServletResponse response) - to the bean, and in jsp-file:<%
bean. setResponse (response); %>
132. How can I delete a cookie with JSP?- Say that I have a cookie called
“foo, ” that I set a while ago & I want it to go away. I simply: <% Cookie
killCookie = new Cookie(”foo”, null); KillCookie. setPath(”/”); killCookie.
setMaxAge(0); response. addCookie(killCookie); %>
133. How are Servlets and JSP Pages related?- JSP pages are focused around
HTML (or XML) with Java codes and JSP tags inside them. When a web server
that has JSP support is asked for a JSP page, it checks to see if it has already
compiled the page into a servlet. Thus, JSP pages become servlets and are
transformed into pure Java and then compiled, loaded into the server and
executed.
134. Is “abc” a primitive value? - The String literal “abc” is not a primitive
value. It is a String object.
135. What restrictions are placed on the values of each case of a switch
statement? - During compilation, the values of each case of a switch statement
must evaluate to a value that can be promoted to an int value.
136. What modifiers may be used with an interface declaration? - An
interface may be declared as public or abstract.
137. Is a class a subclass of itself? - A class is a subclass of itself.
138. What is the difference between a while statement and a do statement?
- A while statement checks at the beginning of a loop to see whether the next loop
iteration should occur. A do statement checks at the end of a loop to see whether
the next iteration of a loop should occur. The do statement will always execute the
body of a loop at least once.
139. What modifiers can be used with a local inner class? - A local inner
class may be final or abstract.
140. What is the purpose of the File class? - The File class is used to create
objects that provide access to the files and directories of a local file system.
141. Can an exception be rethrown? - Yes, an exception can be rethrown.
142. When does the compiler supply a default constructor for a class? -
The compiler supplies a default constructor for a class if no other constructors are
provided.
143. If a method is declared as protected, where may the method be
accessed? - A protected method may only be accessed by classes or interfaces of
the same package or by subclasses of the class in which it is declared.
144. Which non-Unicode letter characters may be used as the first
character of an identifier? - The non-Unicode letter characters $ and _ may
appear as the first character of an identifier
145. What restrictions are placed on method overloading? - Two methods
may not have the same name and argument list but different return types.
146. What is casting? - There are two types of casting, casting between
primitive numeric types and casting between object references. Casting between
numeric types is used to convert larger values, such as double values, to smaller
values, such as byte values. Casting between object references is used to refer to
an object by a compatible class, interface, or array type reference.
147. What is the return type of a program’s main() method? - A program’s
main() method has a void return type.
148. What class of exceptions are generated by the Java run-time system? -
The Java runtime system generates RuntimeException and Error exceptions.
149. What class allows you to read objects directly from a stream? - The
ObjectInputStream class supports the reading of objects from input streams.
150. What is the difference between a field variable and a local variable? -
A field variable is a variable that is declared as a member of a class. A local
variable is a variable that is declared local to a method.
151. How are this() and super() used with constructors? - this() is used to
invoke a constructor of the same class. super() is used to invoke a superclass
constructor.
152. What is the relationship between a method’s throws clause and the
exceptions that can be thrown during the method’s execution? - A method’s
throws clause must declare any checked exceptions that are not caught within the
body of the method.
153. Why are the methods of the Math class static? - So they can be invoked
as if they are a mathematical code library.
154. What are the legal operands of the instanceof operator? - The left
operand is an object reference or null value and the right operand is a class,
interface, or array type.
155. What an I/O filter? - An I/O filter is an object that reads from one stream
and writes to another, usually altering the data in some way as it is passed from
one stream to another.
156. If an object is garbage collected, can it become reachable again? -
Once an object is garbage collected, it ceases to exist. It can no longer become
reachable again.
157. What are E and PI? - E is the base of the natural logarithm and PI is
mathematical value pi.
158. Are true and false keywords? - The values true and false are not
keywords.
159. What is the difference between the File and RandomAccessFile
classes? - The File class encapsulates the files and directories of the local file
system. The RandomAccessFile class provides the methods needed to directly
access data contained in any part of a file.
160. What happens when you add a double value to a String? - The result is
a String object.
161. What is your platform’s default character encoding? - If you are
running Java on English Windows platforms, it is probably Cp1252. If you are
running Java on English Solaris platforms, it is most likely 8859_1.
162. Which package is always imported by default? - The java.lang package
is always imported by default.
163. What interface must an object implement before it can be written to a
stream as an object? - An object must implement the Serializable or
Externalizable interface before it can be written to a stream as an object.
164. How can my application get to know when a HttpSession is removed?
- Define a Class HttpSessionNotifier which implements
HttpSessionBindingListener and implement the functionality what you need in
valueUnbound() method. Create an instance of that class and put that instance in
HttpSession.
165. Whats the difference between notify() and notifyAll()? - notify() is
used to unblock one waiting thread; notifyAll() is used to unblock all of them.
Using notify() is preferable (for efficiency) when only one blocked thread can
benefit from the change (for example, when freeing a buffer back into a pool).
notifyAll() is necessary (for correctness) if multiple threads should resume (for
example, when releasing a “writer” lock on a file might permit all “readers” to
resume).
166. Why can’t I say just abs() or sin() instead of Math.abs() and
Math.sin()? - The import statement does not bring methods into your local name
space. It lets you abbreviate class names, but not get rid of them altogether. That’s
just the way it works, you’ll get used to it. It’s really a lot safer this way.
However, there is actually a little trick you can use in some cases that gets you
what you want. If your top-level class doesn’t need to inherit from anything else,
make it inherit from java.lang.Math. That *does* bring all the methods into your
local name space. But you can’t use this trick in an applet, because you have to
inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at
all, because Math is a “final” class which means it can’t be extended.
167. Why are there no global variables in Java? - Global variables are
considered bad form for a variety of reasons: Adding state variables breaks
referential transparency (you no longer can understand a statement or expression
on its own: you need to understand it in the context of the settings of the global
variables), State variables lessen the cohesion of a program: you need to know
more to understand how something works. A major point of Object-Oriented
programming is to break up global state into more easily understood collections of
local state, When you add one variable, you limit the use of your program to one
instance. What you thought was global, someone else might think of as local: they
may want to run two copies of your program at once. For these reasons, Java
decided to ban global variables.
168. What does it mean that a class or member is final? - A final class can
no longer be subclassed. Mostly this is done for security reasons with basic
classes like String and Integer. It also allows the compiler to make some
optimizations, and makes thread safety a little easier to achieve. Methods may be
declared final as well. This means they may not be overridden in a subclass.
Fields can be declared final, too. However, this has a completely different
meaning. A final field cannot be changed after it’s initialized, and it must include
an initializer statement where it’s declared. For example, public final double c =
2.998; It’s also possible to make a static field final to get the effect of C++’s const
statement or some uses of C’s #define, e.g. public static final double c = 2.998;
169. What does it mean that a method or class is abstract? - An abstract
class cannot be instantiated. Only its subclasses can be instantiated. You indicate
that a class is abstract with the abstract keyword like this:
170. public abstract class Container extends Component {

Abstract classes may contain abstract methods. A method declared abstract is not
actually implemented in the current class. It exists only to be overridden in
subclasses. It has no body. For example,

public abstract float price();

Abstract methods may only be included in abstract classes. However, an abstract


class is not required to have any abstract methods, though most of them do. Each
subclass of an abstract class must override the abstract methods of its superclasses
or itself be declared abstract.

171. What is a transient variable? - transient variable is a variable that may


not be serialized.
172. How are Observer and Observable used? - Objects that subclass the
Observable class maintain a list of observers. When an Observable object is
updated it invokes the update() method of each of its observers to notify the
observers that it has changed state. The Observer interface is implemented by
objects that observe Observable objects.
173. Can a lock be acquired on a class? - Yes, a lock can be acquired on a
class. This lock is acquired on the class’s Class object.
174. What state does a thread enter when it terminates its processing? -
When a thread terminates its processing, it enters the dead state.
175. How does Java handle integer overflows and underflows? - It uses
those low order bytes of the result that can fit into the size of the type allowed by
the operation.
176. What is the difference between the >> and >>> operators? - The >>
operator carries the sign bit when shifting right. The >>> zero-fills bits that have
been shifted out.
177. Is sizeof a keyword? - The sizeof operator is not a keyword.
178. Does garbage collection guarantee that a program will not run out of
memory? - Garbage collection does not guarantee that a program will not run out
of memory. It is possible for programs to use up memory resources faster than
they are garbage collected. It is also possible for programs to create objects that
are not subject to garbage collection
179. Can an object’s finalize() method be invoked while it is reachable? -
An object’s finalize() method cannot be invoked by the garbage collector while
the object is still reachable. However, an object’s finalize() method may be
invoked by other objects.
180. What value does readLine() return when it has reached the end of a
file? - The readLine() method returns null when it has reached the end of a file.
181. Can a for statement loop indefinitely? - Yes, a for statement can loop
indefinitely. For example, consider the following: for(;;) ;
182. To what value is a variable of the String type automatically
initialized? - The default value of an String type is null.
183. What is a task’s priority and how is it used in scheduling? - A task’s
priority is an integer value that identifies the relative order in which it should be
executed with respect to other tasks. The scheduler attempts to schedule higher
priority tasks before lower priority tasks.
184. What is the range of the short type? - The range of the short type is -
(2^15) to 2^15 - 1.
185. What is the purpose of garbage collection? - The purpose of garbage
collection is to identify and discard objects that are no longer needed by a
program so that their resources may be reclaimed and reused.
186. What do you understand by private, protected and public? - These are
accessibility modifiers. Private is the most restrictive, while public is the least
restrictive. There is no real difference between protected and the default type (also
known as package protected) within the context of the same package, however the
protected keyword allows visibility to a derived class in a different package.
187. What is Downcasting ? - Downcasting is the casting from a general to a
more specific type, i.e. casting down the hierarchy
188. Can a method be overloaded based on different return type but same
argument type ? - No, because the methods can be called without using their
return type in which case there is ambiquity for the compiler
189. What happens to a static var that is defined within a method of a class
? - Can’t do it. You’ll get a compilation error
190. How many static init can you have ? - As many as you want, but the
static initializers and class variable initializers are executed in textual order and
may not refer to class variables declared in the class whose declarations appear
textually after the use, even though these class variables are in scope.
191. What is the difference amongst JVM Spec, JVM Implementation,
JVM Runtime ? - The JVM spec is the blueprint for the JVM generated and
owned by Sun. The JVM implementation is the actual implementation of the spec
by a vendor and the JVM runtime is the actual running instance of a JVM
implementation
192. Describe what happens when an object is created in Java? - Several
things happen in a particular order to ensure the object is constructed properly:
Memory is allocated from heap to hold all instance variables and implementation-
specific data of the object and its superclasses. Implemenation-specific data
includes pointers to class and method data. The instance variables of the objects
are initialized to their default values. The constructor for the most derived class is
invoked. The first thing a constructor does is call the consctructor for its
superclasses. This process continues until the constrcutor for java.lang.Object is
called, as java.lang.Object is the base class for all objects in java. Before the body
of the constructor is executed, all instance variable initializers and initialization
blocks are executed. Then the body of the constructor is executed. Thus, the
constructor for the base class completes first and constructor for the most derived
class completes last.
193. What does the “final” keyword mean in front of a variable? A
method? A class? - FINAL for a variable: value is constant. FINAL for a
method: cannot be overridden. FINAL for a class: cannot be derived
194. What is the difference between instanceof and isInstance? - instanceof
is used to check to see if an object can be cast into a specified type without
throwing a cast class exception. isInstance() Determines if the specified Object is
assignment-compatible with the object represented by this Class. This method is
the dynamic equivalent of the Java language instanceof operator. The method
returns true if the specified Object argument is non-null and can be cast to the
reference type represented by this Class object without raising a
ClassCastException. It returns false otherwise.
195. Why does it take so much time to access an Applet having Swing
Components the first time? - Because behind every swing component are many
Java objects and resources. This takes time to create them in memory. JDK 1.3
from Sun has some improvements which may lead to faster execution of Swing
applications.
196. Can there be an abstract class with no abstract methods in it? - Yes
197. Can an Interface be final? - No
198. Can an Interface have an inner class? - Yes.
199. public interface abc
200. {
201. static int i=0; void dd();
202. class a1
203. {
204. a1()
205. {
206. int j;
207. System.out.println("inside");
208. };
209. public static void main(String a1[])
210. {
211. System.out.println("in
interfia");
212. }
213. }
214. }
215. Can we define private and protected modifiers for variables in
interfaces? - No
216. What is Externalizable? - Externalizable is an Interface that extends
Serializable Interface. And sends data into Streams in Compressed Format. It has
two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
217. What modifiers are allowed for methods in an Interface? - Only public
and abstract modifiers are allowed for methods in interfaces.
218. What is a local, member and a class variable? - Variables declared
within a method are “local” variables. Variables declared within the class i.e not
within any methods are “member” variables (global variables). Variables declared
within the class i.e not within any methods and are defined as “static” are class
variables
219. What are the different identifier states of a Thread? - The different
identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread,
CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor
lock, MS - Thread suspended waiting on a monitor lock
220. What are some alternatives to inheritance? - Delegation is an
alternative to inheritance. Delegation means that you include an instance of
another class as an instance variable, and forward messages to the instance. It is
often safer than inheritance because it forces you to think about each message you
forward, because the instance is of a known class, rather than a new class, and
because it doesn’t force you to accept all the methods of the super class: you can
provide only the methods that really make sense. On the other hand, it makes you
write more code, and it is harder to re-use (because it is not a subclass).
221. Why isn’t there operator overloading? - Because C++ has proven by
example that operator overloading makes code almost impossible to maintain. In
fact there very nearly wasn’t even method overloading in Java, but it was thought
that this was too useful for some very basic methods like print(). Note that some
of the classes like DataOutputStream have unoverloaded methods like writeInt()
and writeByte().
222. What does it mean that a method or field is “static”? - Static variables
and methods are instantiated only once per class. In other words they are class
variables, not instance variables. If you change the value of a static variable in a
particular object, the value of that variable changes for all instances of that class.
Static methods can be referenced with the name of the class rather than the name
of a particular object of the class (though that works too). That’s how library
methods like System.out.println() work. out is a static field in the
java.lang.System class.
223. How do I convert a numeric IP address like 192.18.97.39 into a
hostname like java.sun.com?
224. String hostname =
InetAddress.getByName("192.18.97.39").getHostName();
225. Difference between JRE/JVM/JDK?
226. Why do threads block on I/O? - Threads block on i/o (that is enters the
waiting state) so that other threads may execute while the I/O operation is
performed.
227. What is synchronization and why is it important? - 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 object while another thread is in the process of using or
updating that object’s value. This often leads to significant errors.
228. Is null a keyword? - The null value is not a keyword.
229. Which characters may be used as the second character of an
identifier,but not as the first character of an identifier? - The digits 0 through
9 may not be used as the first character of an identifier but they may be used after
the first character of an identifier.
230. What modifiers may be used with an inner class that is a member of
an outer class? - A (non-local) inner class may be declared as public, protected,
private, static, final, or abstract.
231. How many bits are used to represent Unicode, ASCII, UTF-16, and
UTF-8 characters? - Unicode requires 16 bits and ASCII require 7 bits.
Although the ASCII character set uses only 7 bits, it is usually represented as 8
bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses
16-bit and larger bit patterns.
232. What are wrapped classes? - Wrapped classes are classes that allow
primitive types to be accessed as objects.
233. What restrictions are placed on the location of a package statement
within a source code file? - A package statement must appear as the first line in a
source code file (excluding blank lines and comments).
234. What is the difference between preemptive scheduling and time
slicing? - Under preemptive scheduling, the highest priority task executes until it
enters the waiting or dead states or a higher priority task comes into existence.
Under time slicing, a task executes for a predefined slice of time and then reenters
the pool of ready tasks. The scheduler then determines which task should execute
next, based on priority and other factors.
235. What is a native method? - A native method is a method that is
implemented in a language other than Java.
236. What are order of precedence and associativity, and how are they
used? - Order of precedence determines the order in which operators are
evaluated in expressions. Associatity determines whether an expression is
evaluated left-to-right or right-to-left
237. What is the catch or declare rule for method declarations? - If a
checked exception may be thrown within the body of a method, the method must
either catch the exception or declare it in its throws clause.
238. Can an anonymous class be declared as implementing an interface
and extending a class? - An anonymous class may implement an interface or
extend a superclass, but may not be declared to do both.
239. What is the range of the char type? - The range of the char type is 0 to
2^16 - 1.
240. What is garbage collection? What is the process that is responsible for
doing that in java? - Reclaiming the unused memory by the invalid objects.
Garbage collector is responsible for this process
241. What kind of thread is the Garbage collector thread? - It is a daemon
thread.
242. What is a daemon thread? - These are the threads which can run without
user intervention. The JVM can exit when there are daemon thread by killing
them abruptly.
243. How will you invoke any external process in Java? -
Runtime.getRuntime().exec(….)
244. What is the finalize method do? - Before the invalid objects get garbage
collected, the JVM give the user a chance to clean up some resources before it got
garbage collected.
245. What is mutable object and immutable object? - If a object value is
changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you
are not allowed to change the value of an object, it is immutable object. (Ex.,
String, Integer, Float, …)
246. What is the basic difference between string and stringbuffer object? -
String is an immutable object. StringBuffer is a mutable object.
247. What is the purpose of Void class? - The Void class is an uninstantiable
placeholder class to hold a reference to the Class object representing the primitive
Java type void.
248. What is reflection? - Reflection allows programmatic access to
information about the fields, methods and constructors of loaded classes, and the
use reflected fields, methods, and constructors to operate on their underlying
counterparts on objects, within security restrictions.
249. What is the base class for Error and Exception? - Throwable
250. What is the byte range? -128 to 127
251. What is the implementation of destroy method in java.. is it native or
java code? - This method is not implemented.
252. What is a package? - To group set of classes into a single unit is known
as packaging. Packages provides wide namespace ability.
253. What are the approaches that you will follow for making a program
very efficient? - By avoiding too much of static methods avoiding the excessive
and unnecessary use of synchronized methods Selection of related classes based
on the application (meaning synchronized classes for multiuser and non-
synchronized classes for single user) Usage of appropriate design patterns Using
cache methodologies for remote invocations Avoiding creation of variables within
a loop and lot more.
254. What is a DatabaseMetaData? - Comprehensive information about the
database as a whole.
255. What is Locale? - A Locale object represents a specific geographical,
political, or cultural region
256. How will you load a specific locale? - Using
ResourceBundle.getBundle(…);
257. What is JIT and its use? - Really, just a very fast compiler… In this
incarnation, pretty much a one-pass compiler — no offline computations. So you
can’t look at the whole method, rank the expressions according to which ones are
re-used the most, and then generate code. In theory terms, it’s an on-line problem.
258. Is JVM a compiler or an interpreter? - Interpreter
259. When you think about optimization, what is the best way to findout
the time/memory consuming process? - Using profiler
260. What is the purpose of assert keyword used in JDK1.4.x? - In order to
validate certain expressions. It effectively replaces the if block and automatically
throws the AssertionError on failure. This keyword should be used for the critical
arguments. Meaning, without that the method does nothing.
261. How will you get the platform dependent values like line separator,
path separator, etc., ? - Using Sytem.getProperty(…) (line.separator,
path.separator, …)
262. What is skeleton and stub? what is the purpose of those? - Stub is a
client side representation of the server, which takes care of communicating with
the remote server. Skeleton is the server side representation. But that is no more in
use… it is deprecated long before in JDK.
263. What is the final keyword denotes? - final keyword denotes that it is the
final implementation for that method or variable or class. You can’t override that
method/variable/class any more.
264. What is the significance of ListIterator? - You can iterate back and
forth.
265. What is the major difference between LinkedList and ArrayList? -
LinkedList are meant for sequential accessing. ArrayList are meant for random
accessing.
266. What is nested class? - If all the methods of a inner class is static then it
is a nested class.
267. What is inner class? - If the methods of the inner class can only be
accessed via the instance of the inner class, then it is called inner class.
268. What is composition? - Holding the reference of the other class within
some other class is known as composition.
269. What is aggregation? - It is a special type of composition. If you expose
all the methods of a composite class and route the method call to the composite
method through its reference, then it is called aggregation.
270. What are the methods in Object? - clone, equals, wait, finalize,
getClass, hashCode, notify, notifyAll, toString
271. Can you instantiate the Math class? - You can’t instantiate the math
class. All the methods in this class are static. And the constructor is not public.
272. What is singleton? - It is one of the design pattern. This falls in the
creational pattern of the design pattern. There will be only one instance for that
entire JVM. You can achieve this by having the private constructor in the class.
For eg., public class Singleton { private static final Singleton s = new Singleton();
private Singleton() { } public static Singleton getInstance() { return s; } // all non
static methods … }
273. What is DriverManager? - The basic service to manage set of JDBC
drivers.
274. What is Class.forName() does and how it is useful? - It loads the class
into the ClassLoader. It returns the Class. Using that you can get the instance
( “class-instance”.newInstance() ).
275. Inq adds a question: Expain the reason for each keyword of

public static void main(String args[])

1. What is the Collections API? - The Collections API is a set of classes and
interfaces that support operations on collections of objects
2. What is the List interface? - The List interface provides support for ordered
collections of objects.
3. What is the Vector class? - The Vector class provides the capability to
implement a growable array of objects
4. What is an Iterator interface? - The Iterator interface is used to step through the
elements of a Collection
5. Which java.util classes and interfaces support event handling? - The
EventObject class and the EventListener interface support event processing
6. What is the GregorianCalendar class? - The GregorianCalendar provides
support for traditional Western calendars
7. What is the Locale class? - The Locale class is used to tailor program output to
the conventions of a particular geographic, political, or cultural region
8. What is the SimpleTimeZone class? - The SimpleTimeZone class provides
support for a Gregorian calendar
9. What is the Map interface? - The Map interface replaces the JDK 1.1 Dictionary
class and is used associate keys with values
10. What is the highest-level event class of the event-delegation model? - The
java.util.EventObject class is the highest-level class in the event-delegation class
hierarchy
11. What is the Collection interface? - The Collection interface provides support for
the implementation of a mathematical bag - an unordered collection of objects
that may contain duplicates
12. What is the Set interface? - The Set interface provides methods for accessing the
elements of a finite mathematical set. Sets do not allow duplicate elements
13. What is the purpose of the enableEvents() method? - The enableEvents()
method is used to enable an event for a particular object. Normally, an event is
enabled when a listener is added to an object for a particular event. The
enableEvents() method is used by objects that handle events by overriding their
event-dispatch methods.
14. What is the ResourceBundle class? - The ResourceBundle class is used to store
locale-specific resources that can be loaded by a program to tailor the program’s
appearance to the particular locale in which it is being run.
15. What is the difference between yielding and sleeping? - When a task invokes
its yield() method, it returns to the ready state. When a task invokes its sleep()
method, it returns to the waiting state.
16. When a thread blocks on I/O, what state does it enter? - A thread enters the
waiting state when it blocks on I/O.
17. When a thread is created and started, what is its initial state? - A thread is in
the ready state after it has been created and started.
18. What invokes a thread’s run() method? - After a thread is started, via its start()
method or that of the Thread class, the JVM invokes the thread’s run() method
when the thread is initially executed.
19. What method is invoked to cause an object to begin executing as a separate
thread? - The start() method of the Thread class is invoked to cause an object to
begin executing as a separate thread.
20. What is the purpose of the wait(), notify(), and notifyAll() methods? - The
wait(),notify(), and notifyAll() methods are used to provide an efficient way for
threads to wait for a shared resource. When a thread executes an object’s wait()
method, it enters the waiting state. It only enters the ready state after another
thread invokes the object’s notify() or notifyAll() methods.
21. What are the high-level thread states? - The high-level thread states are ready,
running, waiting, and dead
22. What happens when a thread cannot acquire a lock on an object? - If a thread
attempts to execute a synchronized method or synchronized statement and is
unable to acquire an object’s lock, it enters the waiting state until the lock
becomes available.
23. How does multithreading take place on a computer with a single CPU? - The
operating system’s task scheduler allocates execution time to multiple tasks. By
quickly switching between executing tasks, it creates the impression that tasks
execute sequentially.
24. What happens when you invoke a thread’s interrupt method while it is
sleeping or waiting? - When a task’s interrupt() method is executed, the task
enters the ready state. The next time the task enters the running state, an
InterruptedException is thrown.
25. What state is a thread in when it is executing? - An executing thread is in the
running state
26. What are three ways in which a thread can enter the waiting state? - A thread
can enter the waiting state by invoking its sleep() method, by blocking on I/O, by
unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s
wait() method. It can also enter the waiting state by invoking its (deprecated)
suspend() method.
27. What method must be implemented by all threads? - All tasks must implement
the run() method, whether they are a subclass of Thread or implement the
Runnable interface.
28. What are the two basic ways in which classes that can be run as threads may
be defined? - A thread class may be declared as a subclass of Thread, or it may
implement the Runnable interface.
29. How can you store international / Unicode characters into a cookie? - One
way is, before storing the cookie URLEncode it. URLEnocder.encoder(str); And
use URLDecoder.decode(str) when you get the stored cookie.

1. What is a Marker Interface? - An interface with no methods. Example:


Serializable, Remote, Cloneable
2. What interface do you implement to do the sorting? - Comparable
3. What is the eligibility for a object to get cloned? - It must implement the
Cloneable interface
4. What is the purpose of abstract class? - It is not an instantiable class. It
provides the concrete implementation for some/all the methods. So that they can
reuse the concrete functionality by inheriting the abstract class.
5. What is the difference between interface and abstract class? - Abstract class
defined with methods. Interface will declare only the methods. Abstract classes
are very much useful when there is a some functionality across various classes.
Interfaces are well suited for the classes which varies in functionality but with the
same method signatures.
6. What do you mean by RMI and how it is useful? - RMI is a remote method
invocation. Using RMI, you can work with remote object. The function calls are
as though you are invoking a local variable. So it gives you a impression that you
are working really with a object that resides within your own JVM though it is
somewhere.
7. What is the protocol used by RMI? - RMI-IIOP
8. What is a hashCode? - hash code value for this object which is unique for every
object.
9. What is a thread? - Thread is a block of code which can execute concurrently
with other threads in the JVM.
10. What is the algorithm used in Thread scheduling? - Fixed priority scheduling.
11. What is hash-collision in Hashtable and how it is handled in Java? - Two
different keys with the same hash value. Two different entries will be kept in a
single hash bucket to avoid the collision.
12. What are the different driver types available in JDBC? - 1. A JDBC-ODBC
bridge 2. A native-API partly Java technology-enabled driver 3. A net-protocol
fully Java technology-enabled driver 4. A native-protocol fully Java technology-
enabled driver For more information: Driver Description
13. Is JDBC-ODBC bridge multi-threaded? - No
14. Does the JDBC-ODBC Bridge support multiple concurrent open statements
per connection? - No
15. What is the use of serializable? - To persist the state of an object into any
perminant storage device.
16. What is the use of transient? - It is an indicator to the JVM that those variables
should not be persisted. It is the users responsibility to initialize the value when
read back from the storage.
17. What are the different level lockings using the synchronization keyword? -
Class level lock Object level lock Method level lock Block level lock
18. What is the use of preparedstatement? - Preparedstatements are precompiled
statements. It is mainly used to speed up the process of inserting/updating/deleting
especially when there is a bulk processing.
19. What is callable statement? Tell me the way to get the callable statement? -
Callablestatements are used to invoke the stored procedures. You can obtain the
callablestatement from Connection using the following methods
prepareCall(String sql) prepareCall(String sql, int resultSetType, int
resultSetConcurrency)
20. In a statement, I am executing a batch. What is the result of the execution? -
It returns the int array. The array contains the affected row count in the
corresponding index of the SQL.
21. Can a abstract method have the static qualifier? - No
22. What are the different types of qualifier and what is the default qualifier? -
public, protected, private, package (default)
23. What is the super class of Hashtable? - Dictionary
24. What is a lightweight component? - Lightweight components are the one which
doesn’t go with the native call to obtain the graphical units. They share their
parent component graphical units to render them. Example, Swing components
25. What is a heavyweight component? - For every paint call, there will be a native
call to get the graphical units. Example, AWT.
26. What is an applet? - Applet is a program which can get downloaded into a client
environment and start executing there.
27. What do you mean by a Classloader? - Classloader is the one which loads the
classes into the JVM.
28. What are the implicit packages that need not get imported into a class file? -
java.lang
29. What is the difference between lightweight and heavyweight component? -
Lightweight components reuses its parents graphical units. Heavyweight
components goes with the native graphical unit for every component. Lightweight
components are faster than the heavyweight components.
30. What are the ways in which you can instantiate a thread? - Using Thread
class By implementing the Runnable interface and giving that handle to the
Thread class.
31. What are the states of a thread? - 1. New 2. Runnable 3. Not Runnable 4. Dead
32. What is a socket? - A socket is an endpoint for communication between two
machines.
33. How will you establish the connection between the servlet and an applet? -
Using the URL, I will create the connection URL. Then by openConnection
method of the URL, I will establish the connection, through which I can be able to
exchange data.
34. What are the threads will start, when you start the java program? - Finalizer,
Main, Reference Handler, Signal Dispatcher
35. What are synchronized methods and synchronized statements? Synchronized
methods are methods that are used to control access to an object. For example, a
thread only executes a synchronized method after it has acquired the lock for the
method’s object or class. Synchronized statements are similar to synchronized
methods. A synchronized statement can only be executed after a thread has
acquired the lock for the object or class referenced in the synchronized statement.
36. What are different ways in which a thread can enter the waiting state? A
thread can enter the waiting state by invoking its sleep() method, blocking on I/O,
unsuccessfully attempting to acquire an object’s lock, or invoking an object’s
wait() method. It can also enter the waiting state by invoking its (deprecated)
suspend() method.
37. Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This
lock is acquired on the class’s Class object.
38. What’s new with the stop(), suspend() and resume() methods in new JDK
1.2? The stop(), suspend() and resume() methods have been deprecated in JDK
1.2.
39. What is the preferred size of a component? The preferred size of a component
is the minimum component size that will allow the component to display
normally.
40. What method is used to specify a container’s layout? The setLayout() method
is used to specify a container’s layout. For example, setLayout(new
FlowLayout()); will be set the layout as FlowLayout.
41. Which containers use a FlowLayout as their default layout? The Panel and
Applet classes use the FlowLayout as their default layout.
42. What state does a thread enter when it terminates its processing? When a
thread terminates its processing, it enters the dead state.
43. What is the Collections API? The Collections API is a set of classes and
interfaces that support operations on collections of objects. One example of class
in Collections API is Vector and Set and List are examples of interfaces in
Collections API.
44. What is the List interface? The List interface provides support for ordered
collections of objects. It may or may not allow duplicate elements but the
elements must be ordered.
45. How does Java handle integer overflows and underflows? It uses those low
order bytes of the result that can fit into the size of the type allowed by the
operation.
46. What is the Vector class? The Vector class provides the capability to implement
a growable array of objects. The main visible advantage of this class is
programmer needn’t to worry about the number of elements in the Vector.
47. What modifiers may be used with an inner class that is a member of an outer
class? A (non-local) inner class may be declared as public, protected, private,
static, final, or abstract.
48. If a method is declared as protected, where may the method be accessed? A
protected method may only be accessed by classes or interfaces of the same
package or by subclasses of the class in which it is declared.
49. What is an Iterator interface? The Iterator interface is used to step through the
elements of a Collection.
50. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters? Unicode requires 16 bits, ASCII require 7 bits (although the ASCII
character set uses only 7 bits, it is usually represented as 8 bits), UTF-8 represents
characters using 8, 16, and 18 bit patterns, UTF-16 uses 16-bit and larger bit
patterns
51. What is the difference between yielding and sleeping? Yielding means a thread
returning to a ready state either from waiting, running or after creation, where as
sleeping refers a thread going to a waiting state from running state. With reference
to Java, when a task invokes its yield() method, it returns to the ready state and
when a task invokes its sleep() method, it returns to the waiting state
52. What are wrapper classes? Wrapper classes are classes that allow primitive
types to be accessed as objects. For example, Integer, Double. These classes
contain many methods which can be used to manipulate basic data types
53. Does garbage collection guarantee that a program will not run out of
memory? No, it doesn’t. It is possible for programs to use up memory resources
faster than they are garbage collected. It is also possible for programs to create
objects that are not subject to garbage collection. The main purpose of Garbage
Collector is recover the memory from the objects which are no longer required
when more memory is needed.
54. Name Component subclasses that support painting? The following classes
support painting: Canvas, Frame, Panel, and Applet.
55. What is a native method? A native method is a method that is implemented in a
language other than Java. For example, one method may be written in C and can
be called in Java.
56. How can you write a loop indefinitely?

for(;;) //for loop


while(true); //always true
57. Can an anonymous class be declared as implementing an interface and
extending a class? An anonymous class may implement an interface or extend a
superclass, but may not be declared to do both.
58. What is the purpose of finalization? The purpose of finalization is to give an
unreachable object the opportunity to perform any cleanup processing before the
object is garbage collected. For example, closing a opened file, closing a opened
database Connection.
59. What invokes a thread’s run() method? After a thread is started, via its start()
method or that of the Thread class, the JVM invokes the thread’s run() method
when the thread is initially executed.
60. What is the GregorianCalendar class? The GregorianCalendar provides support
for traditional Western calendars.
61. What is the SimpleTimeZone class? The SimpleTimeZone class provides
support for a Gregorian calendar.
62. What is the Properties class? The properties class is a subclass of Hashtable that
can be read from or written to a stream. It also provides the capability to specify a
set of default values to be used.
63. What is the purpose of the Runtime class? The purpose of the Runtime class is
to provide access to the Java runtime system.
64. What is the purpose of the System class? The purpose of the System class is to
provide access to system resources.
65. What is the purpose of the finally clause of a try-catch-finally statement? The
finally clause is used to provide the capability to execute code no matter whether
or not an exception is thrown or caught. For example,

try
{
//some statements
}
catch
{
// statements when exception is cought
}
finally
{
//statements executed whether exception occurs or not
}

66. What is the Locale class? The Locale class is used to tailor program output to
the conventions of a particular geographic, political, or cultural region.
67. What must a class do to implement an interface? It must provide all of the
methods in the interface and identify the interface in its implements clause.
68. What is a class? A class is a blueprint, or prototype, that defines the variables
and the methods common to all objects of a certain kind.
69. What is a object? An object is a software bundle of variables and related
methods.An instance of a class depicting the state and behavior at that particular
time in real world.
70. What is a method? Encapsulation of a functionality which can be called to
perform specific tasks.
71. What is encapsulation? Explain with an example. Encapsulation is the term
given to the process of hiding the implementation details of the object. Once an
object is encapsulated, its implementation details are not immediately accessible
any more. Instead they are packaged and are only indirectly accessible via the
interface of the object
72. What is inheritance? Explain with an example. Inheritance in object oriented
programming means that a class of objects can inherit properties and methods
from another class of objects.
73. What is polymorphism? Explain with an example. In object-oriented
programming, polymorphism refers to a programming language’s ability to
process objects differently depending on their data type or class. More
specifically, it is the ability to redefine methods for derived classes. For example,
given a base class shape, polymorphism enables the programmer to define
different area methods for any number of derived classes, such as circles,
rectangles and triangles. No matter what shape an object is, applying the area
method to it will return the correct results. Polymorphism is considered to be a
requirement of any true object-oriented programming language
74. Is multiple inheritance allowed in Java? No, multiple inheritance is not allowed
in Java.
75. What is interpreter and compiler? Java interpreter converts the high level
language code into a intermediate form in Java called as bytecode, and then
executes it, where as a compiler converts the high level language code to machine
language making it very hardware specific
76. What is JVM? The Java interpreter along with the runtime environment required
to run the Java application in called as Java virtual machine(JVM)
77. What are the different types of modifiers? There are access modifiers and there
are other identifiers. Access modifiers are public, protected and private. Other are
final and static.
78. What are the access modifiers in Java? There are 3 access modifiers. Public,
protected and private, and the default one if no identifier is specified is called
friendly, but programmer cannot specify the friendly identifier explicitly.
79. What is a wrapper class? They are classes that wrap a primitive data type so it
can be used as a object
80. What is a static variable and static method? What’s the difference between
two? The modifier static can be used with a variable and method. When declared
as static variable, there is only one variable no matter how instances are created,
this variable is initialized when the class is loaded. Static method do not need a
class to be instantiated to be called, also a non static method cannot be called from
static method.
81. What is garbage collection? Garbage Collection is a thread that runs to reclaim
the memory by destroying the objects that cannot be referenced anymore.
82. What is abstract class? Abstract class is a class that needs to be extended and its
methods implemented, aclass has to be declared abstract if it has one or more
abstract methods.
83. What is meant by final class, methods and variables? This modifier can be
applied to class method and variable. When declared as final class the class
cannot be extended. When declared as final variable, its value cannot be changed
if is primitive value, if it is a reference to the object it will always refer to the
same object, internal attributes of the object can be changed.
84. What is interface? Interface is a contact that can be implemented by a class, it
has method that need implementation.
85. What is method overloading? Overloading is declaring multiple method with
the same name, but with different argument list.
86. What is method overriding? Overriding has same method name, identical
arguments used in subclass.
87. What is singleton class? Singleton class means that any given time only one
instance of the class is present, in one JVM.
88. What is the difference between an array and a vector? Number of elements in
an array are fixed at the construction time, whereas the number of elements in
vector can grow dynamically.
89. What is a constructor? In Java, the class designer can guarantee initialization of
every object by providing a special method called a constructor. If a class has a
constructor, Java automatically calls that constructor when an object is created,
before users can even get their hands on it. So initialization is guaranteed.
90. What is casting? Conversion of one type of data to another when appropriate.
Casting makes explicitly converting of data.
91. What is the difference between final, finally and finalize? The modifier final is
used on class variable and methods to specify certain behaviour explained above.
And finally is used as one of the loop in the try catch blocks, It is used to hold
code that needs to be executed whether or not the exception occurs in the try catch
block. Java provides a method called finalize( ) that can be defined in the class.
When the garbage collector is ready to release the storage ed for your object, it
will first call finalize( ), and only on the next garbage-collection pass will it
reclaim the objects memory. So finalize( ), gives you the ability to perform some
important cleanup at the time of garbage collection.
92. What is are packages? A package is a collection of related classes and interfaces
providing access protection and namespace management.
93. What is a super class and how can you call a super class? When a class is
extended that is derived from another class there is a relationship is created, the
parent class is referred to as the super class by the derived class that is the child.
The derived class can make a call to the super class using the keyword super. If
used in the constructor of the derived class it has to be the first statement.
94. What is meant by a Thread? Thread is defined as an instantiated parallel
process of a given program.
95. What is multi-threading? Multi-threading as the name suggest is the scenario
where more than one threads are running.
96. What are two ways of creating a thread? Which is the best way and why?
Two ways of creating threads are, one can extend from the Java.lang.Thread and
can implement the rum method or the run method of a different class can be
called which implements the interface Runnable, and the then implement the run()
method. The latter one is mostly used as first due to Java rule of only one class
inheritance, with implementing the Runnable interface that problem is sorted out.
97. What is deadlock? Deadlock is a situation when two threads are waiting on each
other to release a resource. Each thread waiting for a resource which is held by the
other waiting thread. In Java, this resource is usually the object lock obtained by
the synchronized keyword.
98. What are the three types of priority? MAX_PRIORITY which is 10,
MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.
99. What is the use of synchronizations? Every object has a lock, when a
synchronized keyword is used on a piece of code the, lock must be obtained by
the thread first to execute that code, other threads will not be allowed to execute
that piece of code till this lock is released.

What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer
needed by a program so that their resources can be reclaimed and reused. A Java object is
subject to garbage collection when it becomes unreachable to the program in which it is
used.

2) 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 synchonization, 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.

>

3) How is JavaBeans differ from Enterprise JavaBeans?

The JavaBeans architecture is meant to provide a format for general-purpose components.


On the other hand, the Enterprise JavaBeans architecture provides a format for highly
specialized business logic components.

4) In what ways do design patterns help build better software?

Design patterns helps software developers to reuse successful designs and architectures.
It helps them to choose design alternatives that make a system reusuable and avoid
alternatives that compromise reusability through proven techniques as design patterns.

5) Describe 3-Tier Architecture in enterprise application development.


In 3-tier architecture, an application is broken up into 3 separate logical layers, each with
a well-defined set of interfaces. The presentation layer typically consists of a graphical
user interfaces. The business layer consists of the application or business logic, and the
data layer contains the data that is needed for the application

What are the advantages of OOPL?

Ans: Object oriented programming languages directly represent the real life objects. The
features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful.

Q2: What do mean by polymorphisum, inheritance, encapsulation?

Ans: Polymorhisum: is a feature of OOPl that at run time depending upon the type of
object the appropriate method is called.
Inheritance: is a feature of OOPL that represents the "is a" relationship between different
objects(classes). Say in real life a manager is a employee. So in OOPL manger class is
inherited from the employee class.
Encapsulation: is a feature of OOPL that is used to hide the information.

Q3: What do you mean by static methods?

Ans: By using the static method there is no need creating an object of that class to use
that method. We can directly call that method on that class. For example, say class A has
static function f(), then we can call f() function as A.f(). There is no need of creating an
object of class A.

Q4: What do you mean by virtual methods?

Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is
inherited from class B. If we declare say fuction f() as virtual in class B and override the
same function in class A then at runtime appropriate method of the class will be called
depending upon the type of the object.

Q5: Given two tables Student(SID, Name, Course) and Level(SID, level) write the
SQL statement to get the name and SID of the student who are taking course = 3
and at freshman level.

Ans: SELECT Student.name, Student.SID


FROM Student, Level
WHERE Student.SID = Level.SID
AND Level.Level = "freshman"
AND Student.Course = 3;

Q6: What are the disadvantages of using threads?

Ans: DeadLock.
Q1: Write the Java code to declare any constant (say gravitational constant) and to
get its value

Ans: Class ABC


{
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
{
system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT);
}
}
Q2: What do you mean by multiple inheritance in C++ ?

Ans: Multiple inheritance is a feature in C++ by which one class can be of different
types. Say class teachingAssistant is inherited from two classes say teacher and Student.

Q3: Can you write Java code for declaration of multiple inheritance in Java ?

Ans: Class C extends A implements B


{
}

Q:In Java, what is the difference between an Interface and an Abstract class?

A: An Abstract class declares have at least one instance method that is declared abstract
which will be implemented by the subclasses. An abstract class can have instance
methods that implement a default behavior. An Interface can only declare constants and
instance methods, but cannot implement default behavior.

Q: Can you have virtual functions in Java? Yes or No. If yes, then what are virtual
functions?

A: Yes, Java class functions are virtual by default. Virtual functions are functions of
subclasses that can be invoked from a reference to their superclass. In other words, the
functions of the actual object are called when a function is invoked on the reference to
that object.

Q:Write a function to reverse a linked list p in C++?

A:

Link* reverse_list(Link* p)
{
if (p == NULL)
return NULL;

Link* h = p;
p = p->next;
h->next = NULL;
while (p != null)
{
Link* t = p->next;
p->next = h;
h = p;
p = t;
}

return h;
}

Q:In C++, what is the usefulness of Virtual destructors?

A:Virtual destructors are neccessary to reclaim memory that were allocated for objects in
the class hierarchy. If a pointer to a base class object is deleted, then the compiler
guarantees the various subclass destructors are called in reverse order of the object
construction chain.

Q:What are mutex and semaphore? What is the difference between them?

A:A mutex is a synchronization object that allows only one process or thread to access a
critical code block. A semaphore on the other hand allows one or more processes or
threads to access a critial code block. A semaphore is a multiple mutex

Why do you prefer Java?

Answer: write once ,run anywhere.

2. Name some of the classes which provide the functionality of collation?

Answer: collator, rulebased collator, collationkey, collationelement iterator.

3. Awt stands for? and what is it?

Answer: AWT stands for Abstract window tool kit. It is a is a package that provides an
integrated set of classes to manage user interface components.

4. why a java program can not directly communicate with an ODBC driver?
Answer: Since ODBC API is written in C language and makes use of pointers which Java
can not support.

5. Are servlets platform independent? If so Why? Also what is the most common
application of servlets?

Answer: Yes, Because they are written in Java. The most common application of servlet
is to access database and dynamically construct HTTP response

Servlet
1. What is the servlet?
2. What are the JSP atrributes?
3. What is the need of super.init(config) in servlets?
4. How to know whether we have to use jsp or servlet in our project?
5. Can we call destroy() method on servlets from service method?
6. What is the Servlet Interface?
7. What is the difference between GenericServlet and HttpServlet?
8. How we can check in particular page the session will be alive or not?
9. What is the importance of deployment descriptor in servlet?
10. When we increase the buffer size in our project using page directive attribute
‘buffer’ what changes we observe?
11. What is the difference between ServetConfig and ServletContext..?
12. When a servlet accepts a call from a client, it receives two objects. What are they?
13. What are the differences between GET and POST service methods?
14. In which conditions we have to use the ServletContext?
15. What methods will be called in which order?((i.e)service(),doget(),dopost())
16. Servlet is Java class. Then why there is no constructor in Servlet? Can we write
the constructor in Servlet
17. What is the use of ServletConfig and ServletContext..?
18. What information that the ServletRequest interface allows the servlet access to?
19. What is the difference between ServletContext and ServletConfig?
20. When do you have action=get?
21. What is a Singleton class. How do you write it?
22. What is difference between sendRedirect() and forward()..? Which one is faster
then other and which works on server?
23. What information that the ServletResponse interface gives the servlet methods for
replying to the client?
24. Can I invoke a JSP error page from a servlet?
25. Can a init(ServletConfig config) method be overrided in servlets?
26. How many ServletConfig and servlet context objects are present in one
application?
27. Do we have a constructor in servlet? can we explictly provide a constructor in
servlet programme as in java program?
28. What are the uses of Servlets?
29. Can I just abort processing a JSP?
30. Is servlet is used to create a dynamic webpage or Static webpage or both?
31. If you want a servlet to take the same action for both GET and POST request,
what should you do?
32. What is the difference between JSP and SERVLETS?
33. What are the advantages using servlets than using CGI?
34. What is a better approach for enabling thread-safe servlets and JSPs?
SingleThreadModel Interface or synchronization?
35. We have two applications in that we have two servlets each.How they(servlets)
communicate with each other?
36. How the server will know (i.e) when it can invoke init, service,destroy methods of
servlet life cycle?
37. How to communicate between two servlets?
38. What is the difference between servlets and applets?
39. How will u pass the argument from one servlet to another servlet?
40. What method used to add a jsp to the servlet?
41. How HTTP Servlet handles client requests?
42. How to get one Servlet’s Context Information in another Servlet?
43. Difference between single thread and multi thread model servlet
44. What is the super class of All servlets?
45. How are Servlet Applet communication achieved?
46. What is servlet context and what it takes actually as parameters?
47. What is the servlet life cycle?
48. Types of Servlets?
49. Why is that we deploy servlets in a webserver.What exactly is a webserver?
50. Which code line must be set before any of the lines that use the PrintWriter?
51. What is the difference between CGI and Servlet?
52. What is meant by a servlet?
53. What are the types of servlets? What is the difference between 2 types of
Servlets?
54. What is the type of method for sending request from HTTP server ?
55. What are the exceptions thrown by Servlets? Why?
56. What is the life cycle of a servlet?
57. What is meant by cookies? Why is Cookie used?
58. What is HTTP Session?
59. What is the difference between GET and POST methods?
60. How can you run a Servlet Program?
61. What is the middleware? What is the functionality of Webserver?
62. What webserver is used for running the Servlets?
63. How do you invoke a Servelt? What is the difference in between doPost and
doGet methods?
64. What is the difference in between the HTTPServlet and Generic Servlet? Explain
their methods? Tell me their parameter names also?
65. What are session variable in Servlets?
66. What is meant by Session? Tell me something about HTTPSession Class?
67. What is Session Tracking?
68. Difference between doGet and doPost?
69. What are the methods in HttpServlet?
70. What are the types of SessionTracking? Why do you use Session Tracking in
HttpServlet?
71. What is a servlet?
Servlets are modules that extend request/response-oriented servers,such as Java-
enabled web servers. For example, a servlet might be responsible for taking data
in an HTML order-entry form and applying the business logic used to update a
company’s order database. Servlets are to servers what applets are to browsers.
Unlike applets, however, servlets have no graphical user interface.
72. Whats the advantages using servlets over using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write
and faster to run. Servlets also address the problem of doing server-side
programming with platform-specific APIs: they are developed with the Java
Servlet API, a standard Java extension.
73. What are the general advantages and selling points of Servlets?
A servlet can handle multiple requests concurrently, and synchronize requests.
This allows servlets to support systems such as online
real-time conferencing. Servlets can forward requests to other servers and
servlets. Thus servlets can be used to balance load among several servers that
mirror the same content, and to partition a single logical service over several
servers, according to task type or organizational boundaries.
74. Which package provides interfaces and classes for writing servlets? javax
75. What’s the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets
implement this interface, either directly or, more
commonly, by extending a class that implements it such as HttpServlet.Servlets >
Generic Servlet > HttpServlet > MyServlet.
The Servlet interface declares, but does not implement, methods that manage the
servlet and its communications with clients. Servlet writers provide some or all of
these methods when developing a servlet.
76. When a servlet accepts a call from a client, it receives two objects. What are
they?
ServletRequest (which encapsulates the communication from the client to the
server) and ServletResponse (which encapsulates the communication from the
servlet back to the client). ServletRequest and ServletResponse are interfaces
defined inside javax.servlet package.
77. What information does ServletRequest allow access to?
Information such as the names of the parameters passed in by the client, the
protocol (scheme) being used by the client, and the names
of the remote host that made the request and the server that received it. Also the
input stream, as ServletInputStream.Servlets use the input stream to get data from
clients that use application protocols such as the HTTP POST and GET methods.
78. What type of constraints can ServletResponse interface set on the client?
It can set the content length and MIME type of the reply. It also provides an
output stream, ServletOutputStream and a Writer through
which the servlet can send the reply data.
79. Explain servlet lifecycle?
Each servlet has the same life cycle: first, the server loads and initializes the
servlet (init()), then the servlet handles zero or more client requests (service()),
after that the server removes the servlet (destroy()). Worth noting that the last step
on some servers is done when they shut down.
80. How does HTTP Servlet handle client requests?
An HTTP Servlet handles client requests through its service method. The service
method supports standard HTTP client requests by dispatching each request to a
method designed to handle that request.
81. Can we use the constructor, instead of init(), to initialize servlet? - Yes , of
course you can use the constructor instead of init(). There’s nothing to stop you.
But you shouldn’t. The original reason for init() was that ancient versions of Java
couldn’t dynamically invoke constructors with arguments, so there was no way to
give the constructur a ServletConfig. That no longer applies, but servlet
containers still will only call your no-arg constructor. So you won’t have access to
a ServletConfig or ServletContext.
82. How can a servlet refresh automatically if some new data has entered the
database? - You can use a client-side Refresh or Server Push.
83. The code in a finally clause will never fail to execute, right? - Using
System.exit(1); in try block will not allow finally code to execute.
84. How many messaging models do JMS provide for and what are they? - JMS
provide for two messaging models, publish-and-subscribe and point-to-point
queuing.
85. What information is needed to create a TCP Socket? - The Local System?s IP
Address and Port Number. And the Remote System’s IPAddress and Port
Number.
86. What Class.forName will do while loading drivers? - It is used to create an
instance of a driver and register it with the DriverManager. When you have
loaded a driver, it is available for making a connection with a DBMS.
87. How to Retrieve Warnings? - SQLWarning objects are a subclass of
SQLException that deal with database access warnings. Warnings do not stop the
execution of an application, as exceptions do; they simply alert the user that
something did not happen as planned. A warning can be reported on a Connection
object, a Statement object (including PreparedStatement and CallableStatement
objects), or a ResultSet object. Each of these classes has a getWarnings method,
which you must invoke in order to see the first warning reported on the calling
object
88. SQLWarning warning = stmt.getWarnings();
89. if (warning != null)
90. {
91. while (warning != null)
92. {
93. System.out.println("Message: " +
warning.getMessage());
94. System.out.println("SQLState: " +
warning.getSQLState());
95. System.out.print("Vendor error code: ");
96.
System.out.println(warning.getErrorCode());
97. warning = warning.getNextWarning();
98. }
99. }
100. How many JSP scripting elements are there and what are they? -
There are three scripting language elements: declarations, scriptlets, expressions.
101. In the Servlet 2.4 specification SingleThreadModel has been
deprecated, why? - Because it is not practical to have such model. Whether you
set isThreadSafe to true or false, you should take care of concurrent client
requests to the JSP page by synchronizing access to any shared objects defined at
the page level.
102. What are stored procedures? How is it useful? - A stored procedure is a
set of statements/commands which reside in the database. The stored procedure is
pre-compiled and saves the database the effort of parsing and compiling sql
statements everytime a query is run. Each database has its own stored procedure
language, usually a variant of C with a SQL preproceesor. Newer versions of db’s
support writing stored procedures in Java and Perl too. Before the advent of 3-
tier/n-tier architecture it was pretty common for stored procs to implement the
business logic( A lot of systems still do it). The biggest advantage is of course
speed. Also certain kind of data manipulations are not achieved in SQL. Stored
procs provide a mechanism to do these manipulations. Stored procs are also
useful when you want to do Batch updates/exports/houseKeeping kind of stuff on
the db. The overhead of a JDBC Connection may be significant in these cases.
103. How do I include static files within a JSP page? - Static resources
should always be included using the JSP include directive. This way, the inclusion
is performed just once during the translation phase. Do note that you should
always supply a relative URL for the file attribute. Although you can also include
static resources using the action, this is not advisable as the inclusion is then
performed for each and every request.
104. Why does JComponent have add() and remove() methods but
Component does not? - because JComponent is a subclass of Container, and can
contain other components and jcomponents.
105. How can I implement a thread-safe JSP page? - You can make your
JSPs thread-safe by having them implement the SingleThreadModel interface.
This is done by adding the directive <%@ page isThreadSafe="false" % > within
your JSP page.

JSP

1. What is JSP? Describe its concept. JSP is a technology that combines


HTML/XML markup languages and elements of Java programming Language to
return dynamic content to the Web client, It is normally used to handle
Presentation logic of a web application, although it may have business logic.
2. What are the lifecycle phases of a JSP?
JSP page looks like a HTML page but is a servlet. When presented with JSP page
the JSP engine does the following 7 phases.
1. Page translation: -page is parsed, and a java file which is a servlet is
created.
2. Page compilation: page is compiled into a class file
3. Page loading : This class file is loaded.
4. Create an instance :- Instance of servlet is created
5. jspInit() method is called
6. _jspService is called to handle service calls
7. _jspDestroy is called to destroy it when the servlet is not required.
3. What is a translation unit? JSP page can include the contents of other HTML
pages or other JSP files. This is done by using the include directive. When the JSP
engine is presented with such a JSP page it is converted to one servlet class and
this is called a translation unit, Things to remember in a translation unit is that
page directives affect the whole unit, one variable declaration cannot occur in the
same unit more than once, the standard action jsp:useBean cannot declare the
same bean twice in one unit.
4. How is JSP used in the MVC model? JSP is usually used for presentation in the
MVC pattern (Model View Controller ) i.e. it plays the role of the view. The
controller deals with calling the model and the business classes which in turn get
the data, this data is then presented to the JSP for rendering on to the client.
5. What are context initialization parameters? Context initialization parameters
are specified by the <context-param> in the web.xml file, these are initialization
parameter for the whole application and not specific to any servlet or JSP.
6. 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 un-interpreted 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.
7. 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. The hidden
comment is useful when you want to hide or “comment out” part of your JSP
page.
8. What is a Expression? Expressions are act as place holders for language
expression, expression is evaluated each time the page is accessed.
9. What is a Declaration? It declares one or more variables or methods for use later
in the JSP source file. A declaration must contain at least one complete
declarative statement. You can declare any number of variables or methods within
one declaration tag, as long as semicolons separate them. The declaration must be
valid in the scripting language used in the JSP file.
10. What is a Scriptlet? A scriptlet can contain any number of language statements,
variable or method declarations, or expressions that are valid in the page scripting
language. Within scriptlet tags, you can declare variables or methods to use later
in the file, write expressions valid in the page scripting language, use any of the
JSP implicit objects or any object declared with a <jsp:useBean>.
11. What are the implicit objects? List them. Certain objects that are available for
the use in JSP documents without being declared first. These objects are parsed by
the JSP engine and inserted into the generated servlet. The implicit objects are:

o request
o response
o pageContext
o session
o application
o out
o config
o page
o exception
2. What’s the difference between forward and sendRedirect? When you invoke a
forward request, the request is sent to another resource on the server, without the
client being informed that a different resource is going to process the request. This
process occurs completely with in the web container And then returns to the
calling method. When a sendRedirect method is invoked, it causes the web
container to return to the browser indicating that a new URL should be requested.
Because the browser issues a completely new request any object that are stored as
request attributes before the redirect occurs will be lost. This extra round trip a
redirect is slower than forward.
3. What are the different scope values for the <jsp:useBean>? The different
scope values for <jsp:useBean> are:
o page
o request
o session
o application
4. Why are JSP pages the preferred API for creating a web-based client
program? Because no plug-ins or security policy files are needed on the client
systems(applet does). Also, JSP pages enable cleaner and more module
application design because they provide a way to separate applications
programming from web page design. This means personnel involved in web page
design do not need to understand Java programming language syntax to do their
jobs.
5. Is JSP technology extensible? Yes, it is. JSP technology is extensible through
the development of custom actions, or tags, which are encapsulated in tag
libraries.
6. What is difference between custom JSP tags and beans? Custom JSP tag is a
tag you defined. You define how a tag, its attributes and its body are interpreted,
and then group your tags into collections called tag libraries that can be used in
any number of JSP files. Custom tags and beans accomplish the same goals —
encapsulating complex behavior into simple and accessible forms. There are
several differences:
o Custom tags can manipulate JSP content; beans cannot.
o Complex operations can be reduced to a significantly simpler form with
custom tags than with beans.
o Custom tags require quite a bit more work to set up than do beans.
o Custom tags usually define relatively self-contained behavior, whereas
beans are often defined in one servlet and used in a different servlet or JSP
page.
o Custom tags are available only in JSP 1.1 and later, but beans can be used
in all JSP 1.x versions.
7. What is the query used to display all tables names in SQL Server (Query
analyzer)?
8. select * from information_schema.tables
9. How many types of JDBC Drivers are present and what are they?- There are
4 types of JDBC Drivers
o JDBC-ODBC Bridge Driver
o Native API Partly Java Driver
o Network protocol Driver
o JDBC Net pure Java Driver
10. Can we implement an interface in a JSP?- No
11. What is the difference between ServletContext and PageContext?-
ServletContext: Gives the information about the container. PageContext: Gives
the information about the Request
12. What is the difference in using request.getRequestDispatcher() and
context.getRequestDispatcher()?- request.getRequestDispatcher(path): In order
to create it we need to give the relative path of the resource,
context.getRequestDispatcher(path): In order to create it we need to give the
absolute path of the resource.
13. How to pass information from JSP to included JSP?- Using <
%jsp:param> tag.
14. What is the difference between directive include and jsp include?- <
%@ include>: Used to include static resources during translation time. JSP
include: Used to include dynamic content or static content during runtime.
15. What is the difference between RequestDispatcher and
sendRedirect?- RequestDispatcher: server-side redirect with request and
response objects. sendRedirect : Client-side redirect with new request and
response objects.
16. How does JSP handle runtime exceptions?- Using errorPage attribute of
page directive and also we need to specify isErrorPage=true if the current page is
intended to URL redirecting of a JSP.
17. How do you delete a Cookie within a JSP?
18. Cookie mycook = new Cookie("name","value");
19. response.addCookie(mycook);
20. Cookie killmycook = new Cookie("mycook","value");
21. killmycook.setMaxAge(0);
22. killmycook.setPath("/");
23. killmycook.addCookie(killmycook);
24. How do I mix JSP and SSI #include?- If you’re just including raw
HTML, use the #include directive as usual inside your .jsp file.
25. <!--#include file="data.inc"-->

But it’s a little trickier if you want the server to evaluate any JSP code that’s
inside the included file. If your data.inc file contains jsp code you will have to use

<%@ vinclude="data.inc" %>

The <!–#include file="data.inc"–> is used for including non-JSP files.

26. I made my class Cloneable but I still get Can’t access protected method
clone. Why?- Some of the Java books imply that all you have to do in order to
have your class support clone() is implement the Cloneable interface. Not so.
Perhaps that was the intent at some point, but that’s not the way it works
currently. As it stands, you have to implement your own public clone() method,
even if it doesn’t do anything special and just calls super.clone().
27. Why is XML such an important development?- It removes two
constraints which were holding back Web developments: dependence on a single,
inflexible document type (HTML) which was being much abused for tasks it was
never designed for; the complexity of full SGML, whose syntax allows many
powerful but hard-to-program options. XML allows the flexible development of
user-defined document types. It provides a robust, non-proprietary, persistent, and
verifiable file format for the storage and transmission of text and data both on and
off the Web; and it removes the more complex options of SGML, making it easier
to program for.
28. What is the fastest type of JDBC driver?- JDBC driver performance
will depend on a number of issues:
o the quality of the driver code,
o the size of the driver code,
o the database server and its load,
o network topology,
o the number of times your request is translated to a different API.

In general, all things being equal, you can assume that the more your request and
response change hands, the slower it will be. This means that Type 1 and Type 3
drivers will be slower than Type 2 drivers (the database calls are make at least
three translations versus two), and Type 4 drivers are the fastest (only one
translation).

29. How do I find whether a parameter exists in the request object?


30. boolean hasFoo = !(request.getParameter("foo") == null
31. || request.getParameter("foo").equals(""));

or
boolean hasParameter =
request.getParameterMap().contains(theParameter); //(which works
in Servlet 2.3+)
32. How can I send user authentication information while
makingURLConnection?- You’ll want to use
HttpURLConnection.setRequestProperty and set all the appropriate headers to
HTTP authorization.

What are the most common techniques for reusing functionality in object-oriented
systems?
A: The two most common techniques for reusing functionality in object-oriented systems
are class inheritance and object composition.

Class inheritance lets you define the implementation of one class in terms of another’s.
Reuse by subclassing is often referred to as white-box reuse.
Object composition is an alternative to class inheritance. Here, new functionality is
obtained by assembling or composing objects to get more complex functionality. This is
known as black-box reuse.

Q: Why would you want to have more than one catch block associated with a single
try block in Java?
A: Since there are many things can go wrong to a single executed statement, we should
have more than one catch(s) to catch any errors that might occur.

Q: What language is used by a relational model to describe the structure of a


database?
A: The Data Definition Language.

Q: What is JSP? Describe its concept.


A: JSP is Java Server Pages. The JavaServer Page concept is to provide an HTML
document with the ability to plug in content at selected locations in the document. (This
content is then supplied by the Web server along with the rest of the HTML document at
the time the document is downloaded).

Q: What does the JSP engine do when presented with a JavaServer Page to process?

A: The JSP engine builds a servlet. The HTML portions of the JavaServer Page become
Strings transmitted to print methods of a PrintWriter object. The JSP tag portions result in
calls to methods of the appropriate JavaBean class whose output is translated into more
calls to a println method to place the result in the HTML document.

1. What are the implicit objects? - Implicit objects are objects that are created by
the web container and contain information related to a particular request, page, or
application. They are: request, response, pageContext, session, application, out,
config, page, exception.
2. Is JSP technology extensible? - Yes. JSP technology is extensible through the
development of custom actions, or tags, which are encapsulated in tag libraries.
3. How can I implement a thread-safe JSP page? What are the advantages and
Disadvantages of using it? - You can make your JSPs thread-safe by having
them implement the SingleThreadModel interface. This is done by adding the
directive <%@ page isThreadSafe="false" %> within your JSP page. With this,
instead of a single instance of the servlet generated for your JSP page loaded in
memory, you will have N instances of the servlet loaded and initialized, with the
service method of each instance effectively synchronized. You can typically
control the number of instances (N) that are instantiated for all servlets
implementing SingleThreadModel through the admin screen for your JSP engine.
More importantly, avoid using the <%! DECLARE %>tag for variables. If you do
use this tag, then you should set isThreadSafe to true, as mentioned above.
Otherwise, all requests to that page will access those variables, causing a nasty
race condition. SingleThreadModel is not recommended for normal use. There are
many pitfalls, including the example above of not being able to use <%! %>. You
should try really hard to make them thread-safe the old fashioned way: by making
them thread-safe
4. How does JSP handle run-time exceptions? - You can use the errorPage
attribute of the page directive to have uncaught run-time exceptions automatically
forwarded to an error processing page. For example: <%@ page
errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is
encountered during request processing. Within error.jsp, if you indicate that it is
an error-processing page, via the directive: <%@ page isErrorPage="true" %>
Throwable object describing the exception may be accessed within the error page
via the exception implicit object. Note: You must always use a relative URL as
the value for the errorPage attribute.
5. How do I prevent the output of my JSP or Servlet pages from being cached
by the browser? - You will need to set the appropriate HTTP header attributes to
prevent the dynamic content output by the JSP page from being cached by the
browser. Just execute the following scriptlet at the beginning of your JSP pages to
prevent them from being cached at the browser. You need both the statements to
take care of some of the older browser versions.

<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

6. How do I use comments within a JSP page? - You can use “JSP-style”
comments to selectively block out code while debugging or simply to comment
your scriptlets. JSP comments are not visible at the client. For example:
7. <%-- the scriptlet is now commented out
8. <%
9. out.println("Hello World");
10. %>
11. --%>

You can also use HTML-style comments anywhere within your JSP page. These
comments are visible at the client. For example:

<!-- (c) 2004 -->

Of course, you can also use comments supported by your JSP scripting language
within your scriptlets. For example, assuming Java is the scripting language, you
can have:

<%
//some comment
/**
yet another comment
**/
%>
12. Response has already been commited error. What does it mean? - This error
show only when you try to redirect a page after you already have written
something in your page. This happens because HTTP specification force the
header to be set up before the lay out of the page can be shown (to make sure of
how it should be displayed, content-type=”text/html” or “text/xml” or “plain-text”
or “image/jpg”, etc.) When you try to send a redirect status (Number is
line_status_402), your HTTP server cannot send it right now if it hasn’t finished
to set up the header. If not starter to set up the header, there are no problems, but
if it ’s already begin to set up the header, then your HTTP server expects these
headers to be finished setting up and it cannot be the case if the stream of the page
is not over… In this last case it’s like you have a file started with <HTML
Tag><Some Headers><Body>some output (like testing your variables.) Before
you indicate that the file is over (and before the size of the page can be setted up
in the header), you try to send a redirect status. It s simply impossible due to the
specification of HTTP 1.0 and 1.1
13. How do I use a scriptlet to initialize a newly instantiated bean? - A
jsp:useBean action may optionally have a body. If the body is specified, its
contents will be automatically invoked when the specified bean is instantiated.
Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the
newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to
the current date when it is instantiated. Note that here, we make use of a JSP
expression within the jsp:setProperty action.
14. <jsp:useBean id="foo" class="com.Bar.Foo" >
15. <jsp:setProperty name="foo" property="today"
16. value="<%=java.text.DateFormat.getDateInstance().format(new
java.util.Date()) %>"/ >
17. <%-- scriptlets calling bean setter methods go here --%>
18. </jsp:useBean >
19. How can I enable session tracking for JSP pages if the browser has disabled
cookies? - We know that session tracking uses cookies by default to associate a
session identifier with a unique user. If the browser does not support cookies, or if
cookies are disabled, you can still enable session tracking using URL rewriting.
URL rewriting essentially includes the session ID within the link itself as a
name/value pair. However, for this to be effective, you need to append the session
ID for each and every link that is part of your servlet response. Adding the session
ID to a link is greatly simplified by means of of a couple of methods:
response.encodeURL() associates a session ID with a given URL, and if you are
using redirection, response.encodeRedirectURL() can be used by giving the
redirected URL as input. Both encodeURL() and encodeRedirectedURL() first
determine whether cookies are supported by the browser; if so, the input URL is
returned unchanged since the session ID will be persisted as a cookie. Consider
the following example, in which two JSP files, say hello1.jsp and hello2.jsp,
interact with each other. Basically, we create a new session within hello1.jsp and
place an object within this session. The user can then traverse to hello2.jsp by
clicking on the link present within the page.Within hello2.jsp, we simply extract
the object that was earlier placed in the session and display its contents. Notice
that we invoke the encodeURL() within hello1.jsp on the link used to invoke
hello2.jsp; if cookies are disabled, the session ID is automatically appended to the
URL, allowing hello2.jsp to still retrieve the session object. Try this example first
with cookies enabled. Then disable cookie support, restart the brower, and try
again. Each time you should see the maintenance of the session across pages. Do
note that to get this example to work with cookies disabled at the browser, your
JSP engine has to support URL rewriting.
20. hello1.jsp
21. <%@ page session="true" %>
22. <%
23. Integer num = new Integer(100);
24. session.putValue("num",num);
25. String url =response.encodeURL("hello2.jsp");
26. %>
27. <a href='<%=url%>'>hello2.jsp</a>
28. hello2.jsp
29. <%@ page session="true" %>
30. <%
31. Integer i= (Integer )session.getValue("num");
32. out.println("Num value in session is "+i.intValue());
33. How can I declare methods within my JSP page? - You can declare methods
for use within your JSP page as declarations. The methods can then be invoked
within any other methods you declare, or within JSP scriptlets and expressions.
Do note that you do not have direct access to any of the JSP implicit objects like
request, response, session and so forth from within JSP methods. However, you
should be able to pass any of the implicit JSP variables as parameters to the
methods you declare. For example:
34. <%!
35. public String whereFrom(HttpServletRequest req) {
36. HttpSession ses = req.getSession();
37. ...
38. return req.getRemoteHost();
39. }
40. %>
41. <%
42. out.print("Hi there, I see that you are coming in from
");
43. %>
44. <%= whereFrom(request) %>
45. Another Example
46. file1.jsp:
47. <%@page contentType="text/html"%>
48. <%!
49. public void test(JspWriter writer) throws IOException{
50. writer.println("Hello!");
51. }
52. %>
53. file2.jsp
54. <%@include file="file1.jsp"%>
55. <html>
56. <body>
57. <%test(out);% >
58. </body>
59. </html>
60. Is there a way I can set the inactivity lease period on a per-session basis? -
Typically, a default inactivity lease period for all sessions is set within your JSP
engine admin screen or associated properties file. However, if your JSP engine
supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-
session basis. This is done by invoking the HttpSession.setMaxInactiveInterval()
method, right after the session has been created. For example:
61. <%
62. session.setMaxInactiveInterval(300);
63. %>

would reset the inactivity period for this session to 5 minutes. The inactivity
interval is set in seconds.

64. How can I set a cookie and delete a cookie from within a JSP page? - A
cookie, mycookie, can be deleted using the following scriptlet:
65. <%
66. //creating a cookie
67. Cookie mycookie = new Cookie("aName","aValue");
68. response.addCookie(mycookie);
69. //delete a cookie
70. Cookie killMyCookie = new Cookie("mycookie", null);
71. killMyCookie.setMaxAge(0);
72. killMyCookie.setPath("/");
73. response.addCookie(killMyCookie);
74. %>
75. How does a servlet communicate with a JSP page? - The following code
snippet shows how a servlet instantiates a bean and initializes it with FORM data
posted by a browser. The bean is then placed into the request, and the call is then
forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for
downstream processing.
76. public void doPost (HttpServletRequest request,
HttpServletResponse response) {
77. try {
78. govi.FormBean f = new govi.FormBean();
79. String id = request.getParameter("id");
80. f.setName(request.getParameter("name"));
81. f.setAddr(request.getParameter("addr"));
82. f.setAge(request.getParameter("age"));
83. //use the id to compute
84. //additional bean properties like info
85. //maybe perform a db query, etc.
86. // . . .
87. f.setPersonalizationInfo(info);
88. request.setAttribute("fBean",f);
89.
getServletConfig().getServletContext().getRequestDispatcher
90. ("/jsp/Bean1.jsp").forward(request,
response);
91. } catch (Exception ex) {
92. . . .
93. }
94. }

The JSP page Bean1.jsp can then process fBean, after first extracting it from the
default request scope via the useBean action.

jsp:useBean id="fBean" class="govi.FormBean" scope="request"


/ jsp:getProperty name="fBean" property="name"
/ jsp:getProperty name="fBean" property="addr"
/ jsp:getProperty name="fBean" property="age"
/ jsp:getProperty name="fBean" property="personalizationInfo" /
95. How do I have the JSP-generated servlet subclass my own custom servlet
class, instead of the default? - One should be very careful when having JSP
pages extend custom servlet classes as opposed to the default one generated by
the JSP engine. In doing so, you may lose out on any advanced optimization that
may be provided by the JSP engine. In any case, your new superclass has to fulfill
the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or
implementing JspPage otherwise Ensuring that all the methods in the Servlet
interface are declared final Additionally, your servlet superclass also needs to do
the following:
o The service() method has to invoke the _jspService() method
o The init() method has to invoke the jspInit() method
o The destroy() method has to invoke jspDestroy()

If any of the above conditions are not satisfied, the JSP engine may throw a
translation error.
Once the superclass has been developed, you can have your JSP extend it as
follows:

<%@ page extends="packageName.ServletName" %>


96. How can I prevent the word "null" from appearing in my HTML input text
fields when I populate them with a resultset that has null values? - You could
make a simple wrapper function, like
97. <%!
98. String blanknull(String s) {
99. return (s == null) ? "" : s;
100. }
101. %>
102. then use it inside your JSP form, like
103. <input type="text" name="shoesize" value="<
%=blanknull(shoesize)% >" >
104. How can I get to print the stacktrace for an exception occuring within
my JSP page? - By printing out the exception’s stack trace, you can usually
diagonse a problem better when debugging JSP pages. By looking at a stack trace,
a programmer should be able to discern which method threw the exception and
which method called that method. However, you cannot print the stacktrace using
the JSP out implicit variable, which is of type JspWriter. You will have to use a
PrintWriter object instead. The following snippet demonstrates how you can print
a stacktrace from within a JSP error page:
105. <%@ page isErrorPage="true" %>
106. <%
107. out.println(" ");
108. PrintWriter pw = response.getWriter();
109. exception.printStackTrace(pw);
110. out.println(" ");
111. %>
112. How do you pass an InitParameter to a JSP? - The JspPage interface
defines the jspInit() and jspDestroy() method which the page writer can use in
their pages and are invoked in much the same manner as the init() and destory()
methods of a servlet. The example page below enumerates through all the
parameters and prints them to the console.
113. <%@ page import="java.util.*" %>
114. <%!
115. ServletConfig cfg =null;
116. public void jspInit(){
117. ServletConfig cfg=getServletConfig();
118. for (Enumeration e=cfg.getInitParameterNames();
e.hasMoreElements();) {
119. String name=(String)e.nextElement();
120. String value = cfg.getInitParameter(name);
121. System.out.println(name+"="+value);
122. }
123. }
124. %>
125. How can my JSP page communicate with an EJB Session Bean? - The
following is a code snippet that demonstrates how a JSP page can interact with an
EJB session bean:
126. <%@ page import="javax.naming.*,
javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
127. <%!
128. //declare a "global" reference to an instance of the
home interface of the session bean
129. AccountHome accHome=null;
130. public void jspInit() {
131. //obtain an instance of the home interface
132. InitialContext cntxt = new InitialContext( );
133. Object ref=
cntxt.lookup("java:comp/env/ejb/AccountEJB");
134. accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
135. }
136. %>
137. <%
138. //instantiate the session bean
139. Account acct = accHome.create();
140. //invoke the remote methods
141. acct.doWhatever(...);
142. // etc etc...
143. %>

JDBC

1. How do you call a Stored Procedure from JDBC? - The first step is to create a
CallableStatement object. As with Statement and PreparedStatement objects, this
is done with an open Connection object. A CallableStatement object contains a
call to a stored procedure.
2. CallableStatement cs =
3. con.prepareCall("{call SHOW_SUPPLIERS}");
4. ResultSet rs = cs.executeQuery();
5. Is the JDBC-ODBC Bridge multi-threaded? - No. The JDBC-ODBC Bridge
does not support concurrent access from different threads. The JDBC-ODBC
Bridge uses synchronized methods to serialize all of the calls that it makes to
ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the
advantages of multi-threading.
6. Does the JDBC-ODBC Bridge support multiple concurrent open statements
per connection? - No. You can open only one Statement object per connection
when you are using the JDBC-ODBC Bridge.
7. What is cold backup, hot backup, warm backup recovery? - Cold backup (All
these files must be backed up at the same time, before the databaseis restarted).
Hot backup (official name is ‘online backup’) is a backup taken of each
tablespace while the database is running and is being accessed by the users.
8. When we will Denormalize data? - Data denormalization is reverse procedure,
carried out purely for reasons of improving performance. It maybe efficient for a
high-throughput system to replicate data for certain data.
9. What is the advantage of using PreparedStatement? - If we are using
PreparedStatement the execution time will be less. The PreparedStatement object
contains not just an SQL statement, but the SQL statement that has been
precompiled. This means that when the PreparedStatement is executed,the
RDBMS can just run the PreparedStatement’s Sql statement without having to
compile it first.
10. What is a “dirty read”? - Quite often in database processing, we come across
the situation wherein one transaction can change a value, and a second transaction
can read this value before the original change has been committed or rolled back.
This is known as a dirty read scenario because there is always the possibility that
the first transaction may rollback the change, resulting in the second transaction
having read an invalid value. While you can easily command a database to
disallow dirty reads, this usually degrades the performance of your application
due to the increased locking overhead. Disallowing dirty reads also leads to
decreased system concurrency.
11. What is Metadata and why should I use it? - Metadata (’data about data’) is
information about one of two things: Database information
(java.sql.DatabaseMetaData), or Information about a specific ResultSet
(java.sql.ResultSetMetaData). Use DatabaseMetaData to find information about
your database, such as its capabilities and structure. Use ResultSetMetaData to
find information about the results of an SQL query, such as size and types of
columns
12. Different types of Transaction Isolation Levels? - The isolation level describes
the degree to which the data being updated is visible to other transactions. This is
important when two transactions are trying to read the same row of a table.
Imagine two transactions: A and B. Here three types of inconsistencies can occur:
o Dirty-read: A has changed a row, but has not committed the changes. B
reads the uncommitted data but his view of the data may be wrong if A
rolls back his changes and updates his own changes to the database.
o Non-repeatable read: B performs a read, but A modifies or deletes that
data later. If B reads the same row again, he will get different data.
o Phantoms: A does a query on a set of rows to perform an operation. B
modifies the table such that a query of A would have given a different
result. The table may be inconsistent.

TRANSACTION_READ_UNCOMMITTED : DIRTY READS, NON-


REPEATABLE READ AND PHANTOMS CAN OCCUR.
TRANSACTION_READ_COMMITTED : DIRTY READS ARE PREVENTED,
NON-REPEATABLE READ AND PHANTOMS CAN OCCUR.
TRANSACTION_REPEATABLE_READ : DIRTY READS , NON-
REPEATABLE READ ARE PREVENTED AND PHANTOMS CAN OCCUR.
TRANSACTION_SERIALIZABLE : DIRTY READS, NON-REPEATABLE
READ AND PHANTOMS ARE PREVENTED.

13. What is 2 phase commit? - A 2-phase commit is an algorithm used to ensure the
integrity of a committing transaction. In Phase 1, the transaction coordinator
contacts potential participants in the transaction. The participants all agree to
make the results of the transaction permanent but do not do so immediately. The
participants log information to disk to ensure they can complete In phase 2 f all
the participants agree to commit, the coordinator logs that agreement and the
outcome is decided. The recording of this agreement in the log ends in Phase 2,
the coordinator informs each participant of the decision, and they permanently
update their resources.
14. How do you handle your own transaction ? - Connection Object has a method
called setAutocommit(Boolean istrue)
- Default is true. Set the Parameter to false , and begin your transaction
15. What is the normal procedure followed by a java client to access the db.? -
The database connection is created in 3 steps:

1. Find a proper database URL


2. Load the database driver
3. Ask the Java DriverManager class to open a connection to your database

In java code, the steps are realized in code as follows:

4. Create a properly formatted JDBR URL for your database. (See FAQ on JDBC
URL for more information). A JDBC URL has the form
jdbc:someSubProtocol://myDatabaseServer/theDatabaseName
5. Class.forName(”my.database.driver”);
6. Connection conn = DriverManager.getConnection(”a.JDBC.URL”,
“databaseLogin”,”databasePassword”);
2. What is a data source? - A DataSource class brings another level of abstraction
than directly using a connection object. Data source can be referenced by JNDI.
Data Source may point to RDBMS, file System , any DBMS etc.
3. What are collection pools? What are the advantages? - A connection pool is a
cache of database connections that is maintained in memory, so that the
connections may be reused
4. How do you get Column names only for a table (SQL Server)? Write the
Query. -
5. select name from syscolumns
6. where id=(select id from sysobjects where
name='user_hdr')
7. order by colid --user_hdr is the table name
8. What are the steps involved in establishing a JDBC connection? This action
involves two steps: loading the JDBC driver and making the connection.
9. How can you load the drivers?
Loading the driver or drivers you want to use is very simple and involves just one
line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the
following code will load it:

Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);

Your driver documentation will give you the class name to use. For instance, if
the class name is jdbc.DriverXYZ, you would load the driver with the following
line of code:

Class.forName(”jdbc.DriverXYZ”);

10. What will Class.forName do while loading drivers? It is used to create an


instance of a driver and register it with the
DriverManager. When you have loaded a driver, it is available for making a
connection with a DBMS.
11. How can you make the connection? To establish a connection you need to have
the appropriate driver connect to the DBMS.
The following line of code illustrates the general idea:

String url = “jdbc:odbc:Fred”;


Connection con = DriverManager.getConnection(url, “Fernanda”, “J8?);

12. How can you create JDBC statements and what are they?
A Statement object is what sends your SQL statement to the DBMS. You simply
create a Statement object and then execute it, supplying the appropriate execute
method with the SQL statement you want to send. For a SELECT statement, the
method to use is executeQuery. For statements that create or modify tables, the
method to use is executeUpdate. It takes an instance of an active connection to
create a Statement object. In the following example, we use our Connection object
con to create the Statement object

Statement stmt = con.createStatement();

13. How can you retrieve data from the ResultSet?


JDBC returns results in a ResultSet object, so we need to declare an instance of
the class ResultSet to hold our results. The following code demonstrates declaring
the ResultSet object rs.

ResultSet rs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM


COFFEES”);
String s = rs.getString(”COF_NAME”);

The method getString is invoked on the ResultSet object rs, so getString() will
retrieve (get) the value stored in the column COF_NAME in the current row of rs.

14. What are the different types of Statements?


Regular statement (use createStatement method), prepared statement (use
prepareStatement method) and callable statement (use prepareCall)
15. How can you use PreparedStatement? This special type of statement is derived
from class Statement.If you need a
Statement object to execute many times, it will normally make sense to use a
PreparedStatement object instead. The advantage to this is that in most cases, this
SQL statement will be sent to the DBMS right away, where it will be compiled.
As a result, the PreparedStatement object contains not just an SQL statement, but
an SQL statement that has been precompiled. This means that when the
PreparedStatement is executed, the DBMS can just run the PreparedStatement’s
SQL statement without having to compile it first.
16. PreparedStatement updateSales =
17. con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE
COF_NAME LIKE ?");
18. What does setAutoCommit do?
When a connection is created, it is in auto-commit mode. This means that each
individual SQL statement is treated as a transaction and will be automatically
committed right after it is executed. The way to allow two or more statements to
be grouped into a transaction is to disable auto-commit mode:

con.setAutoCommit(false);

Once auto-commit mode is disabled, no SQL statements will be committed until


you call the method commit explicitly.

con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE
COF_NAME LIKE ?");
updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE
COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
19. How do you call a stored procedure from JDBC?
The first step is to create a CallableStatement object. As with Statement an and
PreparedStatement objects, this is done with an open
Connection object. A CallableStatement object contains a call to a stored
procedure.
20. CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
21. ResultSet rs = cs.executeQuery();
22. How do I retrieve warnings?
SQLWarning objects are a subclass of SQLException that deal with database
access warnings. Warnings do not stop the execution of an
application, as exceptions do; they simply alert the user that something did not
happen as planned. A warning can be reported on a
Connection object, a Statement object (including PreparedStatement and
CallableStatement objects), or a ResultSet object. Each of these
classes has a getWarnings method, which you must invoke in order to see the first
warning reported on the calling object:
23. SQLWarning warning = stmt.getWarnings();
24. if (warning != null)
25. {
26. System.out.println("n---Warning---n");
27. while (warning != null)
28. {
29. System.out.println("Message: " +
warning.getMessage());
30. System.out.println("SQLState: " +
warning.getSQLState());
31. System.out.print("Vendor error code: ");
32. System.out.println(warning.getErrorCode());
33. System.out.println("");
34. warning = warning.getNextWarning();
35. }
36. }
37. How can you move the cursor in scrollable result sets?
One of the new features in the JDBC 2.0 API is the ability to move a result set’s
cursor backward as well as forward. There are also methods that let you move the
cursor to a particular row and check the position of the cursor.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,


ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM
COFFEES”);

The first argument is one of three constants added to the ResultSet API to indicate
the type of a ResultSet object: TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The
second argument is one of two ResultSet constants for specifying whether a result
set is read-only or updatable: CONCUR_READ_ONLY and
CONCUR_UPDATABLE. The point to remember here is that if you specify a
type, you must also specify whether it is read-only or updatable. Also, you must
specify the type first, and because both parameters are of type int , the compiler
will not complain if you switch the order. Specifying the constant
TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in
which the cursor moves only forward. If you do not specify any constants for the
type and updatability of a ResultSet object, you will automatically get one that is
TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

38. What’s the difference between TYPE_SCROLL_INSENSITIVE , and


TYPE_SCROLL_SENSITIVE?
You will get a scrollable ResultSet object if you specify one of these ResultSet
constants.The difference between the two has to do with whether a result set
reflects changes that are made to it while it is open and whether certain methods
can be called to detect these changes. Generally speaking, a result set that is
TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still
open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result
sets will make changes visible if they are closed and then reopened:
39. Statement stmt =
40. con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
41. ResultSet srs =
42. stmt.executeQuery("SELECT COF_NAME, PRICE FROM
COFFEES");
43. srs.afterLast();
44. while (srs.previous())
45. {
46. String name = srs.getString("COF_NAME");
47. float price = srs.getFloat("PRICE");
48. System.out.println(name + " " + price);
49. }
50. How to Make Updates to Updatable Result Sets?
Another new feature in the JDBC 2.0 API is the ability to update rows in a result
set using methods in the Java programming language rather than having to send
an SQL command. But before you can take advantage of this capability, you need
to create a ResultSet object that is updatable. In order to do this, you supply the
ResultSet constant CONCUR_UPDATABLE to the createStatement method.
51. Connection con =
52.
DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
53. Statement stmt =
54. con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
55. ResultSet uprs =
56. stmt.executeQuery("SELECT COF_NAME, PRICE FROM
COFFEES");
PL/SQL

1. Which of the following statements is true about implicit cursors?


1. Implicit cursors are used for SQL statements that are not named.
2. Developers should use implicit cursors with great care.
3. Implicit cursors are used in cursor for loops to handle data processing.
4. Implicit cursors are no longer a feature in Oracle.
2. Which of the following is not a feature of a cursor FOR loop?
1. Record type declaration.
2. Opening and parsing of SQL statements.
3. Fetches records from cursor.
4. Requires exit condition to be defined.
3. A developer would like to use referential datatype declaration on a variable.
The variable name is EMPLOYEE_LASTNAME, and the corresponding
table and column is EMPLOYEE, and LNAME, respectively. How would the
developer define this variable using referential datatypes?
1. Use employee.lname%type.
2. Use employee.lname%rowtype.
3. Look up datatype for EMPLOYEE column on LASTNAME table and use
that.
4. Declare it to be type LONG.
4. Which three of the following are implicit cursor attributes?
1. %found
2. %too_many_rows
3. %notfound
4. %rowcount
5. %rowtype
5. If left out, which of the following would cause an infinite loop to occur in a
simple loop?
1. LOOP
2. END LOOP
3. IF-THEN
4. EXIT
6. Which line in the following statement will produce an error?
1. cursor action_cursor is
2. select name, rate, action
3. into action_record
4. from action_table;
5. There are no errors in this statement.
7. The command used to open a CURSOR FOR loop is
1. open
2. fetch
3. parse
4. None, cursor for loops handle cursor opening implicitly.
8. What happens when rows are found using a FETCH statement
1. It causes the cursor to close
2. It causes the cursor to open
3. It loads the current row values into variables
4. It creates the variables to hold the current row values
9. Read the following code:
10. CREATE OR REPLACE PROCEDURE find_cpt
11. (v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument
mode} NUMBER)
12. IS
13. BEGIN
14. IF v_cost_per_ticket > 8.5 THEN
15. SELECT cost_per_ticket
16. INTO v_cost_per_ticket
17. FROM gross_receipt
18. WHERE movie_id = v_movie_id;
19. END IF;
20. END;

Which mode should be used for V_COST_PER_TICKET?

1. IN
2. OUT
3. RETURN
4. IN OUT
21. Read the following code:
22. CREATE OR REPLACE TRIGGER update_show_gross
23. {trigger information}
24. BEGIN
25. {additional code}
26. END;

The trigger code should only execute when the column, COST_PER_TICKET, is
greater than $3. Which trigger information will you add?
1. WHEN (new.cost_per_ticket > 3.75)
2. WHEN (:new.cost_per_ticket > 3.75
3. WHERE (new.cost_per_ticket > 3.75)
4. WHERE (:new.cost_per_ticket > 3.75)
27. What is the maximum number of handlers processed before the PL/SQL
block is exited when an exception occurs?
1. Only one
2. All that apply
3. All referenced
4. None
28. For which trigger timing can you reference the NEW and OLD qualifiers?
1. Statement and Row
2. Statement only
3. Row only
4. Oracle Forms trigger
29. Read the following code:
30. CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)
31. RETURN number IS
32.
33. v_yearly_budget NUMBER;
34.
35. BEGIN
36. SELECT yearly_budget
37. INTO v_yearly_budget
38. FROM studio
39. WHERE id = v_studio_id;
40.
41. RETURN v_yearly_budget;
42. END;

Which set of statements will successfully invoke this function within


SQL*Plus?

1. VARIABLE g_yearly_budget NUMBER


EXECUTE g_yearly_budget := GET_BUDGET(11);
2. VARIABLE g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
3. VARIABLE :g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
4. VARIABLE g_yearly_budget NUMBER
:g_yearly_budget := GET_BUDGET(11);
43. CREATE OR REPLACE PROCEDURE update_theater
44. (v_name IN VARCHAR v_theater_id IN NUMBER) IS
45. BEGIN
46. UPDATE theater
47. SET name = v_name
48. WHERE id = v_theater_id;
49. END update_theater;
50. When invoking this procedure, you encounter the error:
ORA-000: Unique constraint(SCOTT.THEATER_NAME_UK) violated.

How should you modify the function to handle this error?

1. An user defined exception must be declared and associated with the error
code and handled in the EXCEPTION section.
2. Handle the error in EXCEPTION section by referencing the error code
directly.
3. Handle the error in the EXCEPTION section by referencing the
UNIQUE_ERROR predefined exception.
4. Check for success by checking the value of SQL%FOUND immediately
after the UPDATE statement.
51. Read the following code:
52. CREATE OR REPLACE PROCEDURE calculate_budget IS
53. v_budget studio.yearly_budget%TYPE;
54. BEGIN
55. v_budget := get_budget(11);
56. IF v_budget < 30000
57. THEN
58. set_budget(11,30000000);
59. END IF;
60. END;

You are about to add an argument to CALCULATE_BUDGET. What effect


will this have?

1. The GET_BUDGET function will be marked invalid and must be


recompiled before the next execution.
2. The SET_BUDGET function will be marked invalid and must be
recompiled before the next execution.
3. Only the CALCULATE_BUDGET procedure needs to be recompiled.
4. All three procedures are marked invalid and must be recompiled.
61. Which procedure can be used to create a customized error message?
1. RAISE_ERROR
2. SQLERRM
3. RAISE_APPLICATION_ERROR
4. RAISE_SERVER_ERROR
62. The CHECK_THEATER trigger of the THEATER table has been disabled.
Which command can you issue to enable this trigger?
1. ALTER TRIGGER check_theater ENABLE;
2. ENABLE TRIGGER check_theater;
3. ALTER TABLE check_theater ENABLE check_theater;
4. ENABLE check_theater;
63. Examine this database trigger
64. CREATE OR REPLACE TRIGGER prevent_gross_modification
65. {additional trigger information}
66. BEGIN
67. IF TO_CHAR(sysdate, DY) = MON
68. THEN
69. RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be
deleted on Monday);
70. END IF;
71. END;

This trigger must fire before each DELETE of the GROSS_RECEIPT table.
It should fire only once for the entire DELETE statement. What additional
information must you add?

1. BEFORE DELETE ON gross_receipt


2. AFTER DELETE ON gross_receipt
3. BEFORE (gross_receipt DELETE)
4. FOR EACH ROW DELETED FROM gross_receipt
72. Examine this function:
73. CREATE OR REPLACE FUNCTION set_budget
74. (v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS
75. BEGIN
76. UPDATE studio
77. SET yearly_budget = v_new_budget
78. WHERE id = v_studio_id;
79.
80. IF SQL%FOUND THEN
81. RETURN TRUEl;
82. ELSE
83. RETURN FALSE;
84. END IF;
85.
86. COMMIT;
87. END;

Which code must be added to successfully compile this function?

1. Add RETURN right before the IS keyword.


2. Add RETURN number right before the IS keyword.
3. Add RETURN boolean right after the IS keyword.
4. Add RETURN boolean right before the IS keyword.
88. Under which circumstance must you recompile the package body after
recompiling the package specification?
1. Altering the argument list of one of the package constructs
2. Any change made to one of the package constructs
3. Any SQL statement change made to one of the package constructs
4. Removing a local variable from the DECLARE section of one of the
package constructs
89. Procedure and Functions are explicitly executed. This is different from a
database trigger. When is a database trigger executed?
1. When the transaction is committed
2. During the data manipulation statement
3. When an Oracle supplied package references the trigger
4. During a data manipulation statement and when the transaction is
committed
90. Which Oracle supplied package can you use to output values and messages
from database triggers, stored procedures and functions within SQL*Plus?
1. DBMS_DISPLAY
2. DBMS_OUTPUT
3. DBMS_LIST
4. DBMS_DESCRIBE
91. What occurs if a procedure or function terminates with failure without being
handled?
1. Any DML statements issued by the construct are still pending and can be
committed or rolled back.
2. Any DML statements issued by the construct are committed
3. Unless a GOTO statement is used to continue processing within the
BEGIN section, the construct terminates.
4. The construct rolls back any DML statements issued and returns the
unhandled exception to the calling environment.
92. Examine this code
93. BEGIN
94. theater_pck.v_total_seats_sold_overall :=
theater_pck.get_total_for_year;
95. END;

For this code to be successful, what must be true?

1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the


GET_TOTAL_FOR_YEAR function must exist only in the body of the
THEATER_PCK package.
2. Only the GET_TOTAL_FOR_YEAR variable must exist in the
specification of the THEATER_PCK package.
3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in
the specification of the THEATER_PCK package.
4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the
GET_TOTAL_FOR_YEAR function must exist in the specification of the
THEATER_PCK package.
96. A stored function must return a value based on conditions that are
determined at runtime. Therefore, the SELECT statement cannot be hard-
coded and must be created dynamically when the function is executed.
Which Oracle supplied package will enable this feature?
1. DBMS_DDL
2. DBMS_DML
3. DBMS_SYN
4. DBMS_SQL
97. Which of the following statements contains an error?
1. SELECT * FROM emp WHERE empid = 493945;
2. SELECT empid FROM emp WHERE empid= 493945;
3. SELECT empid FROM emp;
4. SELECT empid WHERE empid = 56949 AND lastname = ‘SMITH’;
98. Which of the following correctly describes how to specify a column alias?
1. Place the alias at the beginning of the statement to describe the table.
2. Place the alias after each column, separated by white space, to describe the
column.
3. Place the alias after each column, separated by a comma, to describe the
column.
4. Place the alias at the end of the statement to describe the table.
99. The NVL function
1. Assists in the distribution of output across multiple columns.
2. Allows the user to specify alternate output for non-null column values.
3. Allows the user to specify alternate output for null column values.
4. Nullifies the value of the column output.
100. Output from a table called PLAYS with two columns, PLAY_NAME
and AUTHOR, is shown below. Which of the following SQL statements
produced it?

PLAY_TABLE
————————————-
“Midsummer Night’s Dream”, SHAKESPEARE
“Waiting For Godot”, BECKETT
“The Glass Menagerie”, WILLIAMS

1.SELECT play_name || author FROM plays;


2.SELECT play_name, author FROM plays;
3.SELECT play_name||’, ‘ || author FROM plays;
4.SELECT play_name||’, ‘ || author PLAY_TABLE FROM plays;
101. Issuing the DEFINE_EDITOR=”emacs” will produce which
outcome?
1. The emacs editor will become the SQL*Plus default text editor.
2. The emacs editor will start running immediately.
3. The emacs editor will no longer be used by SQL*Plus as the default text
editor.
4. The emacs editor will be deleted from the system.
102. The user issues the following statement. What will be displayed if the
EMPID selected is 60494?

SELECT DECODE(empid,38475, “Terminated”,60494, “LOA”, “ACTIVE”)


FROM emp;

1.
60494
2.
LOA
3.
Terminated
4.
ACTIVE
103. SELECT (TO_CHAR(NVL(SQRT(59483), “INVALID”)) FROM
DUAL is a valid SQL statement.
1. TRUE
2. FALSE
104. The appropriate table to use when performing arithmetic calculations
on values defined within the SELECT statement (not pulled from a table
column) is
1. EMP
2. The table containing the column values
3. DUAL
4. An Oracle-defined table
105. Which of the following is not a group function?
1. avg( )
2. sqrt( )
3. sum( )
4. max( )
106. Once defined, how long will a variable remain so in SQL*Plus?
1. Until the database is shut down
2. Until the instance is shut down
3. Until the statement completes
4. Until the session completes
107. The default character for specifying runtime variables in SELECT
statements is
1. Ampersand
2. Ellipses
3. Quotation marks
4. Asterisk
108. A user is setting up a join operation between tables EMP and DEPT.
There are some employees in the EMP table that the user wants returned by
the query, but the employees are not assigned to departments yet. Which
SELECT statement is most appropriate for this user?
1. select e.empid, d.head from emp e, dept d;
2. select e.empid, d.head from emp e, dept d where e.dept# = d.dept#;
3. select e.empid, d.head from emp e, dept d where e.dept# = d.dept# (+);
4. select e.empid, d.head from emp e, dept d where e.dept# (+) = d.dept#;
109. Developer ANJU executes the following statement: CREATE TABLE
animals AS SELECT * from MASTER.ANIMALS; What is the effect of this
statement?
1. A table named ANIMALS will be created in the MASTER schema with
the same data as the ANIMALS table owned by ANJU.
2. A table named ANJU will be created in the ANIMALS schema with the
same data as the ANIMALS table owned by MASTER.
3. A table named ANIMALS will be created in the ANJU schema with the
same data as the ANIMALS table owned by MASTER.
4. A table named MASTER will be created in the ANIMALS schema with
the same data as the ANJU table owned by ANIMALS.
110. User JANKO would like to insert a row into the EMPLOYEE table,
which has three columns: EMPID, LASTNAME, and SALARY. The user
would like to enter data for EMPID 59694, LASTNAME Harris, but no
salary. Which statement would work best?
1. INSERT INTO employee VALUES (59694,’HARRIS’, NULL);
2. INSERT INTO employee VALUES (59694,’HARRIS’);
3. INSERT INTO employee (EMPID, LASTNAME, SALARY) VALUES
(59694,’HARRIS’);
4. INSERT INTO employee (SELECT 59694 FROM ‘HARRIS’);
111. Which three of the following are valid database datatypes in Oracle?
(Choose three.)
1. CHAR
2. VARCHAR2
3. BOOLEAN
4. NUMBER
112. Omitting the WHERE clause from a DELETE statement has which of
the following effects?
1. The delete statement will fail because there are no records to delete.
2. The delete statement will prompt the user to enter criteria for the deletion
3. The delete statement will fail because of syntax error.
4. The delete statement will remove all records from the table.
113. Creating a foreign-key constraint between columns of two tables
defined with two different datatypes will produce an error.
1. TRUE
2. FALSE
114. Dropping a table has which of the following effects on a nonunique
index created for the table?
1. No effect.
2. The index will be dropped.
3. The index will be rendered invalid.
4. The index will contain NULL values.
115. To increase the number of nullable columns for a table,
1. Use the alter table statement.
2. Ensure that all column values are NULL for all rows.
3. First increase the size of adjacent column datatypes, then add the column.
4. Add the column, populate the column, then add the NOT NULL
constraint.
116. Which line of the following statement will produce an error?
1. CREATE TABLE goods
2. (good_no NUMBER,
3. good_name VARCHAR2 check(good_name in (SELECT name FROM
avail_goods)),
4. CONSTRAINT pk_goods_01
5. PRIMARY KEY (goodno));
6. There are no errors in this statement.
117. MAXVALUE is a valid parameter for sequence creation.
1. TRUE
2. FALSE
118. Which of the following lines in the SELECT statement below contain
an error?
1.SELECT DECODE(empid, 58385, “INACTIVE”, “ACTIVE”) empid
2.FROM emp
3.WHERE SUBSTR(lastname,1,1) > TO_NUMBER(’S')
4.AND empid > 02000
5.ORDER BY empid DESC, lastname ASC;
6.There are no errors in this statement.
119. Which function below can best be categorized as similar in function to
an IF-THEN-ELSE statement?
1. SQRT
2. DECODE
3. NEW_TIME
4. ROWIDTOCHAR
120. Which two of the following orders are used in ORDER BY clauses?
(choose two)
1. ABS
2. ASC
3. DESC
4. DISC
121. You query the database with this command

SELECT name
FROM employee
WHERE name LIKE ‘_a%’;

Which names are displayed?

1. Names starting with “a”


2. Names starting with “aR
3. or “A”
4. Names containing “aR
5. as second character
6. Names containing “aR
7. as any letter except the first

UML

1. What is UML? UML is Unified Modeling Language. It is a graphical language


for visualizing specifying constructing and documenting the artifacts of the
system. It allows you to create a blue print of all the aspects of the system, before
actually physically implementing the system.
2. What is modeling? What are the advantages of creating a model? Modeling is
a proven and well-accepted engineering technique which helps build a model.
Model is a simplification of reality; it is a blueprint of the actual system that needs
to be built. Model helps to visualize the system. Model helps to specify the
structural and behavior of the system. Model helps make templates for
constructing the system. Model helps document the system.
3. What are the different views that are considered when building an object-
oriented software system? Normally there are 5 views. Use Case view - This
view exposes the requirements of a system. Design View - Capturing the
vocabulary. Process View - modeling the distribution of the systems processes
and threads. Implementation view - addressing the physical implementation of the
system. Deployment view - focus on the modeling the components required for
deploying the system.
4. What are diagrams? Diagrams are graphical representation of a set of elements
most often shown made of things and associations.
5. What are the major three types of modeling used? Major three types of
modeling are structural, behavioral, and architectural.
6. Mention the different kinds of modeling diagrams used? Modeling diagrams
that are commonly used are, there are 9 of them. Use case diagram, Class
Diagram, Object Diagram, Sequence Diagram, statechart Diagram, Collaboration
Diagram, Activity Diagram, Component diagram, Deployment Diagram.
7. What is Architecture? Architecture is not only taking care of the structural and
behavioral aspect of a software system but also taking into account the software
usage, functionality, performance, reuse, economic and technology constraints.
8. What is SDLC? SDLC is Software Development Life Cycle. SDLC of a system
included processes that are Use case driven, Architecture centric and Iterative and
Incremental. This Life cycle is divided into phases. Phase is a time span between
two milestones. The milestones are Inception, Elaboration, Construction, and
Transition. Process Workflows that evolve through these phase are Business
Modeling, Requirement gathering, Analysis and Design, Implementation, Testing,
Deployment. Supporting Workflows are Configuration and change management,
Project management.
9. What are Relationships? There are different kinds of relationships:
Dependencies, Generalization, and Association. Dependencies are relations ships
between two entities that that a change in specification of one thing may affect
another thing. Most commonly it is used to show that one class uses another class
as an argument in the signature of the operation. Generalization is relationships
specified in the class subclass scenario, it is shown when one entity inherits from
other. Associations are structural relationships that are: a room has walls, Person
works for a company. Aggregation is a type of association where there is a has a
relation ship, That is a room has walls, �o if there are two classes room and
walls then the relation ship is called a association and further defined as an
aggregation.
10. How are the diagrams divided? The nine diagrams are divided into static
diagrams and dynamic diagrams.
11. Static Diagrams (Also called Structural Diagram): Class diagram, Object
diagram, Component Diagram, Deployment diagram.
12. Dynamic Diagrams (Also called Behavioral Diagrams): Use Case Diagram,
Sequence Diagram, Collaboration Diagram, Activity diagram, Statechart diagram.
13. What are Messages? A message is the specification of a communication, when a
message is passed that results in action that is in turn an executable statement.
14. What is an Use Case? A use case specifies the behavior of a system or a part of a
system, �se cases are used to capture the behavior that need to be developed. It
involves the interaction of actors and the system.

DataBase Management

What is a Cartesian product? What causes it?

Expected answer:
A Cartesian product is the result of an unrestricted join of two or more tables. The result
set of a three table Cartesian product will have x * y * z number of rows where x, y, z
correspond to the number of rows in each table involved in the join. It is causes by
specifying a table in the FROM clause without joining it to another table.

2. What is an advantage to using a stored procedure as opposed to passing an SQL


query from an application.

Expected answer:
A stored procedure is pre-loaded in memory for faster execution. It allows the DBMS
control of permissions for security purposes. It also eliminates the need to recompile
components when minor changes occur to the database.

3. What is the difference of a LEFT JOIN and an INNER JOIN statement?

Expected answer:
A LEFT JOIN will take ALL values from the first declared table and matching values
from the second declared table based on the column the join has been declared on. An
INNER JOIN will take only matching values from both tables

4. When a query is sent to the database and an index is not being used, what type of
execution is taking place?

Expected answer:
A table scan.

5. What are the pros and cons of using triggers?

Expected answer:
A trigger is one or more statements of SQL that are being executed in event of data
modification in a table to which the trigger belongs.

Triggers enhance the security, efficiency, and standardization of databases.


Triggers can be beneficial when used:
– to check or modify values before they are actually updated or inserted in the database.
This is useful if you need to transform data from the way the user sees it to some internal
database format.
– to run other non-database operations coded in user-defined functions
– to update data in other tables. This is useful for maintaining relationships between data
or in keeping audit trail information.
– to check against other data in the table or in other tables. This is useful to ensure data
integrity when referential integrity constraints aren’t appropriate, or when table check
constraints limit checking to the current table only.

6. What are the pros and cons of using stored procedures. When would you use
them?

7. What are the pros and cons of using cursors? When would you use them?

You might also like