Java All Interview Question Prepared by Abhinav
Java All Interview Question Prepared by Abhinav
page
1-11
12-18
3. SERVLET FAQ 1
19-27
4.SERVLET FAQ 2
28-34
5.SESSION FAQ
34-37
6. JSP FAQ
38-47
7.STRUTS FAQ1
48-63
8.STRUTS FAQ2
64-88
9.SPRING FAQ
10. JAVA FAQ1
89-98
11.JAVA FAQ2
99-110
12.OOP FAQ
111-113
13.SPRING FAQ
114-117
14.EXCEPTION FAQ
118-124
15 COLLECTION FAQ
125-130
16 COLLECTION FAQ2
17 MULTI THREADING FAQ
18 OBJECT BASED FAQ
19 http://java4732.blogspot.in
131-140
141-154
15. If a class is declared without any access modifiers, where may the
class be accessed?
A class that is declared without any access modifiers is said to have default or
package level access. This means that the class can only be accessed by other
classes and interfaces that are defined within the same package.
16. Which class should you use to obtain design information about an
object?
The Class class is used to obtain information about an object's design.
17. What modifiers may be used with an interface declaration?
An interface may be declared as public or abstract.
18. Is a class a subclass of itself?
Yes, a class is a subclass of itself.
19. What modifiers can be used with a local inner class?
A local inner class may be final or abstract.
20. Can an abstract class be final?
An abstract class may not be declared as final. Abstract and Final are two
keywords that carry totally opposite meanings and they cannot be used together.
21. What is the difference between a public and a non-public class?
A public class may be accessed outside of its package. A non-public class may
not be accessed outside of its package.
22. What modifiers may be used with a top-level class?
A top-level class may be public, abstract, or final.
23. What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class
class is used to represent the classes and interfaces that are loaded by a Java
program.
An inner class is same as any other class, just that, is declared inside some
other class
35. How will you reference the inner class
To reference an inner class you will have to use the following syntax:
OuterClass$InnerClass
36. Can objects that are instances of inner class access the members of
the outer class
Yes they can access the members of the outer class
37. Can inner classes be static
Yes inner classes can be static, but they cannot access the non static data of
the outer classes, though they can access the static data.
38. Can an inner class be defined inside a method
Yes it can be defined inside a method and it can access data of the enclosing
methods or a formal parameter if it is final
39. What is an anonymous class
Some classes defined inside a method do not need a name, such classes are
called anonymous classes.
40. What are access modifiers
These public, protected and private, these can be applied to class, variables,
constructors and methods. But if you don't specify an access modifier then it is
considered as Friendly. They determine the accessibility or visibility of the
entities to which they are applied.
41. Can protected or friendly features be accessed from different
packages
No when features are friendly or protected they can be accessed from all the
classes in that package but not from classes in another package.
42. How can you access protected features from another package
You can access protected features from other classes by subclassing the that
class in another package, but this cannot be done for friendly features.
Why use JDBC- Before JDBC, ODBC API was the database API to connect and
execute query with the database. But, ODBC API uses ODBC driver which is
written in C language (i.e. platform dependent and unsecured). That is why Java
has defined its own API (JDBC API) that uses JDBC drivers (written in Java
language).
2- What is JDBC Driver?
JDBC Driver is a software component that enables java application to interact
with the database.There are 4 types of JDBC drivers:
JDBC-ODBC bridge driver
Advantages:
easy to use.
can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC
function calls.
The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not
written entirely in java.
Advantage:
performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is
fully written in java.
Advantage:
No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
Disadvantages:
Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java language.
Advantage:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depends on the Database.
3- What are the steps to connect to the database in java?
There are 5 steps to connect any java application with the database in java
using JDBC. They are as follows:
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection
4- What are the JDBC API components?
The java.sql package contains interfaces and classes for JDBC API.
Interfaces:
Connection
Statement
PreparedStatement
ResultSet
ResultSetMetaData
DatabaseMetaData
CallableStatement etc.
Classes:
DriverManager
Blob
Clob
Types
SQLException etc.
5- What are the JDBC statements?
There are 3 JDBC statements.
Statement
PreparedStatement
CallableStatement
6- What is the difference between Statement and PreparedStatement
interface?
In case of Statement, query is complied each time whereas in case of
PreparedStatement, query is complied only once. So performance of
PreparedStatement is better than Statement.
7- How can we execute stored procedures and functions?
15- How can we store and retrieve images from the database?
By using PreparedStatement interface, we can store and retrieve images.
----------------------------------------------------------------------------------------------------------------------------------------
As displayed in the above diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created. After
invoking the init() method, Servlet comes in the ready state. In the ready state,
servlet performs all the tasks. When the web container invokes the destroy()
method, it shifts to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet
class. The servlet instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle
method of the javax.servlet.Servlet interface. Syntax of the init method is given
below:
RequestDispacher interface
sendRedirect() method etc.
10- What is the purpose of RequestDispatcher Interface?
The RequestDispacher interface provides the facility of dispatching the request
to another resource it may be html, servlet or jsp. This interceptor can also be
used to include the content of antoher resource.
11- Can you call a jsp from the servlet?
Yes, one of the way is RequestDispatcher interface for example:
RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");
rd.forward(request,response);
12- Difference between forward() method and sendRedirect() method ?
forward() method
1) forward() sends the same request to another resource.2) forward() method
works at server side.
3) forward() method works within the server only.
sendRedirect() method
1) sendRedirect() method sends new request always because it uses the URL
bar of the browser.
2) sendRedirect() method works at client side
3) sendRedirect() method works within and outside the server.
13- What is difference between ServletConfig and ServletContext?
The container creates object of ServletConfig for each servlet whereas object of
ServletContext is created for each web application.
14- What is Session Tracking?
Session simply means a particular interval of time.
Session Tracking is a way to maintain state of an user.Http protocol is a
stateless protocol.Each time user requests to the server, server treats the
request as the new request.So we need to maintain the state of an user to
recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It
is shown in the figure given below:
Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
16- What is difference between Cookies and HttpSession?
Cookie works at client side whereas HttpSession works at server side.
17- What is filter?
A filter is an object that is invoked at the preprocessing and postprocessing of a
request.
It is mainly used to perform filtering tasks such as conversion, logging,
compression, encryption and decryption, input validation etc.
18- How can we perform any action at the time of deploying the project?
By the help of ServletContextListener interface.
19- What is the disadvantage of cookies?
It will not work if cookie is disabled from the browser.
20- How can we upload the file to the server using servlet?
One of the way is by MultipartRequest class provided by third party.
21- What is load-on-startup in servlet?
The load-on-startup element of servlet in web.xml is used to load the servlet at
the time of deploying the project or server start. So it saves time for the
response of first request.
22- What if we pass negative value in load-on-startup?
It will not affect the container, now servlet will be loaded at first request.
23- What is war file?
A war (web archive) file specifies the web elements. A servlet or jsp project can
be converted into a war file. Moving one servlet project from one place to
another will be fast as it is combined into a single file.
24- How to create war file?
The war file can be created using jar tool found in jdk/bin directory. If you are
using Eclipse or Netbeans IDE, you can export your project as a war file.
To create war file from console, you can write following code.
jar -cvf abc.war *
25- What are the annotations used in Servlet 3?
There are mainly 3 annotations used for the servlet.
@WebServlet : for servlet class.
@WebListener : for listener class.
@WebFilter : for filter class.
26- Which event is fired at the time of project deployment and
undeployment?
ServletContextEvent.
27- Which event is fired at the time of session creation and destroy?
HttpSessionEvent.
28- Which event is fired at the time of setting, getting or removing attribute
from application scope?
ServletContextAttributeEvent.
29- What is the use of welcome-file-list?
It is used to specify the welcome file for the project.
30- What is the use of attribute in servlets?
Attribute is a map object that can be used to set, get or remove in request,
session or application scope. It is mainly used to share information between one
servlet to another.
Servlet is the software specification given by sun microsystem that provide set of
rule and guideline for vendor company to develop software called servlet
container.
Servlet is single instance multiple threads based java component in Java web
application to generate dynamic web application.
2- What are the types of Servlet?
There are two types of servlets, GenericServlet and HttpServlet. GenericServlet
defines the generic or protocol independent servlet. HttpServlet is subclass of
to communicate with its servlet container, for example, to get the MIME type of a
file, dispatch requests, or write to a log file. There is one context per "web
application" per Java Virtual Machine.
13- What are the objects that are received when a servlets accepts call
from client?
The objects are:
ServeltRequest and
ServletResponse
The ServeltRequest encapsulates the communication from the client to the
server. While ServletResponse encapsulates the communication from the
Servlet back to the client. All the passage of data between the client and server
happens by means of these request and response objects.
---------------------------------------Session Based Interview Questions
1. What is a Session?
A Session refers to all the request that a single client makes to a server. A
session is specific to the user and for each user a new session is created to
track all the requests from that particular user. Sessions are not shared among
users and each user of the system will have a seperate session and a unique
session Id. In most cases, the default value of time-out* is 20 minutes and it can
be changed as per the website requirements.
*Time-Out - The Amount of time after which a session becomes
invalidated/destroyed if the session has been inactive.
2. What is Session ID?
A session ID is an unique identification string usually a long, random and alphanumeric string, that is transmitted between the client and the server. Session IDs
are usually stored in the cookies, URLs (in case url rewriting) and hidden fields
of Web pages.
3. What is Session Tracking?
HTTP is stateless protocol and it does not maintain the client state. But there
exist a mechanism called "Session Tracking" which helps the servers to
maintain the state to track the series of requests from the same user across
some period of time.
4. What are different types of Session Tracking?
Mechanism for Session Tracking are:
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions
5. What is HTTPSession Class?
HttpSession Class provides a way to identify a user across across multiple
request. The servlet container uses HttpSession interface to create a session
between an HTTP client and an HTTP server. The session lives only for a
specified time period, across more than one connection or page request from
the user.
6. Why do we need Session Tracking in a Servlet based Web Application?
In HttpServlet you can use Session Tracking to track the user state. Simply put,
it is used to store information like users login credentials, his choices in previous
pages (like in a shopping cart website) etc
7. What are the advantage of Cookies over URL rewriting?
Sessions tracking using Cookies are more secure and fast. It keeps the website
URL clean and concise instead of a long string appended to the URL everytime
you click on any link in the website. Also, when we use url rewriting, it requites
large data transfer from and to the server. So, it may lead to significant network
traffic and access to the websites may be become slow.
8. What is session hijacking?
If you application is not very secure then it is possible to get the access of
system after acquiring or generating the authentication information. Session
hijacking refers to the act of taking control of a user session after successfully
obtaining or generating an authentication session ID. It involves an attacker
using captured, brute forced or reverse-engineered session IDs to get a control
of a legitimate user's Web application session while that session is still in
progress.
9. What is Session Migration?
Session Migration is a mechanism of moving the session from one server to
another in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.
10. How to track a user session in Servlets?
The interface HttpSession can be used to track the session in the Servlet.
Following code can be used to create session object in the Servlet:
HttpSession session = req.getSession(true);
Using this session object, the servlet can gain access to the details of the
session.
source file. They are comments that are enclosed within the < ! - - Your
Comments Here - - >
9. What is expression in JSP?
Expression tag is used to insert Java values directly into the output.
Syntax for the Expression tag is: < %= expression % >
An expression tag contains a scripting language expression that is evaluated,
converted to a String, and inserted where the expression appears in the JSP file.
The most commonly used language is regular Java.
10. What types of comments are available in the JSP?
There are two types of comments that are allowed in the JSP. They are hidden
and output comments.
A hidden comment does not appear in the generated HTML output, while output
comments appear in the generated output.
Example of hidden comment:
< % - - This is a hidden comment - - % >
Example of output comment:
< ! - - This is an output comment - - >
11. What is a JSP Scriptlet?
JSP Scriptlets is a term used to refer to pieces of Java code that can be
embedded in a JSP PAge. Scriptlets begins with <% tag and ends with %> tag.
Java code written inside scriptlet executes every time the JSP is invoked.
12. What are the life-cycle methods of JSP?
Life-cycle methods of the JSP are:
a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is
called before any other method, and is called only once for a servlet instance.
b)_jspService(): The container calls the _jspservice() for each request and it
passes the request and the response objects. _jspService() method cann't be
overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.
13. What are JSP Custom tags?
JSP Custom tags are user defined JSP language elements. JSP custom tags
are user defined tags that can encapsulate common functionality. For example
you can write your own tag to access the database and performing database
operations. You can also write custom tags to encapsulate both simple and
complex behaviors in an easy to use syntax. The use of custom tags greatly
enhances the functionality and simplifies the readability of JSP pages.
14. What is the role of JSP in MVC Model?
JSP is mostly used to develop the user interface, It plays are role of View in the
MVC Model.
15. What do you understand by context initialization parameters?
The context-param element contains the declaration of a web application's
servlet context initialization parameters.
< context - param >
< param - name > name < / param - name > < param - value > value < / param value >
< / context-param >
The Context Parameters page lets you manage parameters that are accessed
through the ServletContext.getInitParameterNames and
ServletContext.getInitParameter methods.
Model: Components like business logic /business processes and data are the
part of model.
View: HTML, JSP are the view components.
Controller: Action Servlet of Struts is part of Controller components which works
as front controller to handle all the requests.
5.What are the core classes of the Struts Framework?
Struts is a set of cooperating classes, servlets, and JSP tags that make up a
reusable MVC 2 design. JavaBeans components for managing application state
and behavior.
Event-driven development (via listeners as in traditional GUI development).
Pages that represent MVC-style views; pages reference view roots via the JSF
component tree.
6.What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications.
It is the main Controller component that handles client requests and determines
which Action will process each received request. It serves as an Action factory
creating specific Action classes based on users request.
7.What is role of ActionServlet?
ActionServlet performs the role of Controller:
Process user requests
Determine what the user is trying to achieve according to the request
Pull data from the model (if necessary) to be given to the appropriate view,
Select the proper view to respond to the user
Delegates most of this grunt work to Action classes
Is responsible for initialization and clean-up of resources
8.What is the ActionForm?
ActionForm is javabean which represents the form inputs containing the request
parameters from the View referencing the Action bean.
View Helper
Synchronizer Token
16.Can we have more than one struts config.xml file for a single Struts
application?
Yes, we can have more than one struts-config.xml for a single Struts application.
They can be configured as follows:
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml,
/WEB-INF/struts-admin.xml,
/WEB-INF/struts-config-forms.xml
</param-value>
</init-param>
.....
<servlet>
17.What is the directory structure of Struts application?
The directory structure of Struts application
18.What is the difference between session scope and request scope when
saving formbean ?
when the scope is request,the values of formbean would be available for the
current request.
when the scope is session,the values of formbean would be available
throughout the session.
19.What are the important tags of struts-config.xml ?
The five important sections are:
21.What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using
this class, you can have a method for each logical action compared than a
single execute method. The DispatchAction dispatches to one of the logical
actions represented by the methods. It picks a method to invoke based on an
incoming request parameter. The value of the incoming parameter is the name
of the method that the DispatchAction will invoke.
22.How to use DispatchAction?
To use the DispatchAction, follow these steps
Create a class that extends DispatchAction (instead of Action)
In a new class, add a method for every function you need to perform on the
service The method has the same signature as the execute() method of an
Action class.
Do not override execute() method Because DispatchAction class itself
provides execute() method.
Add an entry to struts-config.xml
DispatchAction Example
23.What is the use of ForwardAction?
The ForwardAction class is useful when youre trying to integrate Struts into an
existing application that uses Servlets to perform
business logic functions. You can use this class to take advantage of the Struts
controller and its functionality, without having to rewrite the existing Servlets.
Use ForwardAction to forward a request to another resource in your application,
such as a Servlet that already does business logic processing or even another
JSP page. By using this predefined action, you dont have to write your own
Action class. You just have to set up the struts-config file properly to use
ForwardAction.
24.What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an
application that uses Servlets. Use the IncludeAction class to include another
resource in the response to the request being processed.
<forward>takes precendence.
31.What is DynaActionForm?
A specialized subclass of ActionForm that allows the creation of form beans with
dynamic sets of properties (configured in configuration file), without requiring the
developer to create a Java class for each type of form bean.
32.What are the steps need to use DynaActionForm?
Using a DynaActionForm instead of a custom subclass of ActionForm is
relatively straightforward. You need to make changes in two places:
In struts-config.xml: change your <form-bean> to be an
org.apache.struts.action.DynaActionForm instead of some subclass of
ActionForm
33.How to display validation errors on jsp page?
<html:errors/> tag displays all the errors. <html:errors/> iterates over
ActionErrors request attribute.
34.What are the various Struts tag libraries?
The various Struts tag libraries are:
HTML Tags
Bean Tags
Logic Tags
Template Tags
Nested Tags
Tiles Tags
35.What is the use of <logic:iterate>?
<logic:iterate> repeats the nested body content of this tag over a specified
collection.
<table border=1>
<logic:iterate id="customer" name="customers">
<tr>
<td><bean:write name="customer"
property="firstName"/></td>
<td><bean:write name="customer" property="lastName"/></td>
<td><bean:write name="customer" property="address"/></td>
</tr>
</logic:iterate>
</table>
36.What are differences between <bean:message> and <bean:write>
<bean:message>: is used to retrive keyed values from resource bundle. It also
supports the ability to include parameters that can be
substituted for defined placeholders in the retrieved string.
<bean:message key="prompt.customer.firstname"/>
<bean:write>: is used to retrieve and print the value of the bean property.
<bean:write> has no body.
<bean:write name="customer" property="firstName"/>
37.How the exceptions are handled in struts?
Exceptions in Struts are handled in two ways:
Programmatic exception handling :
Explicit try/catch blocks in any code that can throw exception. It works well when
custom value (i.e., of variable) needed
when error occurs.
Declarative exception handling :You can either define <global-exceptions>
handling tags in your struts-config.xml or define the exception handling tags
within <action></action> tag. It works well when custom page needed when
error occurs. This approach applies only to exceptions thrown by Actions.
<global-exceptions>
<exception key="some.key"
type="java.lang.NullPointerException"
path="/WEB-INF/errors/null.jsp"/>
</global-exceptions>
or
<exception key="some.key"
type="package.SomeException"
path="/WEB-INF/somepage.jsp"/>
38.What is difference between ActionForm and DynaActionForm?
An ActionForm represents an HTML form that the user interacts with over one
or more pages. You will provide properties to hold the state of the form with
getters and setters to access them. Whereas, using DynaActionForm there is no
need of providing properties to hold the state. Instead these properties and their
type are declared in the struts-config.xml
The DynaActionForm bloats up the Struts config file with the xml based
definition. This gets annoying as the Struts Config file
grow larger.
The DynaActionForm is not strongly typed as the ActionForm. This means
there is no compile time checking for the form fields. Detecting them at runtime
is painful and makes you go through redeployment.
ActionForm can be cleanly organized in packages as against the flat
organization in the Struts Config file.
ActionForm were designed to act as a Firewall between HTTP and the Action
classes, i.e. isolate and encapsulate the HTTP request parameters from direct
use in Actions. With DynaActionForm, the property access is no different than
using request.getParameter.
DynaActionForm construction at runtime requires a lot of Java Reflection
(Introspection) machinery that can be avoided.
39.How can we make message resources definitions file available to the
Struts framework environment?
We can make message resources definitions file (properties file) available to
Struts framework environment by adding this file to strutsconfig.
xml.
<message-resources
parameter="com.login.struts.ApplicationResources"/>
40.What is the life cycle of ActionForm?
The lifecycle of ActionForm invoked by the RequestProcessor is as follows:
Retrieve or Create Form Bean associated with Action
"Store" FormBean in appropriate scope (request or session)
------------------------------------------------------------------------------------------------------------------------------------
selective about which of its components you use while also providing a
cohesive framework for J2EE application development. The Spring
modules are built on top of the core container, which defines how beans
are created, configured, and managed. Each of the modules (or
components) that comprise the Spring framework can stand on its own or
be implemented jointly with one or more of the others. The functionality of
each component is as follows:
The core container: The core container provides the essential functionality
of the Spring framework. A primary component of the core container is the
BeanFactory, an implementation of the Factory pattern. The BeanFactory
applies the Inversion of Control (IOC) pattern to separate an applications
configuration and dependency specification from the actual application
code.
Spring context: The Spring context is a configuration file that provides
context information to the Spring framework. The Spring context includes
enterprise services such as JNDI, EJB, e-mail, internalization, validation,
and scheduling functionality.
Spring AOP: The Spring AOP module integrates aspect-oriented
programming functionality directly into the Spring framework, through its
configuration management feature. As a result you can easily AOP-enable
any object managed by the Spring framework. The Spring AOP module
provides transaction management services for objects in any Springbased application. With Spring AOP you can incorporate declarative
transaction management into your applications without relying on EJB
components.
Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful
exception hierarchy for managing the exception handling and error
messages thrown by different database vendors. The exception hierarchy
simplifies error handling and greatly reduces the amount of exception
code you need to write, such as opening and closing connections. Spring
DAOs JDBC-oriented exceptions comply to its generic DAO exception
hierarchy.
Spring ORM: The Spring framework plugs into several ORM frameworks to
provide its Object Relational tool, including JDO, Hibernate, and iBatis
SQL Maps. All of these comply to Springs generic transaction and DAO
exception hierarchies.
Spring Web module: The Web context module builds on top of the
application context module, providing contexts for Web-based
applications. As a result, the Spring framework supports integration with
Jakarta Struts. The Web module also eases the tasks of handling multipart requests and binding request parameters to domain objects.
Spring MVC framework: The Model-View-Controller (MVC) framework is a
full-featured MVC implementation for building Web applications. The MVC
framework is highly configurable via strategy interfaces and
accommodates numerous view technologies including JSP, Velocity, Tiles,
iText, and POI.
5. What is AOP? How does it relate with IOC? What are different tools to
utilize AOP?
Aspect-oriented programming, or AOP, is a programming technique that
allows programmers to modularize crosscutting concerns, or behaviour
that cuts across the typical divisions of responsibility, such as logging
and transaction management. The core construct of AOP is the aspect,
which encapsulates behaviours affecting multiple classes into reusable
modules. AOP and IOC are complementary technologies in that both apply
a modular approach to complex problems in enterprise application
development. In a typical object-oriented development approach you
might implement logging functionality by putting logger statements in all
your methods and Java classes. In an AOP approach you would instead
modularize the logging services and apply them declaratively to the
components that required logging. The advantage, of course, is that the
Java class doesn't need to know about the existence of the logging
service or concern itself with any related code. As a result, application
code written using Spring AOP is loosely coupled. The best tool to utilize
AOP to its capability is AspectJ. However AspectJ works at the byte code
level and you need to use AspectJ compiler to get the aop features built
into your compiled code. Nevertheless AOP functionality is fully integrated
into the Spring context for transaction management, logging, and various
other features. In general any AOP framework control aspects in three
possible ways:
Joinpoints: Points in a program's execution. For example, joinpoints could
define calls to specific methods in a class
Pointcuts: Program constructs to designate joinpoints and collect specific
context at those points
Advices: Code that runs upon meeting certain conditions. For example, an
advice could log a message before executing a joinpoint
6. What are the advantages of spring framework?
Spring has layered architecture. Use what you need and leave you don't
need.
Spring Enables POJO Programming. There is no behind the scene magic
here. POJO programming enables continuous integration and testability.
Dependency Injection and Inversion of Control Simplifies JDBC
Open source and no vendor lock-in.
7. Can you name a tool which could provide the initial ant files and
directory structure for a new spring project?
Appfuse or equinox.
8. Explain BeanFactory in spring.
Bean factory is an implementation of the factory design pattern and its
function is to create and dispense beans. As the bean factory knows about
many objects within an application, it is able to create association between
collaborating objects as they are instantiated. This removes the burden of
configuration from the bean and the client. There are several
implementation of BeanFactory. The most useful one is
"org.springframework.beans.factory.xml.XmlBeanFactory" It loads its
try {
tx.rollback();
} catch (HibernateException e1) {
throw new DAOException(e1.toString()); }
} throw new DAOException(e.toString());
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) { }
}
}
20. What is the difference between hibernate get and load methods?
The load() method is older; get() was added to Hibernates API due to user
request. The difference is trivial:
The following Hibernate code snippet retrieves a User object from the
database:
User user = (User) session.get(User.class, userID);
The get() method is special because the identifier uniquely identifies a
single instance of a class. Hence its common for applications to use the
identifier as a convenient handle to a persistent object. Retrieval by
identifier can use the cache when retrieving an object, avoiding a database
hit if the object is already cached.
Hibernate also provides a load() method:
User user = (User) session.load(User.class, userID);
If load() cant find the object in the cache or database, an exception is
thrown. The load() method never returns null. The get() method returns
null if the object cant be found. The load() method may return a proxy
instead of a real persistent instance. A proxy is a placeholder instance of a
runtime-generated subclass (through cglib or Javassist) of a mapped
persistent class, it can initialize itself if any method is called that is not the
mapped database identifier getter-method. On the other hand, get() never
22. What is lazy loading and how do you achieve that in hibernate?
Lazy setting decides whether to load child objects while loading the Parent
Object. You need to specify parent class.Lazy = true in hibernate mapping
file. By default the lazy loading of the child objects is true. This make sure
that the child objects are not loaded unless they are explicitly invoked in
the application by calling getChild() method on parent. In this case
hibernate issues a fresh database call to load the child when getChild() is
actually called on the Parent object. But in some cases you do need to
load the child objects when parent is loaded. Just make the lazy=false and
hibernate will load the child when parent is loaded from the database.
Examples: Address child of User class can be made lazy if it is not
required frequently. But you may need to load the Author object for Book
parent whenever you deal with the book for online bookshop.
Hibernate does not support lazy initialization for detached objects. Access
to a lazy association outside of the context of an open Hibernate session
will result in an exception.
23. What are the different fetching strategies in Hibernate?
Hibernate3 defines the following fetching strategies:
Join fetching - Hibernate retrieves the associated instance or collection in
the same SELECT, using an OUTER JOIN.
Select fetching - a second SELECT is used to retrieve the associated entity
or collection. Unless you explicitly disable lazy fetching by specifying
lazy="false", this second select will only be executed when you actually
access the association.
Subselect fetching - a second SELECT is used to retrieve the associated
collections for all entities retrieved in a previous query or fetch. Unless
you explicitly disable lazy fetching by specifying lazy="false", this second
select will only be executed when you actually access the association.
Batch fetching - an optimization strategy for select fetching - Hibernate
To use the query cache you must first enable it by setting the property
hibernate.cache.use_query_cache to true in hibernate.properties.
27. What is the difference between sorted and ordered collection in
hibernate?
A sorted collection is sorted in-memory using java comparator, while order
collection is ordered at the database level using order by clause.
28. What are the types of inheritance models and describe how they work
like vertical inheritance and horizontal?
There are three types of inheritance mapping in hibernate:
Example: Let us take the simple example of 3 java classes. Class Manager
and Worker are inherited from Employee Abstract class.
1. Table per concrete class with unions: In this case there will be 2 tables.
Tables: Manager, Worker [all common attributes will be duplicated]
2. Table per class hierarchy: Single Table can be mapped to a class
hierarchy. There will be only one table in database called 'Employee' that
will represent all the attributes required for all 3 classes. But it needs some
discriminating column to differentiate between Manager and worker;
3. Table per subclass: In this case there will be 3 tables represent
Employee, Manager and Worker
-----------------------------------------------------------------------------------------------------------------------------------------
Ex:
for(;;) ;
17. 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
18. What is the range of the short type?
The range of the short data type is -(2^15) to 2^15 - 1.
19. What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.
20. What is the difference between the Boolean & operator and the &&
operator?
&& is a short-circuit AND operator - i.e., The second condition will be
evaluated only if the first condition is true. If the first condition is true, the
system does not waste its time executing the second condition because,
the overall output is going to be false because of the one failed condition.
& operator is a regular AND operator - i.e., Both conditions will be
evaluated always.
21. What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western
calendars.
22. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime
system.
23. What is the argument type of a program's main() method?
file, then the file can take on a name that is different than its classes and
interfaces. Source code files use the .java extension.
30. What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.
31. Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.
32. What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs. It is
the predecessor to the current day HashMap and Hashtable.
33. What is the % operator?
It is referred to as the modulo or remainder operator. It returns the
remainder of dividing the first operand by the second operand.
34. What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific
properties, such as ascent and descent, of a Font object.
35. How is rounding performed under integer division?
The fractional part of the result is truncated. This is known as rounding
toward zero.
36. What is the difference between the Reader/Writer class hierarchy and
the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the
InputStream/OutputStream class hierarchy is byte-oriented.
37. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar. You
can use it to manipulate dates & times.
The File class is used to create objects that provide access to the files and
directories of a local file system.
46. Which Math method is used to calculate the absolute value of a
number?
The abs() method is used to calculate absolute values.
47. 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
48. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different
return types.
49. What is the return type of a program's main() method?
A program's main() method has a void return type. i.e., the main method
does not return anything.
50. 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.
Basically a Bean is a java class but it has getter and setter method and it
does not have any logic in it, it is used for holding data.
On the other hand the Java class can have what a java bean has and also
has some logic inside it
70. What are null or Marker interfaces in Java ?
The null interfaces or marker interfaces or Tagged Interfaces, do not have
method declarations in them. They are empty interfaces, this is to convey
the compiler that they have to be treated differently
71. Does java Support multiple inheritance ?
Java does not support multiple inheritance directly like C++, because then
it is prone to ambiguity, example if a class extends 2 other classes and
these 2 parent classes have same method names then there is ambiguity.
Hence in Partial Java Multiple inheritance is supported using Interfaces
72. What are virtual function ?
In OOP when a derived class inherits from a base class, an object of the
derived class may be referred to (or cast) as either being the base class
type or the derived class type. If there are base class functions overridden
by the derived class, a problem then arises when a derived object has
been cast as the base class type. When a derived object is referred to as
being of the base's type, the desired function call behavior is ambiguous.
The distinction between virtual and not virtual is provided to solve this
issue. If the function in question is designated "virtual" then the derived
class's function would be called (if it exists). If it is not virtual, the base
class's function would be called.
73. Does java support virtual functions ?
No java does not support virtual functions direclty like in C++, but it
supports using Abstract class and interfaces
74. What is JVM ?
When we install a java package. It contains 2 things
class variable is a static variable and does not belong to instance of class
but rather shared across all the instances of the Class.
member variable belongs to a particular instance of class and can be
called from any method of the class
automatic or local variable is created on entry to a method and is alive
only when the method is executed
82. When are static and non static variables of the class initialized ?
The static variables are initialized when the class is loaded
Non static variables are initialized just before the constructor is called
83. How is an argument passed in java, is it by copy or by reference?
If the variable is primitive datatype then it is passed by copy.
If the variable is an object then it is passed by reference
84. How does bitwise (~) operator work ?
It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g
11110000 gets coverted to 00001111
85. Can shift operators be applied to float types ?
No, shift operators can be applied only to integer or long types (whole
numbers)
86. What happens to the bits that fall off after shifting ?
They are discarded (ignored)
87. What are the rules for overriding ?
The rules for Overriding are: Private method can be overridden by private,
protected or public methods Friendly method can be overridden by
protected or public methods Protected method can be overridden by
protected or public methods Public method can be overridden by public
method
---------------------------------------------------------------------------------------------------------------------------------
8- What is Aggregation?
It is a specialized form of Association where all object have their own lifecycle
but there is ownership. This represents whole-part or a-part-of relationship.
This is represented by a hollow diamond followed by a line.
The result is a String object. For that matter, if you add anything to a String, you
will end up with a String.
7. What will be the result if you compare StringBuffer with String if both
have same values?
It will return false as you cannot compare String with StringBuffer directly. If you
really want to compare the contents of the String & the StringBuffer you would
have to invoke the equals method with the String and the toString() output of the
StringBuffer.
method?
No it cannot throw, except for the subclasses of the exceptions thrown by the
parent class's method.
29. Is it legal for the extending class which overrides a method which
throws an exception, not to throw in the overridden class?
Yes, it is perfectly legal.
=============================================================
====
EnumMap
18.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map
interface. In a TreeMap the data will be sorted in ascending order of keys
according to the natural order for the key's class, or by the comparator provided
at creation time. TreeMap is based on the Red-Black tree data structure.
19.How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the
best alternative. If, however, you need to traverse the keys in a sorted order,
then TreeMap is your better alternative. Depending upon the size of your
collection, it may be faster to add elements to a HashMap, then convert the map
to a TreeMap for sorted key traversal.
20. Can I store multiple keys or values that are null in a HashMap?
You can store only one key that has a value null. But, as long as your keys are
unique, you can store as many nulls as you want in an HashMap.
=============================================================
=
interface Comparable
where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the
compareTo() method that has the return type as an integer. The signature of the
compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative.
If object1 > object2: The value of i returned will be positive.
If object1 = object2: The value of i returned will be zero.
25.What are the differences between the Comparable and Comparator
interfaces?
The Comparable uses the compareTo() method while the Comparator uses the
compare() method
You need to modify the class whose instance is going to be sorted and add code
corresponding to the Comparable implementation. Whereas, for the Comparator,
you can have a separate class that has the sort logic/code.
In case of Comparable, Only one sort sequence can be created while
Comparator can have multiple sort sequences.
=============================================================
========
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 many other factors. You can refer to articles on
Operating Systems and processor scheduling for more details on the same.
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. 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.
18. 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.
19. What invokes a thread's run() method?
After a thread is started, via its start() method, the JVM invokes the thread's
run() method when the thread needs to be executed.
20. 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.
21. 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.
22. What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
23. What is an object's lock and which object's have locks?
No it just makes the thread eligible to run. The thread still has to wait for the
CPU time along with the other threads, then at some time in future, the
scheduler will permit the thread to run
36. When the thread gets to execute, what does it execute
It executes all the code that is placed inside the run() method.
37. How many methods are declared in the interface runnable
The runnable method declares only one method : public void run();
38. Which way would you prefer to implement threading - by extending
Thread class or implementing Runnable interface
The preferred way will be to use Interface Runnable, because by subclassing
the Thread class you have single inheritance i.e you wont be able to extend any
other class in Java.
39. What happens when the run() method returns
When the run() method returns, the thread has finished its task and is
considered dead. You can't restart a dead thread.
40. What are the different states of the thread
The different states of Threads are:
New: Just created Thraed
Running: The state that all threads want to be
Various waiting states : Waiting, Sleeping, Suspended and Blocked
Ready : Waiting only for the CPU
Dead : Story Over
41. What is Thread priority
Every thread has a priority, the higher priority thread gets preference over the
lower priority thread by the thread scheduler
42. What is the range of priority integer that can be set for Threads?
It is from 1 to 10. 10 beings the highest priority and 1 being the lowest
information?
Have the class implement Cloneable interface and call its clone() method. If the
class doesnt implement the interface and still the clone() is called, you will get
an exception.
7. Describe the wrapper classes in Java ?
Wrapper class is wrapper around a primitive data type. An instance of a wrapper
class contains, or wraps, a primitive value of the corresponding type and creates
an Object.
Ex: java.lang.Boolean is the Wrapper for boolean, java.lang.Long is the wrapper
for long etc.
8. Which class is extended by all other classes?
The Object class is extended by all other classes.
9. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses. But, a class
can invoke the constructors of its super class by calling super();
10. 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 coded by the programmer who created the class.
11. 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.
12. How are this and super used?
this is used to refer to the current object instance. super is used to refer to the
variables and methods of the superclass of the current object instance.
13. When a new object of derived Class is created, whose constructor will
be called first, childs or parents
Even when the new object of child class is created, first the Base class
constructor gets executed and then the child classes constructor. This is
because, super() is the first line of code in any constructor and so, classes get
created top to bottom and hence, the constructor of the Object class gets
created first and then all the other classes in the hierarchy.
14. Can constructors be overloaded
Yes.
15. If you use super() or this() in a constructor where should it appear in
the constructor
It should always be the first statement in the constructor and a point to note is,
you cannot have both super() and this() in the same constructor for a simple
reason - you cannot have two first lines in a method.
16. What is the ultimate ancestor of all java classes
Object class is the ancestor of all the java classes
17. What are important methods of Object class
wait(), notify(), notifyAll(), equals(), toString().
-======================================================
2. How can you minimize the need of garbage collection and make the
memory use more effective?
Use object pooling and weak object references. We need to ensure that all
objects that are no longer required in the program are cleared off using finalize()
blocks in your code.
3. Explain garbage collection ?
Garbage collection is an important part of Java's security strategy. Garbage
collection is also called automatic memory management as JVM automatically
removes the unused variables/objects from the memory. The name "garbage
collection" implies that objects that are no longer needed or used by the
program are "garbage" and can be thrown away to create free space for the
programs that are currently running. A more accurate and up-to-date term might
be "memory recycling." When an object is no longer referenced by the program,
the heap space it occupies must be recycled so that the space is available for
subsequent new objects. The garbage collector must determine which objects
are no longer referenced by the program and make available the heap space
occupied by such unreferenced objects. This way, unused memory space is
reclaimed and made available for the program to use.
4. 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 as well. Hence, the Garbage Collection
mechanism is a "On Best Effort Basis" system where the GC tries to clean up
memory as much as possible to ensure that the system does not run out of
memory but it does not guarantee the same.
5. 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.
Inheritance
Encapsulation
(i.e. easily remembered as A-PIE).
2.What is Abstraction?
Abstraction refers to the act of representing essential features without including the
background details or explanations.
3.What is Encapsulation?
Encapsulation is a technique used for hiding the properties and behaviors of an object
and allowing outside access only as appropriate. It prevents other objects from
directly altering or accessing the properties or methods of the encapsulated object.
4.What is the difference between abstraction and encapsulation?
Abstraction focuses on the outside view of an object (i.e. the
interface) Encapsulation (information hiding) prevents clients from seeing its
inside view, where the behavior of the abstraction is implemented.
Abstraction solves the problem in the design side while Encapsulation is the
Implementation.
5.What is Inheritance?
Inheritance is the process by which objects of one class acquire the properties
of objects of another class.
A class that is inherited is called a superclass.
To use polymorphism
6.What is Polymorphism?
Polymorphism is briefly described as "one interface, many implementations."
Polymorphism is a characteristic of being able to assign a different meaning or usage
to something in different contexts - specifically, to allow an entity such as a variable,
a function, or an object to have more than one form.
7.How does Java implement polymorphism?
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the
same name.
In some cases, multiple methods have the same name, but different formal
argument lists (overloaded methods).
In other cases, multiple methods have the same name, same return type, and
same formal argument list (overridden methods).
8.Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the
other is run time polymorphism. Compile time polymorphism is method
overloading. Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in
three distinct forms in Java:
Method overloading
Method overriding through inheritance
13.What are the differences between method overloading and method overriding?
Overloaded Method
Overridden Method
Arguments
Must change
Return type
Can change
Exceptions
Can change
Access
Can change
Invocation
// From subclass
super.overriddenMethod();
17.What is super?
super is a keyword which is used to access the method or member variables from the
superclass. If a method hides one of the member variables in its superclass, the
method can refer to the hidden variable through the use of the super keyword. In the
same way, if a method overrides one of the methods in its superclass, the method can
invoke the overridden method through the use of the super keyword.
Note:
You can only go back one level.
In the constructor, if you use super(), it must be the very first code, and you
cannot access anythis.xxx variables or methods to compute its parameters.
18.How do you prevent a method from being overridden?
To prevent a specific method from being overridden in a subclass, use the final
modifier on the method declaration, which means "this is the final implementation of
this method", the end of its inheritance hierarchy.
Method statements
Interfaces
An abstract class can have non-abstract methods. All methods of an Interface are abstract.
An abstract class can have instance variables.
28.When should I use abstract classes and when should I use interfaces?
Use Interfaces when
You see that something in your design will change frequently.
If various implementations only share method signatures then it is better to use
Interfaces.
you need some classes to use some methods which you don't want to be
included in the class, then you go for the interface, which makes it easy to just
implement and make use of the methods defined in the interface.
29.When you declare a method as abstract, can other nonabstract methods access
it?
Yes, other nonabstract methods can access a method that you declare as abstract.
30.Can there be an abstract class with no abstract methods in it?
Yes, there can be an abstract class without abstract methods.
31.What is Constructor?
A constructor is a special method whose task is to initialize the object of its
class.
It is special because its name is the same as the class name.
They do not have return types, not evenvoid and therefore they cannot return
values.
They cannot be inherited, though a derived class can call the base class
constructor.
Methods
Purpose
Modifiers
Return Type
Name
this
super
Inheritance
Instance Methods
Class methods can only operate on class members Instance methods of the class can also not be
and not on instance members as class methods
called from within a class method unless they are
are unaware of instance members.
being called on an instance of that class.
Class methods are methods which are declared as
static. The method can be called without
Instance methods are not declared as static.
creating an instance of the class.
37.How are this() and super() used with constructors?
Constructors use this to refer to another constructor in the same class with a
different parameter list.
Default(no specifier)- If you do not set access to specific level, then such a
class, method, or field will be accessible from inside the same package to
which the class, method, or field belongs, but not from outside this package.
Private- private methods and fields can only be accessed within the same class
to which the methods and fields belong. private methods and fields are not
visible within subclasses and are not inherited by subclasses.
Situation
public
protected
default
Accessible to class
from same package?
yes
yes
yes
no
Accessible to class
from different package?
yes
no
no
privat
static type
varIdentifier;
where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically
initialized with a default value. The default value depends on the data type of the
variables.
44.What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific
instances of a class. Non-static variables take on unique values with each object
instance.
45.What are static methods?
Methods declared with the keyword static as modifier are called static methods or
class methods. They are so called because they affect a class as a whole, not a
particular instance of the class. Static methods are always invoked without reference
to a particular instance of a class.
Note:The use of a static method suffers from the following restrictions:
A static method can only call other static methods.
A static method must only access static data.
46.What is an Iterator ?
Iterator
Iterator has a remove() method
Enumeration acts as Read-only interface, because Can be abstract, final, native, static,
it has the methods only to traverse and fetch the orsynchronized
objects
Note: So Enumeration is used whenever we want to make Collection objects as Readonly.
50.How is ListIterator?
ListIterator is just like Iterator, except it allows us to access the collection in either
the forward or backward direction and lets us modify an element
51.What is the List interface?
The List interface provides support for ordered collections of objects.
Lists may contain duplicate elements.
52.What are the main implementations of the List interface ?
Vector
a[] = arrayList.toArray();
ArrayList internally uses and array to store the elements, when that array gets
filled by inserting elements a new array of roughly 1.5 times the size of the
original array is created and all the data of old array is copied to new array.
During deletion, all elements present in the array after the deleted elements
have to be moved one step back to fill the space created by deletion. In linked
list data is stored in nodes that have reference to the previous node and the
next node so adding element is simple as creating the node an updating the
next pointer on the last node and the previous pointer on the new
node. Deletion in linked list is fast because it involves only updating the next
pointer in the node before the deleted node and updating the previous pointer
in the node after the deleted node.
The Set interface provides methods for accessing the elements of a finite
mathematical set
Sets do not allow duplicate elements
Two Set objects are equal if they contain the same elements
LinkedHashSet
EnumSet
61.What is a HashSet ?
Use this class when you want a collection with no duplicates and you dont care
about order when you iterate through it.
62.What is a TreeSet ?
TreeSet is a Set implementation that keeps the elements in sorted order. The
elements are sorted according to the natural order of elements or by the comparator
provided at creation time.
63.What is an EnumSet ?
An EnumSet is a specialized set for use with enum types, all of the elements in the
EnumSet type that is specified, explicitly or implicitly, when the set is created.
64.Difference between HashSet and TreeSet ?
HashSet
TreeSet
65.What is a Map ?
A map is an object that stores associations between keys and values (key/value
pairs).
Given a key, you can find its value. Both keys and values are objects.
Some maps can accept a null key and null values, others cannot.
TreeMap
EnumMap
67.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map
interface. In a TreeMap the data will be sorted in ascending order of keys according to
the natural order for the key's class, or by the comparator provided at creation time.
TreeMap is based on the Red-Black tree data structure.
68.How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best
alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap
is your better alternative. Depending upon the size of your collection, it may be
faster to add elements to a HashMap, then convert the map to a TreeMap for sorted
key traversal.
69.Difference between HashMap and Hashtable ?
HashMap
Hashtable
HashMap is unsynchronized.
Hashtable is synchronized.
Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple
keys to be NULL. Nevertheless, it can have multiple NULL values.
70.How does a Hashtable internally maintain the key-value pairs?
TreeMap actually implements the SortedMap interface which extends the Map
interface. In a TreeMap the data will be sorted in ascending order of keys according to
the natural order for the key's class, or by the comparator provided at creation time.
TreeMap is based on the Red-Black tree data structure.
71.What Are the different Collection
Views That Maps Provide?
Maps Provide Three Collection Views.
Key Set - allow a map's contents to be viewed as a set of keys.
Values Collection - allow a map's contents to be viewed as a set of values.
interface Comparable<T>
where T is the name of the type parameter.
int i = object1.compareTo(object2)
77.What are the differences between the Comparable and Comparator interfaces ?
Comparable
Comparato
int objectOne.compareTo(objectTwo).
It is necessary to modify the class whose instance A separate class can be created in order to sort
is going to be sorted.
the instances.
Only one sort sequence can be created.
1.What is an exception?
An Error indicates that a non-recoverable condition has occurred that should not be
caught. Error, a subclass of Throwable, is intended for drastic problems, such as
OutOfMemoryError, which would be reported by the JVM itself.
3.Which is superclass of Exception?
There are two types of exceptions in Java, unchecked exceptions and checked
exceptions.
A unchecked exception classes which are the error classes (Error and its subclasses)
are exempted from compile-time checking because they can occur at many points in
the program and recovery from them is difficult or impossible. A program declaring
such exceptions would be pointlessly.
7.Why Runtime Exceptions are Not Checked?
The runtime exception classes (RuntimeException and its subclasses) are exempted
from compile-time checking because, in the judgment of the designers of the Java
programming language, having to declare such exceptions would not aid significantly
in establishing the correctness of programs. Many of the operations and constructs of
the Java programming language can result in runtime exceptions. The information
available to a compiler, and the level of analysis the compiler performs, are usually
not sufficient to establish that such run-time exceptions cannot occur, even though
this may be obvious to the programmer. Requiring such exception classes to be
declared would simply be an irritation to programmers.
8.Explain the significance of try-catch blocks?
Whenever the exception occurs in Java, we need a way to tell the JVM what code to
execute. To do this, we use the try and catch keywords. The try is used to define a
block of code in which exceptions may occur. One or more catch clauses match a
specific exception to a block of code that handles it.
The finally block encloses code that is always executed at some point after the try
block, whether an exception was thrown or not. This is right place to close files,
release your network sockets, connections, and perform any other cleanup your code
requires.
Note: If the try block executes with no exceptions, the finally block is executed
immediately after the try block completes. It there was an exception thrown, the
finally block executes immediately after the proper catch block completes
10.What if there is a break or return statement in try block followed by finally block?
If there is a return statement in the try block, the finally block executes right after
the return statement encountered, and before the return executes.
11.Can we have the try block without catch block?
Yes, we can have the try block without catch block, but finally block should follow the
try block.
Note: It is not valid to use a try clause without either a catch clause or a finally
clause.
12.What is the difference throw and throws?
then any other method that calls it must either have a try-catch clause to handle that
exception or must be declared to throw that exception (or its superclass) itself.
A method that does not handle an exception it throws has to announce this:
}
throw: Used to trigger an exception. The exception will be caught by the nearest trycatch clause that can catch that type of exception. The flow of execution stops
immediately after the throw statement; any subsequent statements are not executed.
Wrapping the desired code in a try block followed by a catch block to catch the
exceptions.
List the desired exceptions in the throws clause of the method and let the caller of the
method handle those exceptions.
Java Database Connectivity (JDBC) is a standard Java API to interact with relational
databases form Java. JDBC has set of classes and interfaces which can use from Java
application and talk to database without learning RDBMS details and using Database
Specific JDBC Drivers.
2.What are the new features added to JDBC 4.0?
JDBC makes the interaction with RDBMS simple and intuitive. When a Java application
needs to access database :
Load the RDBMS specific JDBC driver because this driver actually communicates with
the database (Incase of JDBC 4.0 this is automatically loaded).
Open the connection to database which is then used to send SQL statements and get
results back.
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases. The JDBC driver manager
ensures that the correct driver is used to access each data source. The driver manager
is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases. The location of the driver manager with respect to the
JDBC drivers and the Java application is shown in Figure 1.
Driver: The database communications link, handling all communication with the
database. Normally, once the driver is loaded, the developer need not call it explicitly.
ResultSet: The ResultSet represents set of rows retrieved due to query execution.
Driver layer consists of DriverManager class and the available JDBC drivers.
The application begins with requesting the DriverManager for the connection.
An appropriate driver is choosen and is used for establishing the connection. This
connection is given to the application which falls under the application layer.
The application uses this connection to create Statement kind of objects, through
which SQL commands are sent to backend and obtain the results.
Provided the JAR file containing the driver is properly configured, just place the JAR
file in the classpath. Java developers NO longer need to explicitly load JDBC drivers
using code like Class.forName() to register a JDBC driver.The DriverManager class
takes care of this by automatically locating a suitable driver when
the DriverManager.getConnection() method is called. This feature is backwardcompatible, so no changes are needed to the existing JDBC code.
8.What is JDBC Driver interface?
Statement acts like a vehicle through which SQL commands can be sent. Through the
connection object we create statement kind of objects.
Through the connection object we
create statement kind of objects.
Statement
stmt =
conn.createStatement();
This method returns object which
implements statement interface.
11.What is PreparedStatement?
PreparedStatement pstmt =
conn.prepareStatement("UPDATE EMPLOYEES SET SALARY = ?
WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00);
pstmt.setInt(2, 110592);
Here: conn is an instance of the Connection class and "?" represents
parameters.These parameters must be specified before execution.
Prepare
A PreparedStatement is a precompi
the PreparedStatement is executed
PreparedStatement SQL statement
Statement has to verify its metadata against the database every time.
Callable statements are used from JDBC application to invoke stored procedures and
functions.
14.How to call a stored procedure from JDBC ?
PL/SQL stored procedures are called from within JDBC programs by means of the
prepareCall() method of the Connection object created. A call to this method takes
variable bind parameters as input parameters as well as output variables and creates
an object instance of the CallableStatement class.
The following line of code illustrates this:
CallableStatement stproc_stmt =
conn.prepareCall("{call procname(?,?,?)}");
Here conn is an instance of the Connection class.
15.What are types of JDBC drivers?
JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC
calls into vendor specific protocol calls and it directly interacts with the database.
17.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.
Note: Preferred by 9 out of 10 Java developers: Type IV. Click here to learn more
about JDBC drivers.
19.What are the standard isolation levels defined by JDBC?
TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE
ResultSet rs
Spring Questions
MyFaces Examples
JSF Integration with Spring
Framework
webMethods Interview Questions
stmt.executeQuery(sqlQuery);
21.What are the types of resultsets?
TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows within it
TYPE_SCROLL_SENSITIVE
22.What is rowset?
A RowSet is an object that encapsulates a set of rows from either Java Database
Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet.
RowSets support component-based development models like JavaBeans, with a
standard set of properties and an event notification mechanism.
24.What are the different types of
RowSet ?
Connected - A connected RowSet object connects to the database once and remains
connected until the application terminates.
Disconnected - A disconnected RowSet object connects to the database, executes a
query to retrieve the data from the database and then closes the connection. A
program may change the data in a disconnected RowSet while it is disconnected.
The BatchUpdates feature allows us to group SQL statements together and send to
database server in one single trip.
26.What is a DataSource?
Data Source may point to RDBMS, file System , any DBMS etc..
28.What is connection pooling? what is the main advantage of using connection pooling?