EJB Interview Questions
EJB Interview Questions
Q:The EJB container implements the EJBHome and EJBObject classes. For
every request from a unique client, does the container create a separate
instance of the generated EJBHome and EJBObject classes?
A: The EJB container maintains an instance pool. The container uses these instances
for the EJB Home reference irrespective of the client request. while refering the
EJB Object classes the container creates a separate instance for each client
request. The instance pool maintainence is up to the implementation of the
container. If the container provides one, it is available otherwise it is not
mandatory for the provider to implement it. Having said that, yes most of the
container providers implement the pooling functionality to increase the
performance of the application server. The way it is implemented is again up to the
implementer.
[ Received from Vishal Khasgiwala ] TOP
Q:Can the primary key in the entity bean be a Java primitive type such as
int?
A: The primary key can't be a primitive type--use the primitive wrapper classes,
instead. For example, you can use java.lang.Integer as the primary key class, but
not int (it has to be a class, not a primitive)
[ Received from Prasanna Inamanamelluri ] TOP
Some EJB containers, such as BEA WebLogic, provide the ability to tune the
container to minimize passivation calls.
Taken from the WebLogic 6.0 DTD -"The passivation-strategy can be either
"default" or "transaction". With the default setting the container will attempt to
keep a working set of beans in the cache. With the "transaction" setting, the
container will passivate the bean after every transaction (or method call for a non-
transactional invocation).
[ Received from Prasanna Inamanamelluri ] TOP
Q:What is the advantage of using Entity bean for database operations, over
directly using JDBC API to do database operations? When would I use one
over the other?
A: Entity Beans actually represents the data in a database. It is not that Entity Beans
replaces JDBC API. There are two types of Entity Beans Container Managed and
Bean Mananged. In Container Managed Entity Bean - Whenever the instance of
the bean is created the container automatically retrieves the data from the
DB/Persistance storage and assigns to the object variables in bean for user to
manipulate or use them. For this the developer needs to map the fields in the
database to the variables in deployment descriptor files (which varies for each
vendor).
In the Bean Managed Entity Bean - The developer has to specifically make
connection, retrive values, assign them to the objects in the ejbLoad() which will
be called by the container when it instatiates a bean object. Similarly in the
ejbStore() the container saves the object values back the the persistance storage.
ejbLoad and ejbStore are callback methods and can be only invoked by the
container. Apart from this, when you use Entity beans you dont need to worry
about database transaction handling, database connection pooling etc. which are
taken care by the ejb container. But in case of JDBC you have to explicitly do the
above features. what suresh told is exactly perfect. ofcourse, this comes under the
database transations, but i want to add this. the great thing about the entity
beans of container managed, whenever the connection is failed during the
transaction processing, the database consistancy is mantained automatically. the
container writes the data stored at persistant storage of the entity beans to the
database again to provide the database consistancy. where as in jdbc api, we,
developers has to do manually.
[ Received from Prasanna Inamanamelluri ] TOP
Many developers are using EJBs locally -- that is, some or all of their EJB calls are
between beans in a single container.
With this feedback in mind, the EJB 2.0 expert group has created a local interface
mechanism. The local interface may be defined for a bean during development, to
allow streamlined calls to the bean if a caller is in the same container. This does
not involve the overhead involved with RMI like marshalling etc. This facility will
thus improve the performance of applications in which co-location is planned.
Q:What are the special design care that must be taken when you work with
local interfaces?
A: EIt is important to understand that the calling semantics of local interfaces are
different from those of remote interfaces. For example, remote interfaces pass
parameters using call-by-value semantics, while local interfaces use call-by-
reference.
This means that in order to use local interfaces safely, application developers need
to carefully consider potential deployment scenarios up front, then decide which
interfaces can be local and which remote, and finally, develop the application code
with these choices in mind.
While EJB 2.0 local interfaces are extremely useful in some situations, the long-
term costs of these choices, especially when changing requirements and
component reuse are taken into account, need to be factored into the design
decision.
[ Received from Prasanna Inamanamelluri ] TOP
In case of stateful session bean, the bean may be kept in cache till either the
session times out, in which case the bean is removed or when there is a
requirement for memory in which case the data is cached and the bean is sent to
free pool.
[ Received from Prasanna Inamanamelluri ] TOP
Note: Only the container directly interacts with a message-driven bean by creating
bean instances and passing JMS messages to those instances as necessary.
Q:The EJB container implements the EJBHome and EJBObject classes. For
every request from a unique client, does the container create a separate
instance of the generated EJBHome and EJBObject classes?
A: The EJB container maintains an instance pool. The container uses these instances
for the EJB Home reference irrespective of the client request. While refering the
EJB Object classes the container creates a separate instance for each client
request. The instance pool maintainence is up to the implementation of the
container. If the container provides one, it is available otherwise it is not
mandatory for the provider to implement it. Having said that, yes most of the
container providers implement the pooling functionality to increase the
performance of the application server. The way it is implemented is again up to the
implementer.
Q:What is Struts?
A: The core of the Struts framework is a flexible control layer based on standard
technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as
various Jakarta Commons packages. Struts encourages application architectures
based on the Model 2 approach, a variation of the classic Model-View-Controller
(MVC) design paradigm.
Struts provides its own Controller component and integrates with other
technologies to provide the Model and the View. For the Model, Struts can interact
with standard data access technologies, like JDBC and EJB, as well as most any
third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the
View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as
Velocity Templates, XSLT, and other presentation systems.
The Struts framework provides the invisible underpinnings every professional web
application needs to survive. Struts helps you create an extensible development
environment for your application, based on published standards and proven design
patterns.
[ Received from Ramakrishna Potluri ] TOP
Q:What is ActionServlet?
A: The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In
the the Jakarta Struts Framework this class plays the role of controller. All the
requests to the server goes through the controller. Controller is responsible for
handling all the requests.
[ Received from Dhiraj Sharma] TOP
Q:How you will make available any Message Resources Definitions file to
the Struts Framework Environment?
A: T Message Resources Definitions file are simple .properties files and these files
contains the messages that can be used in the struts project. Message Resources
Definitions files can be added to the struts-config.xml file through <message-
resources /> tag.
Example:
Q:What is ActionForm?
A: An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.
ActionForm maintains the session state for web application and the ActionForm
object is automatically populated on the server side with data entered from a form
on the client side.
[ Received from Dhiraj Sharma] TOP
<html:errors/>
Q: What is ActionServlet?
A: The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the
the Jakarta Struts Framework this class plays the role of controller. All the requests to the
server goes through the controller. Controller is responsible for handling all the requests.
Q: How you will make available any Message Resources Definitions file to the Struts
Framework Environment?
A: Message Resources Definitions file are simple .properties files and these files contains
the messages that can be used in the struts project. Message Resources Definitions files
can be added to the struts-config.xml file through <message-resources /> tag.
Example:
<message-resources parameter="MessageResources" />
Q: What is Action Class?
A: The Action is part of the controller. The purpose of Action Class is to translate the
HttpServletRequest to the business logic. To use the Action, we need to Subclass and
overwrite the execute() method. The ActionServlet (commad) passes the parameterized
class to Action Form using the execute() method. There should be no database
interactions in the action. The action should receive the request, call business objects
(which then handle database, or interface with J2EE, etc) and then determine where to go
next. Even better, the business objects could be handed to the action at runtime (IoC
style) thus removing any dependencies on the model. The return type of the execute
method is ActionForward which is used by the Struts Framework to forward the request
to the file as per the value of the returned ActionForward object.
package roseindia.net;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
Q: What is ActionForm?
A: An ActionForm is a JavaBean that extends
org.apache.struts.action.ActionForm. ActionForm maintains the session state for
web application and the ActionForm object is automatically populated on the server side
with data entered from a form on the client side.
Q. How you will enable front-end validation based on the xml in validation.xml?
A: The <html:javascript> tag to allow front-end validation based on the xml in
validation.xml. For example the code: <html:javascript formName="logonForm"
dynamicJavascript="true" staticJavascript="true" /> generates the client side java script
for the form "logonForm" as defined in the validation.xml file. The <html:javascript>
when added in the jsp file generates the client site validation script.
The controller is implemented by a java servlet, this servlet is centralized point of control
for the web application. In struts framework the controller responsibilities are
implemented by several different components like
The ActionServlet Class
The RequestProcessor Class
The Action Class
All request URIs with the pattern *.do are mapped to this servlet in the deployment
descriptor as follows.
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
<url-pattern>*.do</url-pattern>
A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/actionName.do
The preceding mapping is called extension mapping, however, you can also specify path
mapping where a pattern ends with /* as shown below.
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/do/*</url-pattern>
<url-pattern>*.do</url-pattern>
A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/do/action_Name
The class org.apache.struts.action.requestProcessor process the request from the
controller. You can sublass the RequestProcessor with your own version and modify how
the request is processed.
Once the controller receives a client request, it delegates the handling of the request to a
helper class. This helper knows how to execute the business operation associated with the
requested action. In the Struts framework this helper class is descended of
org.apache.struts.action.Action class. It acts as a bridge between a client-side user action
and business operation. The Action class decouples the client request from the business
model. This decoupling allows for more than one-to-one mapping between the user
request and an action. The Action class also can perform other functions such as
authorization, logging before invoking business operation. the Struts Action class
contains several methods, but most important method is the execute() method.
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception;
The execute() method is called by the controller when a request is received from a client.
The controller creates an instance of the Action class if one doesn’t already exist. The
strut framework will create only a single instance of each Action class in your
application.
Action are mapped in the struts configuration file and this configuration is loaded into
memory at startup and made available to the framework at runtime. Each Action element
is represented in memory by an instance of the org.apache.struts.action.ActionMapping
class . The ActionMapping object contains a path attribute that is matched against a
portion of the URI of the incoming request.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
Once this is done the controller should determine which view to return to the client. The
execute method signature in Action class has a return type
org.apache.struts.action.ActionForward class. The ActionForward class represents a
destination to which the controller may send control once an action has completed.
Instead of specifying an actual JSP page in the code, you can declaratively associate as
action forward through out the application. The action forward are specified in the
configuration file.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
The action forward mappings also can be specified in a global section, independent of
any specific action mapping.
<global-forwards>
<forward name="Success" path="/action/somejsp.jsp" />
<forward name="Failure" path="/someotherjsp.jsp" />
</global-forwards>
Defines an object that receives requests from the client and sends them to any resource
(such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the
RequestDispatcher object, which is used as a wrapper around a server resource located at
a particular path or given by a particular name.
This interface is intended to wrap servlets, but a servlet container can create
RequestDispatcher objects to wrap any type of resource.
getRequestDispatcher
Returns a RequestDispatcher object that acts as a wrapper for the resource located at the
given path. A RequestDispatcher object can be used to forward a request to the resource
or to include the resource in a response. The resource can be dynamic or static.
The pathname must begin with a "/" and is interpreted as relative to the current context
root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts.
This method returns null if the ServletContext cannot return a RequestDispatcher.
Parameters:
path - a String specifying the pathname to the resource
Returns:
a RequestDispatcher object that acts as a wrapper for the resource at the specified
path
See Also:
RequestDispatcher, getContext(java.lang.String)
getNamedDispatcher
Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
Servlets (and JSP pages also) may be given names via server administration or via a web
application deployment descriptor. A servlet instance can determine its name using
ServletConfig.getServletName().
This method returns null if the ServletContext cannot return a RequestDispatcher for any
reason.
Parameters:
name - a String specifying the name of a servlet to wrap
Returns:
a RequestDispatcher object that acts as a wrapper for the named servlet
See Also:
RequestDispatcher, getContext(java.lang.String), ServletConfig.getServletName()
A very simple way to do this is to have the submit button modify a field in the form
which indicates which operation to perform.
Then, in the Action you can setup different methods to handle the different operations,
and branch to one or the other depending on which value is passed in the dispatch field.
Cool. But do you have to use a property named dispatch? No, you don't. The only other
step is to specify the name of of the dispatch property as the "parameter" property of the
action-mapping. So a mapping for our example might look like this:
<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="dispatch"/>
If you wanted to use the property "o" instead, as in o=create, you would change the
mapping to
<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="o"/>
Again, very cool. But why use a JavaScript button in the first place? Why not use several
buttons named "dispatch" and use a different value for each?
You can, but the value of the button is also its label. This means if the page designers
want to label the button something different, they have to coordinate the Action
programmer. Localization becomes virtually impossible. (Source:
http://husted.com/struts/tips/002.html).
An action can perform tasks such as validating a user name and password.
An action mapping is a configuration file entry that, in general, associates an action name
with an action. An action mapping can contain a reference to a form bean that the action
can use, and can additionally define a list of local forwards that is visible only to this
action.
An action servlet is a servlet that is started by the servlet container of a Web server to
process a request that invokes an action. The servlet receives a forward from the action
and asks the servlet container to pass the request to the forward's URL. An action servlet
must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of
that class. An action servlet is the primary component of the controller.
b) Harder to learn
Struts are harder to learn, benchmark and optimize.
<bean:write>: This tag is used to output property values from a bean. <bean:write> is a
commonly used tag which enables the programmers to easily present the data.
ActionErrors: A class that encapsulates the error messages being reported by the
validate() method of an ActionForm. Validation errors are either global to the entire
ActionForm bean they are associated with, or they are specific to a particular bean
property (and, therefore, a particular input field on the corresponding form).
key="database.error.duplicate"
path="/UserExists.jsp"
type="mybank.account.DuplicateUserException"/>
b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle
the exception.
Servlet Interview Questions
The servlet is removed from service, destroyed with the destroy() methid, then
garbaged collected and finalized.
TOP
Q:Explain ServletContext.
A: ServletContext interface is a window for a servlet to view it's environment. A
servlet can use this interface to get information such as initialization parameters
for the web applicationor servlet container's version. Every web application has
one and only one ServletContext and is accessible to all active resource of that
application.
TOP
ServletConfig: The object created after a servlet is instantiated and its default
constructor is read. It is created to pass initialization information to the servlet.
[ Received from Sivagopal Balivada ]
Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->
You can use any characters in the body of the comment except the closing --%>
combination. If you need to use --%> in your comment, you can escape it by
typing --%\>.
JSP Syntax
<%-- comment --%>
Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>
TOP
Q:What is a Expression?
A: An expression tag contains a scripting language expression that is evaluated,
converted to a String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an
expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression
TOP
Q:What is a Declaration?
A: A declaration 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
they are separated by semicolons. The declaration must be valid in the scripting
language used in the JSP file.
Q:What is a Scriptlet?
A: 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
1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).
3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean>
tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the
scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client
request. If the scriptlet produces output, the output is stored in the out object,
from which you can display it.
TOP
• exception
TOP
1. page
2. request
3.session
4.application
TOP
Question:How do I prevent the output of my JSP or Servlet pages from being cached
by the browser?
Question:How does JSP handle run-time exceptions?
Question:How can I implement a thread-safe JSP page? What are the advantages
and Disadvantages of using it?
Question:How do I use a scriptlet to initialize a newly instantiated bean?
Question: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?
Question:What's a better approach for enabling thread-safe servlets and JSPs?
SingleThreadModel Interface or Synchronization?
Question:How can I enable session tracking for JSP pages if the browser has disabled
cookies?
<%
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
%>
Q:How can I implement a thread-safe JSP page? What are the advantages
and Disadvantages of using it?
A: 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
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 .
[ Received from Sumit Dhamija ] TOP
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.
</jsp:useBean >
Q: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?
A: You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? \"\" : s;
}
%>
Also, note that SingleThreadModel is pretty resource intensive from the server\'s
perspective. The most serious issue however is when the number of concurrent
requests exhaust the servlet instance pool. In that case, all the unserviced
requests are queued until something becomes free - which results in poor
performance. Since the usage is non-deterministic, it may not help much even if
you did add more memory and increased the size of the instance pool.
Q:How can I enable session tracking for JSP pages if the browser has
disabled cookies?
A: 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.
hello1.jsp
<%@ page session=\"true\" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href=\'<%=url%>\'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is " + i.intValue());
%>
[ Received from Vishal Khasgiwala ]
Q:What is the difference b/w variable declared inside a declaration part and
variable declared in scriplet part?
A: Variable declared inside declaration part is treated as a global variable.that means
after convertion jsp file into servlet that variable will be in outside of service
method or it will be declared as instance variable.And the scope is available to
complete jsp and to complete in the converted servlet class.where as if u declare a
variable inside a scriplet that variable will be declared inside a service method and
the scope is with in the service method.
[ Received from Neelam Gangadhar] TOP
Q:Is there a way to execute a JSP from the comandline or from my own
application?
A: There is a little tool called JSPExecutor that allows you to do just that. The
developers (Hendrik Schreiber <[email protected]> & Peter Rossbach
<[email protected]>) aim was not to write a full blown servlet engine, but to provide
means to use JSP for generating source code or reports. Therefore most HTTP-
specific features (headers, sessions, etc) are not implemented, i.e. no reponseline
or header is generated. Nevertheless you can use it to precompile JSP for your
website.
[ Received from Nitin Jawarkar ] TOP
<jsp:include/>
<jsp:forward/>
<jsp:plugin/>
<jsp:usebean/>
<jsp:setProperty/>
<jsp:getProperty/>
Question: What is the difference between <jsp:include page = ... > and
<%@ include file = ... >?.
Answer: Both the tag includes the information from one page in another. The differences
are as follows:
<jsp:include page = ... >: This is like a function call from one jsp to
another jsp. It is executed ( the included page is executed and the
generated html content is included in the content of calling jsp) each
time the client page is accessed by the client. This approach is useful
to for modularizing the web application. If the included file changed
then the new content will be included in the output.
<%@ include file = ... >: In this case the content of the included file
is textually embedded in the page that have <%@ include file="..">
directive. In this case in the included file changes, the changed
content will not included in the output. This approach is used when the
code from one jsp file required to include in multiple jsp files.
Question: What is the difference between <jsp:forward page = ... > and
response.sendRedirect(url),?.
Answer: The <jsp:forward> element forwards the request object containing the client
request information from one JSP file to another file. The target file can be an HTML file,
another JSP file, or a servlet, as long as it is in the same application context as the
forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser
creates a new request to go the redirected page. The response.sendRedirect kills the
session variables.
<HTML>
<HEAD><TITLE>RESULT PAGE</TITLE></HEAD>
<BODY>
<%
%>
</BODY>
</HTML>
Suppose you access this JSP file, Find out your answer.
a) A blank page will be displayed.
b) A page with the text Welcome is displayed
c) An exception will be thrown because the implicit out object is not used
d) An exception will be thrown because PrintWriter can be used in servlets only
Question: What are all the different scope values for the <jsp:useBean> tag?
Answer:<jsp:useBean> tag is used to use any java object in the jsp page. Here are the
scope values for <jsp:useBean> tag:
a) page
b) request
c) session and
d) application
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p><%=getCount()%></p>
</body>
</html>
In the J2EE applications modules can be deployed as stand-alone units. Modules can also
be assembled into J2EE applications.
Question: What is the difference between Session Bean and Entity Bean?
Answer:
Session Bean: Session is one of the EJBs and it represents a single client inside the
Application Server. Stateless session is easy to develop and its efficient. As compare to
entity beans session beans require few server resources.
A session bean is similar to an interactive session and is not shared; it can have only one
client, in the same way that an interactive session can have only one user. A session bean
is not persistent and it is destroyed once the session terminates.
Entity Bean: An entity bean represents persistent global data from the database. Entity
beans data are stored into database.
Question: Why J2EE is suitable for the development distributed multi-tiered enterprise
applications?
Answer: The J2EE platform consists of multi-tiered distributed application model. J2EE
applications allows the developers to design and implement the business logic into
components according to business requirement. J2EE architecture allows the
development of multi-tired applications and the developed applications can be installed
on different machines depending on the tier in the multi-tiered J2EE environment . The
J2EE application parts are:
In short containers are the interface between a component and the low-level platform
specific functionality that supports the component. The application like Web, enterprise
bean, or application client component must be assembled and deployed on the J2EE
container before executing.
Question: What is difference between Java Bean and Enterprise Java Bean?
Answer: Java Bean as is a plain java class with member variables and getter setter
methods. Java Beans are defined under JavaBeans specification as Java-Based software
component model which includes the features like introspection, customization, events,
properties and persistence.
Enterprise JavaBeans or EJBs for short are Java-based software components that comply
with Java's EJB specification. EJBs are delpoyed on the EJB container and executes in
the EJB container. EJB is not that simple, it is used for building distributed applications.
Examples of EJB are Session Bean, Entity Bean and Message Driven Bean. EJB is used
for server side programming whereas java bean is a client side. Bean is only development
but the EJB is developed and then deploy on EJB Container.
The JTA specifies an architecture for building transactional application servers and
defines a set of interfaces for various components of this architecture. The components
are: the application, resource managers, and the application server. The JTA specifies
standard interfaces for Java-based applications and application servers to interact with
transactions, transaction managers, and resource managers JTA transaction management
provides a set of interfaces utilized by an application server to manage the beginning and
completion of transactions. Transaction synchronization and propagation services are also
provided under the domain of transaction management.
In the Java transaction model, the Java application components can conduct transactional
operations on JTA compliant resources via the JTS. The JTS acts as a layer over the OTS.
The applications can therefore initiate global transactions to include other OTS
transaction managers, or participate in global transactions initiated by other OTS
compliant transaction managers.
Q:I am trying to store an object using a key in a Hashtable. And some other
object already exists in that location, then what will happen? The existing
object will be overwritten? Or the new object will be stored elsewhere?
A: The existing object will be overwritten and thus it will be lost.
[ Received from Sandesh Sadhale] TOP
Q:What is an enumeration?
A: An enumeration is an interface containing methods for accessing the underlying
data structure from which the enumeration is obtained. It is a construct which
collection classes return when you request a collection of all the objects stored in
the collection. It allows sequential access to all the elements stored in the
collection.
[ Received from Sandesh Sadhale] TOP
Q:Considering the basic properties of Vector and ArrayList, where will you
use Vector and where will you use ArrayList?
A: The basic difference between a Vector and an ArrayList is that, vector is
synchronized while ArrayList is not. Thus whenever there is a possibility of multiple
threads accessing the same instance, one should use Vector. While if not multiple
threads are going to access the same instance then use ArrayList. Non
synchronized data structure will give better performance than the synchronized
one.
[ Received from Sandesh Sadhale] TOP
Q:What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a
java.util.Iterator interface. This interface allows you to walk through a collection of
objects, operating on each object in turn. Remember when using Iterators that
they contain a snapshot of the collection at the time the Iterator was obtained;
generally it is not advisable to modify the collection itself while traversing an
Iterator.
TOP
Q:What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final
method can't be overridden when its class is inherited. You can't change value of a
final variable (is a constant).
Q:What if the static modifier is removed from the signature of the main
method?
A: Program compiles. But at runtime throws an error "NoSuchMethodError".
[ Received from Sandesh Sadhale] TOP
Q:What if I write static public void instead of public static void?
A: Program compiles and runs properly.
[ Received from Sandesh Sadhale] TOP
Q:What if I do not provide the String array as the argument to the method?
A: Program compiles but throws a runtime error "NoSuchMethodError".
[ Received from Sandesh Sadhale] TOP
Q:If I do not provide any arguments on the command line, then the String
array of Main method will be empty or null?
A: It is empty. But not null.
[ Received from Sandesh Sadhale] TOP
Q:How can one prove that the array is not null but empty using one line of
code?
A: Print args.length. It will print 0. That means it is empty. But if it would have been
null then it would have thrown a NullPointerException on attempting to print
args.length.
[ Received from Sandesh Sadhale] TOP
Q:Can I import same package/class twice? Will the JVM load the package
twice at runtime?
A: One can import the same package or same class multiple times. Neither compiler
nor JVM complains abt it. And the JVM will internally load the class only once no
matter how many times you import the same class.
[ Received from Sandesh Sadhale] TOP
Q:What is Overriding?
A: When a class defines a method using the same name, return type, and arguments
as a method in its superclass, the method in the class overrides the method in the
superclass.
When the method is invoked for an object of the class, it is the new definition of
the method that is called, and not the method definition from superclass. Methods
may be overridden to be more public, not more private.
TOP
Nested top-level classes- If you declare a class within a class and specify the
static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring
class name acting similarly to a package. eg, outer.inner. Top-level inner classes
implicitly have access only to static variables.There can also be inner interfaces.
All of these are of the nested top-level variety.
Member classes - Member inner classes are just like other member methods and
member variables and access to the member class is restricted, just like methods
and variables. This means a public member class acts similarly to a nested top-
level class. The primary difference between member classes and nested top-level
classes is that member classes have access to the specific instance of the
enclosing class.
Local classes - Local classes are like local variables, specific to a block of code.
Their visibility is only within the block of their declaration. In order for the class to
be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the
modifiers public, protected, private, and static are not usable.
Anonymous classes - Anonymous inner classes extend local inner classes one
level further. As anonymous classes have no name, you cannot provide a
constructor.
Question:Are the imports checked for validity at compile time? e.g. will the code
containing an import such as java.lang.ABCD compile?
Question:Does importing a package imports the subpackages as well? e.g. Does
importing com.MyTest.* also import com.MyTest.UnitTests.*?
Question:What is the difference between declaring a variable and defining a variable?
Question:What is the default value of an object reference declared as an instance
variable?
Question:Can a top level class be private or protected?
Question:What type of parameter passing does Java support?
Question:Primitive data types are passed by reference or pass by value?
Question:Objects are passed by value or by reference?
Question:What is serialization?
Question:How do I serialize an object to a file?
Question:Which methods of Serializable interface should I implement?
Question:How can I customize the seralization process? i.e. how can one have a
control over the serialization process?
Question:What is the common usage of serialization?
Question:What is Externalizable interface?
Question:When you serialize an object, what happens to the object references
included in the object?
Question:What one should take care of while serializing the object?
Question:What happens to the static fields of a class during serialization?
Q:Are the imports checked for validity at compile time? e.g. will the code
containing an import such as java.lang.ABCD compile?
A: Yes the imports are checked for the semantic validity at compile time. The code
containing above line of import will not compile. It will throw an error saying,can
not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;
[ Received from Sandesh Sadhale] TOP
Q:What is serialization?
A: Serialization is a mechanism by which you can save the state of an object by
converting it to a byte stream.
[ Received from Sandesh Sadhale] TOP
Question:Does Java provide any construct to find out the size of an object?
Question:Give a simplest way to find out the time a method takes for execution
without using any profiling tool?
Question:What are wrapper classes?
Question:Why do we need wrapper classes?
Question:What are checked exceptions?
Question:What are runtime exceptions?
Question:What is the difference between error and an exception??
Question:How to create custom exceptions?
Question:If I want an object of my class to be thrown as an exception object, what
should I do?
Question:If my class already extends from some other class what should I do if I
want an instance of my class to be thrown as an exception object?
Question:How does an exception permeate through the code?
Question:What are the different ways to handle exceptions?
Question:What is the basic difference between the 2 approaches to exception
handling...1> try catch block and 2> specifying the candidate exceptions in
the throws clause?
When should you use which approach?
Question:Is it necessary that each try block must be followed by a catch block?
Question:If I write return at the end of the try block, will the finally block still
execute?
Question:If I write System.exit (0); at the end of the try block, will the finally block
still execute?
Q:Does Java provide any construct to find out the size of an object?
A: No there is not sizeof operator in Java. So there is not direct way to determine the
size of an object directly in Java.
[ Received from Sandesh Sadhale] TOP
Q:Give a simplest way to find out the time a method takes for execution
without using any profiling tool?
A: Read the system time just before the method is invoked and immediately after
method returns. Take the time difference, which will give you the time taken by a
method for execution.
To put it in code...
Remember that if the time taken for execution is too small, it might show that it is
taking zero milliseconds for execution. Try it on a method which is big enough, in
the sense the one which is doing considerable amout of processing.
[ Received from Sandesh Sadhale] TOP
Q:If my class already extends from some other class what should I do if I
want an instance of my class to be thrown as an exception object?
A: One can not do anytihng in this scenarion. Because Java does not allow multiple
inheritance and does not provide any exception interface as well.
[ Received from Sandesh Sadhale] TOP
Q:Is it necessary that each try block must be followed by a catch block?
A: It is not necessary that each try block must be followed by a catch block. It should
be followed by either a catch block OR a finally block. And whatever exceptions
are likely to be thrown should be declared in the throws clause of the method.
[ Received from Sandesh Sadhale] TOP
Q:If I write return at the end of the try block, will the finally block still
execute?
A: Yes even if you write return as the last statement in the try block and no exception
occurs, the finally block will execute. The finally block will execute and then the
control return.
[ Received from Sandesh Sadhale] TOP
Q:If I write System.exit (0); at the end of the try block, will the finally block
still execute?
A: No in this case the finally block will not execute because when you say
System.exit (0); the control immediately goes out of the program, and thus finally
never executes.
[ Received from Sandesh Sadhale] TOP
Q:Does garbage collection guarantee that a program will not run out of
memory?
A: 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
.
[ Received from Venkateswara Manam] TOP
Q:What is daemon thread and which method is used to create the daemon
thread?
A: 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.
[ Received from Shipra Kamra] TOP
An applet can also get references to all other applets on the same page using the
getApplets() method of java.applet.AppletContext. Once you get the reference to
an applet, you can communicate with it by using its public members.
stmt.exceuteUpdate();
Q:How does a try statement determine which catch clause should be used to
handle an exception?
A: When an exception is thrown within the body of a try statement, the catch clauses
of the try statement are examined in the order in which they appear. The first
catch clause that is capable of handling the exceptionis executed. The remaining
catch clauses are ignored.
Q:What is Externalizable?
A: 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)
[ Received from Venkateswara Manam] TOP
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.
Q:What will be the default values of all the elements of an array defined as
an instance variable?
A: If the array is an array of primitive types, then all the elements of the array will be
initialized to the default value corresponding to that primitive type. e.g. All the
elements of an array of int will be initialized to 0, while that of boolean type will be
initialized to false. Whereas if the array is an array of references (of any type), all
the elements will be initialized to null.
[ Received from Sandesh Sadhale] TOP
Question: Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and
Dialog classes.
• Interfaces provide a form of multiple inheritance. A class can extend only one
other class.
• Interfaces are limited to public methods and constants with no implementation.
Abstract classes can have a partial implementation, protected parts, static
methods, etc.
• A Class may implement several interfaces. But in case of abstract class, a class
may extend only one abstract class.
• Interfaces are slow as it requires extra indirection to to find corresponding method
in in the actual class. Abstract classes are fast.
Similarities:
• Scrollable result sets- using new methods in the ResultSet interface allows
programmatically move the to particular row or to a position relative to its current
position
• JDBC 2.0 Core API provides the Batch Updates functionality to the java
applications.
• Java applications can now use the ResultSet.updateXXX methods.
• New data types - interfaces mapping the SQL3 data types
• Custom mapping of user-defined types (UTDs)
• Miscellaneous features, including performance hints, the use of character streams,
full precision for java.math.BigDecimal values, additional security, and support
for time zones in date, time, and timestamp values.
• Public
• Protected
• Private
• Defaults
Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void