Java

Java Interview Questions

Java Interview Questions -33

1.What is an Aspect?

An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, you can create a logging aspect and apply it throughout your application using AOP.

2.What is a Jointpoint?

A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.

3.What is an Advice?

Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints.

4.What is a Pointcut?

A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where theadvice can be applied.

5.What are the important methods of ActionForm?

The important methods of ActionForm are : validate() & reset().

6.Describe validate() and reset() methods ?

i.validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request).
ii. reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm’s data members prior to the new request values being set.
public void reset() {}.

7.What is a framework?

A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.

8.What are the components of Struts?

Struts components can be categorize into Model, View and Controller:
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.

9.What is ActionMapping?

Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is complete.

10.What is Struts framework?

Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

11.How is the Action Mapping specified ?

We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from <ActionMapping> configuration element of struts-config.xml file

An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.

13.In which method of Action class the business logic is executed ?

In the execute() method of Action class the business logic is executed.

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;
execute() method of Action class:
Perform the processing required to deal with this request
Update the server-side objects (Scope variables) that will be used to create the next page of the user interface.Return an appropriate ActionForward object

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.

17.How to use DispatchAction?

To use the DispatchAction, follow these steps:
1.Create a class that extends DispatchAction (instead of Action)
2.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.
3.Do not override execute() method – Because DispatchAction class itself provides execute() method.
4.Add an entry to struts-config.xml

18.What is the use of ForwardAction?

The ForwardAction class is useful when you’re 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 don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.

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

20.What is the difference between ForwardAction and IncludeAction?

The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp. 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.

21.What is SwitchAction?

The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending.

22.What if <action> element has <forward> declaration with same name as global forward?

In this case the global forward is not used. Instead the <action> element’s <forward> takes precendence.

23.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.DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.
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( .. ).

24.What is the life cycle of ActionForm?

The lifecycle of ActionForm invoked by the RequestProcessor is as follows:
1.Retrieve or Create Form Bean associated with Action
2.”Store” FormBean in appropriate scope (request or session)
3.Reset the properties of the FormBean
4.Populate the properties of the FormBean
5.Validate the properties of the FormBean
6.Pass FormBean to Action

25. What is Jakarta Struts Framework?

Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

26.What is LookupDispatchAction?

The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.

27.What is the use of LookupDispatchAction?

LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.

28.What is difference between LookupDispatchAction and DispatchAction?

The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.

29.What is ActionServlet?

The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

30.How you will make available any Message Resources Definitions file to the Struts Framework Environment?

Message Resources Definitions file are simple properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through < message-resources /> tag.
Example:
< message-resources parameter=”MessageResources” />.

31.What is Action Class?

The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

32.What is ActionForm?

An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

33.What is Struts Validator Framework?

Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.
The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

34.Give the Details of XML files used in Validator Framework?

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

35.How you will display validation fail errors on jsp page?

Following tag displays all the errors:
< html:errors/>

36.How you will enable front-end validation based on the xml in validation.xml?

The < html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: < html:javascript formName=”logonForm” dynamicJavascript=”true” staticJavascript=”true” /> generates the client side java script for the form “logonForm” as defined in the validation.xml file. The < html:javascript> when added in the jsp file generates the client site validation script.

37.How to get data from the velocity page in a action class?

We can get the values in the action classes by using data.getParameter(“variable name defined in the velocity page”);

From the EJB Spec : – A Session bean’s home interface defines one or morecreate(…) methods. Each create method must be named create and must match one of the ejbCreate methods defined in the enterprise Bean class. The return type of a create method must be the enterprise Bean’s remote interface type. The home interface of a stateless session bean must have one create method that takes no arguments.

40.Is struts threadsafe?Give an example?

Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action.

41.Can we Serialize static variable?

Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular object’s state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields. There are four basic things you must do when you are making a class serializable. They are:
1. Implement the Serializable interface.
2. Make sure that instance-level, locally defined state is serialized properly.
3. Make sure that superclass state is serialized properly.
4. Override equals( )and hashCode( ).
it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process .

It’s the job of handlers to transfer the requests to appropriate models as they are bound to the model layer of MVC architecture. Handlers use mapping information from configuration files for request transfer.

44.What’s the flow of requests in Struts based applications?

Struts based applications use MVC design pattern. The flow of requests is as follows:
i.User interacts with View by clicking any link or by submitting any form.
ii.Upon user’s interaction, the request is passed towards the controller.
iii.Controller is responsible for passing the request to appropriate action.
iv.Action is responsible for calling a function in Model which has all business logic implemented.
v.Response from the model layer is received back by the action which then passes it towards the view where user is able to see the response.

45.Which file is used by controller to get mapping information for request routing?

Controller uses a configuration file “struts-config.xml file to get all mapping information to decide which action to use for routing of user’s request.

46.What’s the role of Action Class in Struts?

In Struts, Action Class acts as a controller and performs following key tasks:
after receiving user request, it processes the user’s request.Uses appropriate model and pulls data from model (if required).Selects proper view to show the response to the user.

47. What are the two types of validations supported by Validator FrameWork?

Validator Framework is used for form data validation. This framework provides two types of validations:
1.Client Side validation on user’s browser
2.Server side validation

48. What are the steps of Struts Installation?

In order to use Struts framework, we only need to add Struts.Jar file in our development environment. Once jar file is available in the CLASSPATH, we can use the framework and develop Strut based applications.

49. How duplicate form submission can be controlled in Struts?

In Struts, action class provides two important methods which can be used to avoid duplicate form submissions.

saveToken() method of action class generates a unique token and saves it in the user’s session. isTokenValid() method is used then used to check uniqueness of tokens.

50. In Struts, how can we access Java beans and their properties?

Bean Tag Library is a Struts library which can be used for accessing Java beans.

51. Which configuration file is used for storing JSP configuration information in Struts?

For JSP configuration details, Web.xml file is used.

52.What’s the purpose of Execute method of action class?

Execute method of action class is responsible for execution of business logic. If any processing is required on the user’s request, it’s performed in this method. This method returns actionForward object which routes the application to appropriate page.

53.What’s the difference between validation.xml and validator-rules.xml files in Struts Validation framework?

In Validation.xml, we define validation rules for any specific Java bean while in validator-rules.xml file, standard and generic validation rules are defined.

54.How can we display all validation errors to user on JSP page?

To display all validation errors based on the validation rules defined in validation.xml file, we use <html:errors /> tag in our JSP file.

55.What’s declarative exception handling in Struts?

When logic for exception handling is defined in struts-config.xml or within the action tag, it’s known as declarative exception handling in Struts.

56.What’s DynaActionForm?

DynaActionForm is a special type of actionForm class (sub-class of ActionForm Class) that’s used for dynamically creating form beans. It uses configuration files for form bean creation.

57.What’s the difference between Jakarta Struts and Apache Struts? Which one is better to use?

Both are same and there is no difference between them.

58.What’s the use of Struts.xml configuration file?

Struts.xml file is one the key configuration files of Struts framework which is used to define mapping between URL and action. When a user’s request is received by the controller, controller uses mapping information from this file to select appropriate action class.

59.What’s the significance of logic tags in Struts?

Use of logic tags in Struts helps in writing a clean and efficient code at presentation layer without use of scriptlets.

60.What are the two scope types for formbeans?

1. Request Scope: Formbean values are available in the current request only
2. Session Scope: Formbean values are available for all requests in the current session.

61. How can we group related actions in one group in Struts?

To group multiple related actions in one group, we can use DispatcherAction class.

62. When should we use SwtichAction?

The best scenario to use SwitchAction class is when we have a modular application with multiple modules working separately. Using SwitchAction class we can switch from a resource in one module to another resource in some different module of the application.

63. What are the benefits of Struts framework?

Struts is based on MVC and hence there is a good separation of different layers in Struts which makes Struts applications development and customization easy. Use of different configuration files makes Struts applications easily configurable. Also, Struts is open source and hence, cost effective.

64. What steps are required to for an application migration from Struts1 to Struts2?

For validation of populated properties, validate() method of ActionForm class is used before handling the control of formbean to Action class.

66. What’s the use of reset method of ActionForm class?

reset method of actionForm class is used to clear the values of a form before initiation of a new request.

67. What are disadvantages of Struts?

Although Struts have large number of advantages associated, it also requires bigger learning curve and also reduces transparency in the development process.

Struts also lack proper documentation and for many of its components, users are unable to get proper online resources for help.

68. What’s the use of resourcebundle.properties file in Struts Validation framework?

resourcebundle.properties file is used to define specific error messages in key value pairs for any possible errors that may occur in the code.This approach helps to keep the code clean as developer doesn’t need to embed all error messages inside code.

69. Can I have html form property without associated getter and setter formbean methods?

For each html form property, getter and setter methods in the formbean must be defined otherwise application results in an error.

70. How many servlet controllers are used in a Struts Application?

Struts framework works on the concept of centralized control approach and the whole application is controlled by a single servlet controller. Hence, we require only one servlet controller in a servlet application.

71. Which model components are supported by Struts?

Struts support all types of models including Java beans, EJB, CORBA. However, Struts doesn’t have any in-built support for any specific model and it’s the developer’s choice to opt for any model.

72. When it’s useful to use IncludeAction?

IncludeAction is action class provided by Struts which is useful when an integration is required between Struts and Servlet based application.

73. Is Struts thread safe?

Yes Struts are thread safe. In Struts, a new servlet object is not required to handle each request; rather a new thread of action class object is used for each new request.

74. What configuration changes are required to use resource files in Struts?

Resource files (.properties files) can be used in Struts by adding following configuration entry in struts-config.xml file:
<message-resources parameter=”com.login.struts.ApplicationResources”/>

75. How nested beans can be used in Struts applications?

Struts provide a separate tag library (Nested Tag Library) for this purpose. Using this library, we can nest the beans in any Struts based application.

In Struts framework, actionServlet acts as a controller and all the requests made by users are controlled by this controller. ActionServlet is based on singleton design patter as only one object needs to be created for this controller class. Multiple threads are created later for each user request.

80. Which technologies can be used at View Layer in Struts?

In Struts, we can use any of the following technologies in view layer:
1.JSP
ii.HTML
iii.XML/XSLT
iv.WML Files
v.Velocity Templates
vi.Servlets

81. What are the conditions for actionForm to work correctly?

ActionForm must fulfill following conditions to work correctly:It must have a no argument constructor.It should have public getter and setter methods for all its properties.

82. Which library is provided by Struts for form elements like check boxes, text boxes etc?

Struts provide HTML Tags library which can be used for adding form elements like text fields, text boxes, radio buttons etc.

83.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.
1.JavaBeans components for managing application state and behavior.
2.Event-driven development (via listeners as in traditional GUI development).
3.Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

84.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 user’s request.

85.What is role of ActionServlet?

ActionServlet performs the role of Controller:
1.Process user requests
2.Determine what the user is trying to achieve according to the request
3.Pull data from the model (if necessary) to be given to the appropriate view,
4.Select the proper view to respond to the user
5.Delegates most of this grunt work to Action classes
6.Is responsible for initialization and clean-up of resources

86.What is the ActionForm?

ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

87. What are derived properties?

The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

88.Define HibernateTemplate?

org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

89.What is a SessionFactory? Is it a thread-safe object?

SessionFactory is Hibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

90.What is a Session? Can you share a session object between different theads?

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.

91.What are the benefits of detached objects?

Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

92.How do you switch between relational databases without code changes?

Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

93.If you want to see the Hibernate generated SQL statements on console, what should we do?

In Hibernate configuration file set as follows:
<property name=”show_sql”>true</property>

94.What are derived properties?
The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

95.What is component mapping in Hibernate?
* A component is an object saved as a value, not as a reference
* A component can be saved directly without needing to declare interfaces or identifier properties
* Required to define an empty constructor
* Shared references not supported

96.What is an Introduction in AOP?

An introduction allows the user to add new methods or attributes to an existing class. This can then be introduced to an existing class without having to change the structure of the class, but give them the new behavior and state.

97.What is a Target?

A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to anyadvice that is being applied.

98 What is a Proxy?

A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

99.What is meant by Weaving?

The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven into the target object at the specified joinpoints.

100.What are the different points where weaving can be applied?

i.Compile Time
ii.Classload Time
iii.Runtime

101.What are different types of Autowire types?

There are four different types by which autowiring can be done.

1 byName
2 byType
3 constructor
4 autodetect

102.What is Significance of JSF- Spring integration?

Spring – JSF integration is useful when an event handler wishes to explicitly invoke the bean factory to create beans on demand, such as a bean that encapsulates the business logic to be performed when a submit button is pressed.

103.What are the important beans lifecycle methods?

There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.

104.What are Inner Beans?

When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused anywhere else.

105.What are the different types of bean injections?

There are two types of bean injections.
1. By setter
2. By constructor