Advanced Java Interview Questions -12

Advanced Java Interview Questions -12
1.What’s the use of JAVAP tool ?

javap disassembles compiled Java files and spits out representation of the Java program. This is a useful option when the original source code is not available.

2.what’s the main difference between ArrayList / HashMap and Vector / Hashtable?

Vector / HashTable are synchronized which means they are thread safe. Cost of thread safe is performance degradation. So if you are sure that you are not dealing with huge number of threads then you should use ArrayList / HashMap.But yes you can still
synchronize List and Map’s using Collections provided methods :-
List OurList = Collections.synchronizedList (OurList);
Map OurMap = Collections.synchronizedMap (OurMap);

3.What are applets ?

Applets are small applications that are accessed from web server automatically installed, and run from the browser. Once an applet arrives on the client it has limited access to resources thus ensuring security for the end user. An applet is controlled by the software that runs it. Usually, the underlying software is a browser, but it can also be applet viewer. If you run the applet source code from eclipse it runs inside an applet viewer. All applets should inherit from applet class.
Below are sequences of events which occur in applet:-
The init Method: The init method is called when the applet is first loaded. Init method can be used to initialize color, fonts or any type of one type operation needed for the applet.
The start Method: The start method is called when user visits a browser with an applet on it. In start method applet spawns a thread in which it runs the paint method.
paint() is called every time when applet has to re-display everything. paint() event can occur due to various reasons some of the reasons are :-.

4.what is a StringBuffer class and how does it differs from String class?

StringBuffer is a peer class of String that provides almost all functionality of strings. String represents fixed-length, immutable character sequences. Comparatively StringBuffer represents mutable, growable and writeable character sequences. But StringBuffer does not create new instances as string so it’s more efficient when it comes to intensive concatenation operation.

5.In which package is the applet class located?

Applet classes are located in ” java.applet “package.

6.How can you copy one array in to a different array?

System.arraycopy(myOldArray, 0, myNewArray, 0, length);+

7.Can you explain the core collection interfaces?

There are six interfaces and come under two different inheritance group one which comes under the collection interface root and the other in the map interface root.
It’s the base of all collection classes. It provides a unified way to manipulate collection objects. Collection has group of object called as elements. These elements can be accessed and manipulated using Iterator.
In List interface the elements are arranged sequentially. Elements can be inserted in to any location and you can also insert duplicate elements. In order to access the elements you need to use the “ListIterator”. Using “ListIterator” you can move back and forth which makes it unique as compared to other iterators.
It represents a collection but no duplicates are allowed in this case.
It extends the Set interface and sorts the set in ascending order.
Map stores association between keys and value pairs. So given a key you can easily find the value. One thing important to note is they do not implement iterable interface. But yes you can obtain a collection view of the map which allows you loop using for loop.
it Extends Map so that the keys are maintained in ascending order.

8.What is JAVAdoc utility?

Javadoc parses comments in JAVA source files and produced HTML pages for the same. Below is the syntax for the same javadoc [ options ] [ packagenames ] [ sourcefiles ] [ @files ] Arguments can be in any order. Options Command-line options that is doctitle, windowtitle, header, bottom etc
Packagenames: –
A series of names of packages, separated by spaces, such as java.lang java.lang.reflect java.awt. You must separately specify each package you want to document. Javadoc uses -sourcepath to look for these package names. Javadoc does not recursively traverse subpackages.
sourcefiles :-
A series of source file names, separated by spaces, each of which can begin with a path and contain a wildcard such as asterisk (*). The path that precedes the source file name determines where javadoc will look for it. (Javadoc does not use -sourcepath to look for these source file names.)
@files: – One or more files that contain packagenames and sourcefiles in any order, one name per line.

9.How much subclasses you can maximum in Inheritance?

In one of our old JAVA projects we had an inheritance depth of five. Believe us we never liked that code. It’s bad to have a huge inheritance depth. A maintainable inheritance depth should be maximum 5. Anything above that is horrible. There is no limit as such specified anywhere that there is some limit on the inheritance sub classing . But depending on environments you will get stack over flow error.

10. What is Servlet?

Servlet is small program which execute on the server. The environment exploiting the functionalities of the web server.More

11.What is Servlet life cycle?

There are three methods which are very important in servlet life cycle those one init(), service() and destroy(). Server invokes “init ()” method when servlet is first loaded in to the web server memory. Servlet reads HTTP data provided in HTTP request in the “service ()” method. Once initialized servlet remains in memory to process subsequent request. So for every HTTP request “service ()” method of the servlet is called. Finally when server unloads the “servlet ()” from the memory it calls the “destroy” method which can be used to clean up any resource the servlet is consuming.

12.What are advantages of servlets over CGI?

In CGI for every request there is a new process started which is quiet an overhead. In servlets JVM stays running and handles each request using a light weight thread. In CGI if there are 5000 request then 5000 CGI program is loaded in memory while in servlets there are 5000 thread and only one copy of the servlet class.

13.Can you explain in detail “javax.servlet” package?

javax.servlet package has interfaces and classes which define a framework in which servlets can operate. Let’s first make a walk through of all the interfaces and methods and its description.
Interfaces in javax.servlet :-
Servlet Interface This interface has the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. Following are the method in Servlet interface :- void destroy( ):- Executed when servlet is unloaded from the web server memory. ServletConfig getServletConfig() :- Returns back a ServletConfig object that contains initialization data. String getServletInfo( ):- Returns a string describing the servlet. init method :- Called for first time when the servlet is initialized by the web server. void service() method :- Called to process a request from a client. ServletConfig Interface This interface is implemented by the servlet container. Servlet can access any configuration data when its loaded. The methods declared by this interface are summarized here: Following are the methods in ServletConfig interface:- ServletContext getServletContext():- Gives the servlet context. String getInitParameter(String param):- Returns the value of the initialization parameter named param. Enumeration getInitParameterNames() :- Returns an enumeration of all initialization parameter names.
String getServletName( ) :- Returns the name of the invoking servlet. .

14.What are the two important API’s in for Servlets?

Two important packages are required to build servlet “javax.servlet” and javax.servlet.http”. They form the core of Servlet API. Servlets are not part of core Java but are standard extensions provided by Tomcat.

15.What’s the use of ServletContext?

ServletContext Interface
It gives information about the environment. It represents a Servlet’s view of the Web Application.Using this interface servlet can access raw input streams to Web Application resources, virtual directory translation, a common mechanism for logging information, and an application scope for binding objects.

16.what’s the difference between Authentication and authorization?

Authentication is the process the application identifies that you are who. For example when a user logs into an application with a username and password, application checks that the entered credentials against its user data store and responds with success or failure. Authorization, on the other hand, is when the application checks to see if you’re allowed to do something. For instance are you allowed to do delete or modify a resource.

17.What’s the architecture of a Servlet package?

At the top of all is the main servlet interface which is implemented by the generic servlet. But generic servlet does not provide implementation specific to any protocol. HTTP servlet further inherits from the generic servlet and provides HTTP implementation like “Get” and “Post”. Finally comes our custom servlet which inherits from HTTP Servlet.

18. What are the different ways we can maintain state between requests?

Following are the different ways of maintaining state’s between stateless requests:-
>>URL rewriting
>> Cookies
>>Hidden fields
>> Sessions

19.What’s the difference between GenericServlet and HttpServlet?

HttpServlet class extends GenericServlet class which is an abstract class to provide HTTP protocol-specific functionalities. Most of the java application developers extend HttpServlet class as it provides more HTTP protocol-specific functionalities. You can see in HttpServlet class doGet (), doPOst () methods which are more targeted towards HTTP protocol specific functionalities. For instance we can inherit from GenericServlet class to make something like MobileServlet. So GenericServlet class should be used when we want to write protocol specific implementation which is not available. But when we know we are making an internet application where HTTP is the major protocol its better to use HttpServlet.

20. What is URL rewriting?

It’s based on the concept of attaching a unique ID (which is generated by the server) in the URL of response from the server. So the server attaches this unique ID in each URL.

21.Why is HTTP protocol called as a stateless protocol?

A protocol is stateless if it can remember difference between one client request and the other. HTTP is a stateless protocol because each request is executed independently without any knowledge of the requests that came before it.

22.What are sessions in Servlets?

Session’s can be considered as a series of related interactions between client and the server that take place over a period of time. Because HTTP is a stateless protocol these series of interactions are difficult to track. That’s where we can use HttpSession object to save in between of these interactions so that server can co-relate between interactions between clients.

23.How do we share data using “getServletContext ()?

Using the “getServletContext ()” we can make data available at application level. So servlets which lie in the same application can get the data. Below are important snippets which you will need to add, get and remove data which can be shared across servlets. Figure 4.10 : – Sharing data using “getServletContext ()” You can see in Step1 how “getServletContext().setAttribute()” method can be used add new objects to the “getServletContext” collection. Step2 shows how we can get the object back using “getAttribute()” and manipulate the same. Step3 shows how to remove an already shared application object from the collection. “getServletContext()” object is shared across servlets with in a application and thus can be used to share data between servlets.

24.Which are the different ways you can communicate between servlets?

Below are the different ways of communicating between servlets:-
>> Using RequestDispatcher object.
>> Sharing resource using “ServletContext ()” object.
>> Include response of the resource in the response of the servlet.
>> Calling public methods of the resource.
>> Servlet chaining.

25.What are cookies?

Cookies are piece of data which are stored at the client’s browser to track information regarding the user usage and habits. Servlets sends cookies to the browser client using the HTTP response headers. When client gets the cookie information it’s stored by the browser in the client’s hard disk. Similarly client returns the cookie information using the HTTP request headers.

26.Explain in brief the directory structure of a web application?

Below is the directory structure of a web application:-
The webapp directory contains the JSP files, images, and HTML files. The webapp directory can also contain subdirectories such as images or html or can be organized by function, such as public or private.
The WEB-INF/web.xml file is called the deployment descriptor for the Web application. This file contains configuration information for the Web application, including the mappings of URLs to servlets and filters. The web.xml file also contains configuration information for security, MIME type mapping, error pages, and locale settings
The WEB-INF/classes directory contains the class files for the servlets, JSP files, tag libraries, and any other utility classes that are used in the Web application.
The WEB-INF/lib directory contains JAR files for libraries that are used by the Web application. These are generally third-party libraries or classes for any tag libraries used by the Web application.

27. Explain the concept of SSI ?

Server Side Includes (SSI) are commands and directives placed in Web pages that are evaluated by the Web server when the Web page is being served. SSI are not supported by all web servers. So before using SSI read the web server documentation for the support. SSI is useful when you want a small part of the page to be dynamically generated rather than loading the whole page again.

28.What are cursors and what are the situations you will use them?

SQL statements are good for set at a time operation. So it is good at handling set of data. But there are scenarios where we want to update row depending on certain criteria. we will loop through all rows and update data accordingly. There’s where cursors come in to picture.

29.What’s the difference between “UNION” and “UNION ALL” ?

UNION SQL syntax is used to select information from two tables. But it selects only distinct records from both the table. , while UNION ALL selects all records from both the tables.

30.What is the difference between “HAVING” and “WHERE” clause?

“HAVING” clause is used to specify filtering criteria for “GROUP BY”, while “WHERE” clause applies on normal SQL.

31.What is ” Group by ” clause?

“Group by” clause group similar data so that aggregate values can be derived.

32.What is EJB ?

EJB is a standard for building server side components in JAVA. It specifies an agreement between components and application servers that enables any component to run in any application server. EJB components are deployable and can be imported in to an application server which hosts these components. EJB are not intended for client side they are server side components. They are specially meant for complex server side operations like executing complex algorithms or high volume business transactions.
Above is the most popular architecture in software industry. Three tier architecture has many advantages but the most important of them is that you can change any layer with least changes. For instance you can change the business logic with out making changes to UI or the database side. EJB provides the application layer logic. Application layer logic is also called as middle tier. EJB provides a standard specifications-based way to develop and deploy enterprise-class systems. It’s like moving towards an actually thought JAVA dream that we can run on any vendor platform. This is in contrast to the vendor-specific way we used to develop where each application server had its own way of doing things and where the developer was tied up to a application server.

33.What’s MVC pattern ?

The main purpose of using MVC pattern is to decouple the GUI from the Data. It also gives the ability to provide multiple views for the same Data. MVC pattern separates objects into three important sections:-
Model: – This section is specially for maintaining data. It is actually where your business logic, querying database, database connection etc. is actually implemented.
Views: – Displaying all or some portion of data, or probably different view of data. View is responsible for look and feel, Sorting, formatting etc.
Controller: – They are event handling section which affects either the model or the view. Controller responds to the mouse or keyboard input to command model and view to change. Controllers are associated with views. User interaction triggers the events to change the model, which in turn calls some methods of model to update its state to notify other registered views to refresh their display.

34.Define struts?

Struts are an open source framework for developing JAVA web applications. It extends Java Servlets API and helps developers to adopt MVC architecture. MVC pattern is good but developing the same can be real pain. Using struts it’s a breeze to implement MVC in projects. Struts provide a standard way of implementing MVC.

35.Can you explain the directory structure for a struts folder in brief ?

Below are the folders from point of view of root folder.
META-INF: – This directory has the Meta information.
WEB-INF/classes: – This location has the actual JAVA classes.
WEB-INF/classes/ Contains text which application can
use. For instance error messages.
WEB-INF/lib/struts.jar:- Contains the Struts servlet, helper classes, taglib code etc.
WEB-INF/*.tld:- The Struts tag libraries.
WEB-INF/struts-config.xml:- A Struts configuration file.
WEB-INF/web.xml:- Configuration file for the servlet container
Index.jsp:- All JSP files come in the root directory as this one Index.jsp.

36.How does the server decide which beans to passivate and activate ?

Most servers use the (LRU) Last Recently Used time as a strategy. Which mean passivate the beans which have been called recently.

37.In what format is the conversational data written to the disk ?

Bean conversational data is saved in the disk as serialized object. This is possible because “javax.ejb.EnterpriseBean” implements “” interface. So during passivation time it converts the bean conversational data to a bit-blob and during activation it just reverses the process.

38.Can you give an overview of how a struts application flows ?

just to summarize how the execution flows in the struts application.
User makes browser makes a request to the Struts application that is processed by ActionServlet (Controller).
ActionServlet (Controller) populates the ActionForm (View) object with HTML JSP form data method.
ActionServlet (Controller) executes the Action object (Controller).
Action object uses the model and does the necessary execution and passes the control back to the ActionServlet
Action (Controller) forwards control to the JSP pages.
JSP pages use model data to generate a response to the browser.

39.what are the different kind of EJB’s ?

There are three kinds of EJB’s:-
Session beans
Session beans are construct in EJB. They represent business logic of an application. They represent a group of logical related functionality. For instance you can have a customer session bean which can have functionality like customer interest calculation, customer reporting, customer tax calculation etc. But as these functionalities logically belong to customer they will be included in the customer session bean. In short session bean has business logic.
There are two types of session beans:-
Stateless: – they do not maintain state across method calls. So every time client makes a call it’s like a new object from scratch. Stateful— These beans can hold client state across method invocations. This is possible with the use of instance variables declared in the class definition. Every time the client calls it they can get there previous states. Stateless session bean provide greater scalability as EJB container does not have to maintain state across method invocations. Storing state for EJB container is huge activity.
Entity beans
Entity bean represent persistent data in an EJB application. They provide object-oriented abstraction to a relational database. When Session bean needs to access data it called the entity beans. Entity beans do read, write, update and delete from tables. For instance you have a customer table then you will have customer entity bean which maps to the table and can do the CRUD (Create, Read, Update and Delete) operation to the customer table. From architecture angle you can think entity bean as the data access layer of a system.
Message-driven beans
There are situations in project where you would like to communicate asynchronously with some other systems. This is achieved by using message-driven beans. For instance when user places order you would like to submit it asynchronously to the order system and then move ahead with some other work. You would then later comeback after sometime to see if the order is completely or the order system will notify you about the completion of the order.

40.explain the concept of local interfaces ?

Local objects implement local interface rather than using remote interface. Just to have a comparison below are the steps how the local object works. JAVA client calls the local object. Local object does connection pooling, transactions and security. It then passes calls the bean and when bean completes its work it returns the data to the Local object who then passes the same to the end client. You can understand from the above steps we have by passed completely marshalling and de-marshalling. .

41.what is Passivation and Activation in EJB?

When we are dealing with stateful session beans we need to store the client conversation of the bean so that it can be available in client’s next request. But when we talk about server it has limited resources. If the conversation of the bean is large then the server can run out of resource. So in order to preserve resources EJB server swaps this conversational data in memory to hard disk thus allowing memory to be reclaimed. This process of saving the memory data to hard disk is called as “Passivation”. Now when the client comes back the conversational data is again swapped from the hard disk to the bean. This process is called as “Activation”. The container informs the bean that its about to passivate or activate using the “ejbPassivate()” and “ejbActivate()” methods. do you decide whether you should use session, entity or message driven bean?

Session beans should only implement business logic and work flow.
Entity beans are data objects and represent persistent data. They are only responsible to do database activities like add, update and delete
Message-driven beans are used for receiving asynchronous messages from other systems.

43.explain EJBHome and EJBObject in EJB?

Bean Interface
Client uses the Bean interface to communicate with the session bean which resides on the EJB application server. The Bean interface extends the EJBObject interface of the javax.ejb package. This interface has all the methods, functions which the final session bean has.
Home Interface
In order the client gets a reference to the Bean interface it must call the Beans home interface. The Home interface extends EJBHome interface of the javax.ejb package. Home Interface of a bean is responsible for creating the object and giving the reference of the Bean interface.

44.What are the limitations of using Local object ?

Local object only work if you are calling beans in the same process. Second they marshal data by ref rather than by Val. This may speed up your performance but you need to change semantics for the same. So finally it’s a design and the requirement decision. If you are expecting to call beans remotely then using local object will not work.

45.Can beans who are involved in transaction have “Passivation” process?


46.What is SQLExceptionTranslator ?

SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring’s own data-access-strategy-agnostic org.springframework.dao.DataAccessException.

47.What is IOC (or Dependency Injection)?

The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects. .

48.What are the benefits of IOC (Dependency Injection)?

Benefits of IOC (Dependency Injection) are as follows:
Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
· Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
· Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
· IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

49.What is Spring ?

Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. .

50.What are the advantages of Spring framework?

The advantages of Spring are as follows:
Spring has layered architecture. Use what you need and leave you don’t need now.
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. .

51.What are the different types of IOC (dependency injection) ?

There are three types of dependency injection:
==>Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
==>Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
==>Interface Injection (e.g. Avalon): Injection is done through an interface. Note: Spring supports only Constructor and Setter Injection

52.How many modules are there in Spring? What are they?

Spring comprises of seven modules. They are..
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 application’s 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 Spring-based 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 DAO’s 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 Spring’s 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 multi-part 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.

53.What are features of Spring ?

spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
Inversion of control (IOC):
Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP):
Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Spring contains and manages the life cycle and configuration of application objects.
MVC Framework:
Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
Transaction Management:
Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring’s transaction support is not tied to J2EE environments and it can be also used in container less environments.
JDBC Exception Handling:
The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

54.What is Application Context?

A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
A means for resolving text messages, including support for internationalization.
A generic way to load file resources.
Events to beans that are registered as listeners.

55.What is the difference between Bean Factory and Application Context

On the surface, an application context is same as a bean factory. But application context offers much more..
Application contexts provide a means for resolving text messages, including support for i18n of those messages.
Application contexts provide a generic way to load file resources, such as images.
Application contexts can publish events to beans that are registered as listeners.
Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level
resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable

56.What are the types of Dependency Injection Spring supports?>

Setter Injection:
Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Constructor Injection:
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator

57.What do you mean by Auto Wiring?

The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes. · no · byName · byType · constructor · autodirect

58.What is DelegatingVariableResolver?

Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard Java Server Faces managed beans mechanism which lets you use JSF and Spring together. This variable resolver is called as DelegatingVariableResolver

59.What is Bean Factory ?

A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

60.What do you mean by Bean wiring ?

The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring.

61.How to integrate your Struts application with Spring?

To integrate your Struts application with Spring, we have two options:
Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.
Subclass Spring’s ActionSupport classes and grab your Spring-managed beans explicitly using agetWebApplicationContext()

62.How to integrate Java Server Faces (JSF) with Spring?

? JSF and Spring do share some of the same features, most noticeably in the area of IOC services. By declaring JSF managed-beans in the faces-config.xml configuration file, you allow the FacesServlet to instantiate that bean at startup. Your JSF pages have access to these beans and all of their properties.We can integrate JSF and Spring in two ways:
DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you use JSF and Spring together.
< ?xml version=”1.0″ encoding=”UTF-8 “? >
< faces-config >
< application >
< variable-resolver >
org.springframework.web.jsf.DelegatingVariableResolver < / variable-resolver >
< / application >
< / faces-config >
The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and then to Spring’s ‘business context’ WebApplicationContext. This allows one to easily inject dependencies into one’s JSF-managed beans. FacesContextUtils:custom VariableResolver works well when mapping one’s properties to beans in faces-config.xml, but at times one may need to grab a bean explicitly. The FacesContextUtils class makes this easy. It is similar to WebApplicationContextUtils, except that it takes a FacesContext parameter rather than a ServletContext parameter. ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());

63. What is Java Server Faces (JSF) – Spring integration mechanism?

Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard JavaServer Faces managed beans mechanism. When asked to resolve a variable name, the following algorithm is performed:
Does a bean with the specified name already exist in some scope (request, session, application)? If so, return
Is there a standard JavaServer Faces managed bean definition for this variable name? If so, invoke it in the usual way, and return the bean that was created.
Is there configuration information for this variable name in the Spring WebApplicationContext for this application? If so, use it to create and configure an instance, and return that instance to the caller.
If there is no managed bean or Spring definition for this variable name, return null instead.
BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
As a result of this algorithm, you can transparently use either JavaServer Faces or Spring facilities to create beans on demand. e.

64.What is AOP? and How the AOP used in Spring?

Aspect-oriented programming, or AOP, is a programming technique that allowsprogrammers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.
AOP is used in the Spring Framework: To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on the Spring Framework’s transaction abstraction.To allow users to implement custom aspects, complementing their use of OOP with AOP.

65. What are the ways to access Hibernate using Spring ?

There are two approaches to Spring’s Hibernate integration:
Inversion of Control with a HibernateTemplate and Callback
Extending HibernateDaoSupport and Applying an AOP Interceptor nodes.

66.Explain about the Spring DAO support?

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.

67.What are callable statements ?

callable statements are used from JDBC application to invoke stored procedures and functions.

68.What are types of JDBC drivers?

There are four types of drivers defined by JDBC as follows:
Type 1: JDBC/ODBC—These require an ODBC (Open Database Connectivity) driver for the database to be installed. This type of driver works by translating the submitted queries into equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver. It provides no host redirection capability.
Type2: Native API (partly-Java driver)—This type of driver uses a vendor-specific driver or database API to interact with the database. An example of such an API is Oracle OCI (Oracle Call Interface). It also provides no host redirection.
Type 3: Open Protocol-Net—This is not vendor specific and works by forwarding database requests to a remote database source using a net server component. How the net server component accesses the database is transparent to the client. The client driver communicates with the net server using a database-independent protocol and the net server translates this protocol into database calls. This type of driver can access any database.
Type 4: Proprietary Protocol-Net(pure Java driver)—This has a same configuration as a type 3 driver but uses a wire protocol specific to a particular vendor and hence can access only that vendor’s database. Again this is all transparent to the client.

69.How the JDBC application works?

A JDBC application can be logically divided into two layers:
1. Driver layer
2. Application layer
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.

70.Which type of JDBC driver is the fastest one?

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.

71.What is PreparedStatement?

A prepared statement is an SQL statement that is precompiled by the database. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.
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.

71.How do I load a database driver with JDBC 4.0 / Java 6?

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 backward-compatible, so no changes are needed to the existing JDBC code.

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

73.What is JDBC Driver interface?

The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

74.What is Statement ?

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

75.What does the connection object represents?

The connection object represents communication context, i.e., all communication with database is through connection object only.

76.What are the new features added to JDBC 4.0?

The major features added in JDBC 4.0 include :
Auto-loading of JDBC driver class
Connection management enhancements
Support for RowId SQL type
DataSet implementation of SQL using Annotations
SQL exception handling enhancements
SQL XML support
Learn more about JDBC 4.0 features

77.Exaplain the JDBC Architecture.

The JDBC Architecture consists of two layers:
The JDBC API, which provides the application-to-JDBC Manager connection.
The JDBC Driver API, which supports the JDBC Manager-to-Driver Connection.
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.

78.Explain Basic Steps in writing a Java program using JDBC?

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.
Create JDBC Statement object. This object contains SQL query.
Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query.
Process the result set.
Close the connection.

79.What are the main components of JDBC ?

The life cycle of a servlet consists of the following phases:
DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.
Connection : Interface with all methods for contacting a database.The connection object represents communication context, i.e., all communication with database is through connection object only.
Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
ResultSet: The ResultSet represents set of rows retrieved due to query execution.

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

81.Which is the right type of driver to use and when?

Type I driver is handy for prototyping
Type III driver adds security, caching, and connection control
Type III and Type IV drivers need no pre-installation
Note: Preferred by 9 out of 10 Java developers: Type IV. Click here to learn more about JDBC drivers.

82.What are the standard isolation levels defined by JDBC?

The values are defined in the class java.sql.Connection and are:
Any given database may not support all of these levels.

83.What is resultset ?

The ResultSet represents set of rows retrieved due to query execution.
ResultSet rs = stmt.executeQuery(sqlQuery);
People who read this, also read:-
JSP Interview Questions
JSF Tomahawk Tag Reference
SCJP 5.0 Certification
A first look at Shale Framework
AJAX Interview Questions
21.What are the types of resultsets?
The values are defined in the class java.sql.Connection and are:
TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows within it can be advanced only in the forward direction.
TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.
TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.
Note: A TYPE_FORWARD_ONLY resultset is always insensitive.

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

85.What are the different types  of RowSet ?

There are two types of RowSet are there. They are:
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. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.

86.What are the advantages of DataSource?

The few advantages of data source are :
An application does not need to hardcode driver information, as it does with the DriverManager.
The DataSource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details.
The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions.

87.What is connection pooling? what is the main advantage of using connection pooling?

A connection pool is a mechanism to reuse connections created. Connection pooling can increase performance dramatically by reusing connections rather than creating a new physical connection each time a connection is requested..

88.What is the need of BatchUpdates?

The BatchUpdates feature allows us to group SQL statements together and send to database server in one single trip.

89.What is a DataSource?

A DataSource object is the representation of a data source in the Java programming language. In basic terms,
A DataSource is a facility for storing data.
DataSource can be referenced by JNDI.
Data Source may point to RDBMS, file System , any DBMS etc..

90.What’s the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.

91.How to make a query?

Create a Statement object and calls the Statement.executeQuery method to select data from the database. The result of the query are returned in a ResultSet object.
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(“SELECT data FROM table”);

92.How to navigate the ResultSet?

By default the result set cursor points to the row before the first row of the result set. A call to next() retrieves the first result set row. The cursor can also be moved by calling one of the following ResultSet methods:
beforeFirst(): Puts cursor before the first row of the result set.
first(): Puts cursor on the first row of the result set.
last(): Puts cursor before the last row of the result set.
afterLast(): Puts cursor beyond last row of the result set.
absolute(pos): Puts cursor at the row number position where absolute(1) is the first row and absolute(-1) is the last row.
relative(pos): Puts cursor at a row relative to its current position where relative(1) moves row cursor one row forward.

93.How to update a ResultSet?

An updatable result set allows modification to data in a table through the result set.  You can update a value in a result set by calling the ResultSet Update Methods on the row where the cursor is positioned. The type value here is the same used when retrieving a value from the result set, for example, updateString updates a String value and updateDouble updates a double value in the result set.
rs.updateDouble(“balance”, rs.getDouble(“balance”) – 5.00);
The update applies only to the result set until the call to rs.updateRow(), which updates the underlying database.
To delete the current row, use rs.deleteRow().

94.How to set a scroll type?

Both Statements and PreparedStatements have an additional constructor that accepts a scroll type and an update type parameter. The scroll type value can be one of the following values:
ResultSet.TYPE_FORWARD_ONLY:  Default behavior in JDBC 1.0, application can only call next() on the result set.
ResultSet.SCROLL_SENSITIVE: ResultSet is fully navigable and updates are reflected in the result set as they occur.
ResultSet.SCROLL_INSENSITIVE: Result set is fully navigable, but updates are only visible after the result set is closed. You need to create a new result set to see the results.

95.How to set update type parameter?

To set update type parameter in the constructors of Statements and PreparedStatements, you may use
ResultSet.CONCUR_READ_ONLY: The result set is read only.
ResultSet.CONCUR_UPDATABLE: The result set can be updated.

96.How to do a batch job?

By default, every JDBC statement is sent to the database individually. To send multiple statements at one time, use addBatch() method to append statements to the original statement and call executeBatch() method to submit entire statement.
Statement stmt = con.createStatement();
stmt.addBatch(“update registration set balance=balance-5.00 where theuser=”+theuser);
stmt.addBatch(“insert into auctionitems(description, startprice) ” +

int[] results = stmt.executeBatch();
The return result of the addBatch() method is an array of row counts affected for each statement executed in the batch job. If a problem occurred, a java.sql.BatchUpdateException is thrown. An incomplete array of row counts can be obtained from BatchUpdateException by calling its getUpdateCounts() method.

97.How to use meta data to check a column type?

Use getMetaData().getColumnType() method to check data type. For example to retrieve an Integer, you may check it first:
To insert a new row, use rs.moveToInsertRow().

98.What is the difference among “dropping a table”, “truncating a table” and “deleting all records” from a table?

Dropping:  Table structure + Data are deleted. Invalidates the dependent objects and drops the indexes
Truncating:  Data alone deleted. Performs an automatic commit and faster than delete.
Delete: Data alone deleted. Doesn’t perform automatic commit

99.What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

Cursors allow row-by-row prcessing of the resultsets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven.

Disadvantages of cursors:
A) In cursors each time you fetch a new row it does a round trip with the database thereby increase network use and time.
B) There is also restriction on select statements that can be used in cursors
C) It also uses more resources and temporary memory
Cursors can be avoided with the help of careful implementation of while loop and other set based operations.

100.What are triggers? How to invoke a trigger on demand?

Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.
Triggers can’t be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.

101.Why cannot java.util.Date match with java.sql.Date?

Because java.util.Date represents both date and time. SQL has three types to represent date and time.
java.sql.Date — (00/00/00)
java.sql.Time — (00:00:00)
java.sql.Timestamp — in nanoseconds
Note that they are subclasses of java.util.Date.

Also Read:

Advanced Java Interview Questions -1

Advanced Java Interview Questions –2

Advanced Java Interview Questions –3

Advanced Java Interview Questions –4

Advanced Java Interview Questions -5

Advanced Java Interview Questions -6

Advanced Java Interview Questions -7

Advanced Java Interview Questions -8

Advanced Java Interview Questions -9

Advanced Java Interview Questions -10

Advanced Java Interview Questions -11

Advanced Java Interview Questions -12

Advanced Java Interview Questions -13

Advanced Java Interview Questions -14   



This site uses Akismet to reduce spam. Learn how your comment data is processed.