Friday, December 28, 2012

Core Java Interview Questions - Classes & Interfaces

1. What's the difference between an interface and an abstract class?
An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

2. Can an inner class declared inside of a method access local variables of this method?

Yes, it is possible if the variables are declared as final.

3. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

Sometimes. But your class may be a descendent of another class and in this case the interface is your only option because Java does not support multiple inheritance.

4. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?

You do not need to specify any access level, and Java will use a default package access level. A class with default access will be accessible only to other classes that are declared in the same directory/package.

5. When you declare a method as abstract method ?

We declare a method as abstract, When we want child class to implement the behavior of the method.

6. Can I call a abstract method from a non abstract method ?

Yes, We can call a abstract method from a Non abstract method in a Java abstract class

7. What is the difference between an Abstract class and Interface in Java ? or can you explain when you use Abstract classes ?

Abstract classes let you define some behavior while forcing your subclasses to provide the rest. These abstract classes will provide the basic funcationality of your application, child class which inherit this class will provide the funtionality of the abstract methods in abstract class.

Whereas, An Interface can only declare constants and instance methods, but cannot implement any default behavior.

If you want your class to extend some other class but at the same time re-use some features outlined in a parent class/interface - Interfaces are your only option because Java does not allow multiple inheritance and once you extend an abstract class, you cannot extend any other class. But, if you implement an interface, you are free to extend any other concrete class as per your wish.

Also, Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.

8. What are different types of inner classes ?

Inner classes nest within other classes. A normal class is a direct member of a package. Inner classes are of four types

1. Static member classes
2. Member classes
3. Local classes
4. Anonymous classes

9. What are the field/method access levels (specifiers) and class access levels ?

Each field and method has an access level corresponding to it:

private: accessible only in this class
package: accessible only in this package
protected: accessible only in this package and in all subclasses of this class
public: accessible everywhere this class is available

Similarly, each class has one of two possible access levels:

package: class objects can only be declared and manipulated by code in this package
public: class objects can be declared and manipulated by code in any package

10. What modifiers may be used with an inner class that is a member of an outer class?

A non-local inner class may be declared as public, protected, private, static, final, or abstract.

11. Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

12. What must a class do to implement an interface?

It must provide implementation to all of the methods in the interface and identify the interface in its implements clause in the class declaration line of code.

13. What is the difference between a static and a non-static inner class?

A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

14. When can an object reference be cast to an interface reference?

An object reference be cast to an interface reference when the object implements the referenced interface.

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.

24. Can you make an instance of abstract class

No you cannot create an instance of abstract class. If you use new keyword to instantiate an abstract class, you will get a compilation error.

25. Describe what happens when an object is created in Java

Several things happen in a particular order to ensure the object is created properly:

1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the
object and its superclasses. Implemenation-specific data includes pointers to class and method data.

2. The instance variables of the objects are initialized to their default values.

3. The constructor for the most derived class is invoked. The first thing a constructor does is call the
consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.

4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

26. What is the purpose of System Class

The purpose of the system class is to provide the access to the System reources

27. What is instanceOf operator used for

It is used to check if an object can be cast into a specific type without throwing Class cast exception

28. Why we should not have instance variable in an interface?

Since all data fields and methods in an Interface are public by default, when we implement that interface in our class, we have public members in our class and this class will expose these data members and this is violation of encapsulation as now the data is not secure

29. What is a singleton class

A singleton is an object that cannot be instantiated more than once. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy. We accomplish this by declaring the constructor private and having a public static instance variable of the class's type that can be accessed using a getInstance() method in the class.

30. Can an abstract class have final method

Yes, you can have a final method in an Abstract class.

31. Can a final class have an abstract method

No, a Final class cannot have an Abstract method.

32. When does the compiler insist that the class must be abstract

The compiler insists that your class be made abstract under the following circumstances:

1. If one or more methods of the class are abstract.
2. If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method
3. If class implements an interface and provides no implementation for some methods

33. How is abstract class different from final class

Abstract class must be subclassed and an implementation has to be provided by the child class whereas final class cannot be subclassed

34. What is an inner class

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

Core Java Interview Questions - Exception handling

Exception Handling

1. How could Java classes direct messages to a file instead of the Console?
The System class has a variable "out" that represents the standard output, and the variable "err" that represents the standard error device. By default, they both point at the system console.

The standard output could be re-directed to a file as follows:

Stream st = new Stream(new FileOutputStream("output.txt"));
System.setErr(st);
System.setOut(st);

2. Does it matter in what order catch statements for FileNotFoundException and IOException are written?

Yes, it does. The child exceptions classes must always be caught first and the "Exception" class should be caught last.

3. What is user-defined exception in java ?

User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inheriting the Exception class. Using this class we can create & throw new exceptions.

4. What is the difference between checked and Unchecked Exceptions in Java ?

Checked exceptions must be caught using try-catch() block or thrown using throws clause. If you dont, compilation of program will fail. whereas we need not catch or throw Unchecked exceptions.

5. What is the catch or declare rule for method declarations?

If a checked exception may be thrown within the body of a method, the method must either catch that exception or declare it in its throws clause. This is done to ensure that there are no orphan exceptions that are not handled by any method.

6. What is the purpose of the finally clause of a try-catch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. It is usually used in places where we are connecting to a database so that, we can close the connection or perform any cleanup even if the query execution in the try block caused an exception.

7. What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

8. Can an exception be rethrown?

Yes, an exception can be rethrown any number of times.

9. When is the finally clause of a try-catch-finally statement executed?

The finally clause of the try-catch-finally statement is always executed after the catch block is executed, unless the thread of execution terminates or an exception occurs within the execution of the finally clause.

10. What classes of exceptions may be thrown by a throw statement?

A throw statement may throw any expression that may be assigned to the Throwable type.

11. What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.


12. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.

13. Can try statements be nested?

Try statements can be tested. It is possible to nest them to any level, but it is preferable to keep the nesting to 2 or 3 levels at max.


14. How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception that was thrown, is executed. The remaining catch clauses are ignored.

15. What is difference between error and exception

Error occurs at runtime and cannot be recovered, Outofmemory is one such example. Exceptions on the other hand are due conditions which the application encounters, that can be recovered such as FileNotFound exception or IO exceptions

16. What is the base class from which all exceptions are subclasses

All exceptions are subclasses of a class called java.lang.Throwable

17. How do you intercept and control exceptions

We can intercept and control exceptions by using try/catch/finally blocks.

You place the normal processing code in try block
You put the code to deal with exceptions that might arise in try block in catch block
Code that must be executed no matter what happens must be place in finally block

18. When do we say an exception is handled

When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled. Or when an exception thrown by a method is caught by the calling method and handled, an exception can be considered handled.

19. When do we say an exception is not handled

There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed

20. In what sequence does the finally block gets executed

If you put finally after a try block without a matching catch block then it will be executed after the try block
If it is placed after the catch block and there is no exception then also it will be executed after the try block
If there is an exception and it is handled by the catch block then it will be executed after the catch block

21. What can prevent the execution of the code in finally block

Theoretically, the finally block will execute no matter what. But practically, the following scenarios can prevent the execution of the finally block.

* The death of thread
* Use of system.exit()
* Turning off the power to CPU
* An exception arising in the finally block itself


22. What are the rules for catching multiple exceptions?

A more specific catch block must precede a more general one in the source, else it gives compilation error about unreachable code blocks.


23. What does throws statement declaration in a method indicate?

This indicates that the method throws some exception and the caller method should take care of handling it. If a method invokes another method that throws some exception, the compiler will complain until the method itself throws it or surrounds the method invocation with a try-catch block.

24. What are checked exceptions?

Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems. Checked Exceptions can be caught and handled by the programmer to avoid random error messages on screen.

25. What are runtime exceptions

Runtime exceptions are due to programming bugs like out of bound arrays or null pointer exceptions.

26. What is difference between Exception and errors

Errors are situations that cannot be recovered and the system will just crash or end. Whereas, Exceptions are just unexpected situations that can be handled and the system can recover from it. We usually catch & handle exceptions while we dont handle Errors.

27. How will you handle the checked exceptions

You can provide a try/catch block to handle it or throw the exception from the method and have the calling method handle it.

28. When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original 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

Struts Interview Questions


1. What is Struts framework?

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

2. What design patterns are used in Struts?

Struts is based on model 2 MVC (Model-View-Controller) architecture.

Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern.

Struts also implement the following J2EE design patterns.
a. Service to Worker
b. Dispatcher View
c. Composite View (Struts Tiles)
d. Front Controller
e. View Helper
f. Synchronizer Token

An important point to note here is that, not all of these patterns may be used in every Struts based application and you may not require to remember all of these patterns. If you know that Struts is based on the MVC Framework, that is more than sufficient.

3. What is the MVC Framework?

MVC Stands for Model View Controller Framework

Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.

Model - The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.

View - The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.

Controller - The controller reacts to the user input. It creates and sets the model.

4. What are the components of a Struts based application?

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.

5. What is the ActionServlet?

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

6. What is the role of an ActionServlet?

ActionServlet performs the role of Controller. It does the following:

a. Process user requests
b. Determine what the user is trying to achieve according to the request
c. Pull data from the model (if necessary) to be given to the appropriate view,
d. Select the proper view to respond to the user
e. Delegates most of this grunt work to Action classes
f. Is responsible for initialization and clean-up of resources

7. What is the ActionForm?

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

8. What are the important methods of ActionForm?

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

9. Describe the validate() and reset() methods of the ActionForm?

The validate() method is used to validate properties after they have been populated (In the JSP). It is called before FormBean is handed over to the Action. It returns a collection of ActionError objects as ActionErrors. Following is the method signature for the validate() method.

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)

The 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. Following is the method signature of the reset() method.

public void reset() {}

10. What is ActionMapping?

The 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 over.

For ex: You enter your credentials in the login page of your bank's internet banking website and then hit the "Login" button. How would the system know what to do next? It refers to the ActionMappings to find out what to do next based on the action chosen by the user.


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 configuration element of struts-config.xml file



< action-mappings >
< action path="/submit" type="submit.SubmitAction" name="submitForm" input="/submit.jsp" scope="request" validate="true" >
< forward name="success" path="/success.jsp" / >
< forward name="failure" path="/error.jsp" / >
< / action >
< / action-mappings >


12. What is role of Action Class?

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.

Practically speaking, this class contains all the logic of what to do in response to the user action. Remember the login to banks website example I gave a couple of questions back, the system actually goes to the Action class corresponding to your action (Login) to try to figure out what needs to be done next.

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

In the execute() method of Action class the business logic is executed. It performs the processing required to deal with this request, updates the server-side objects (Scope variables) that will be used to create the next page of the user interface and returns an appropriate ActionForward object

14. Can you give me a sample code for this execute method's Signature?


public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;


15. Can we have more than one struts-config.xml file for a single Struts application?

A lot of people think that having multiple struts config files isnt possible for a single application but the truth is, it is very well possible. Unfortunately, in most real life scenarios, we would be using only one struts config file even though we can have many.

16. How would you configure your application to have multiple struts config files?

They can be configured as follows in your web.xml file:



< 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 difference between session scope and request scope when saving the formbean in struts?

When the scope is request,the values of formbean would be available for the current request. Whereas, when the scope is session, the values of formbean would be available throughout the session.


18. What are the different kinds of actions in Struts?

The different kinds of actions in Struts are:
ForwardAction
IncludeAction
DispatchAction
LookupDispatchAction
SwitchAction

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

20. How will you use the 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


21. When would you use the 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.


22. When would you use the 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.

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

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

25. When would you use 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. This is typically useful when you create something that will be shared across different locales. For ex: The login page of an international banks website would look surprisingly similar in almost all countries. It does the same thing in all countries but what exactly happens after you finish the login depends on the country you are. So, this is the kind if scenario where LookupDispatchAction would come in handy.

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

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

28. What if element has declaration with same name as global forward?

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

29. What is DynaActionForm?

DynaActionForm is 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. Since the developer need not create actual bean java classes, a lot of developers prefer DynaActionForms.

30. 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:

First in the struts-config.xml: change your to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm.

Example:


< form-bean name="loginForm"type="org.apache.struts.action.DynaActionForm" >
< form-property name="userName" type="java.lang.String" / >
< form-property name="password" type="java.lang.String" / >
< / form-bean >


Second - In your Action subclass that uses your form bean:

1. import org.apache.struts.action.DynaActionForm
2. downcast the ActionForm parameter in execute() to a DynaActionForm
3. access the form fields with get(field) rather than getField()

Example:


......

public class DynaActionFormExample extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm loginForm = (DynaActionForm) form;
ActionMessages errors = new ActionMessages();
if (((String) loginForm.get("userName")).equals("")) {
errors.add("userName", new ActionMessage(
"error.userName.required"));
}
if (((String) loginForm.get("password")).equals("")) {
errors.add("password", new ActionMessage(
"error.password.required"));
}
...........


31. How would you display validation errors on jsp page in a Struts Application?

tag displays all the errors. iterates over ActionErrors request attribute. Remember the ActionErrors that get created while using the validate() method? See Question No. 9 if you dont remember...


32. What are the various Struts tag libraries?

The various Struts tag libraries are:
1. HTML Tags
2. Bean Tags
3. Logic Tags
4. Template Tags
5. Nested Tags
6. Tiles Tags

33. What is the use of ?

repeats the nested body content of this tag over a specified collection.

example:



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


34. 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" / >


35. How the exceptions are handled in struts?

Exceptions in Struts are handled in two ways:
1. Programmatic exception handling - Using 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.

2. Declarative exception handling - You can either define handling tags in your struts-config.xml or define the exception handling tags within tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.

36. Can you give an example of Programmatic Exception Handling?


< global-exceptions >
< exception key="some.key" type="java.lang.NullPointerException" path="/WEB-INF/errors/null.jsp" / >
< / global-exceptions >


37. Can you give an example of declarative exception handling?


< exception key="some.key" type="package.SomeException" path="/WEB-INF/somepage.jsp" / >


38. What are some benefits of using DynaActionForm?

The biggest advantage is that - we need not create multiple classes to hold form information. We can just declare forms as and when required inside the struts-config.xml file and we are good to go.

39. Can you think of any drawbacks of the DynaActionForm?

Of Course. Every coin has two sides. Some drawbacks of using DynaActionForm could be:

1. The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger and the config file in itself could become unmanageable
2. 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.
3. ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.


40. 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 struts-config.xml.
< message-resources parameter="com.login.struts.ApplicationResources" />

Hibernate Interview Questions

Does Hibernate implement its functionality using a minimal number of database queries to ensure optimal output?
Hibernate can make certain optimizations all the time:
Caching objects - The session is a transaction-level cache of persistent objects. You may also enable a JVM-level/cluster cache to memory and/or local disk.
Executing SQL statements later, when needed - The session never issues an INSERT or UPDATE until it is actually needed. So if an exception occurs and you need to abort the transaction, some statements will never actually be issued. Furthermore, this keeps lock times in the database as short as possible (from the late UPDATE to the transaction end).
Never updating unmodified objects - It is very common in hand-coded JDBC to see the persistent state of an object updated, just in case it changed.....for example, the user pressed the save button but may not have edited any fields. Hibernate always knows if an object's state actually changed, as long as you are inside the same (possibly very long) unit of work.
Efficient Collection Handling - Likewise, Hibernate only ever inserts/updates/deletes collection rows that actually changed.
Rolling two updates into one - As a corollary to (1) and (3), Hibernate can roll two seemingly unrelated updates of the same object into one UPDATE statement.
Updating only the modified columns - Hibernate knows exactly which columns need updating and, if you choose, will update only those columns.
Outer join fetching - Hibernate implements a very efficient outer-join fetching algorithm! In addition, you can use subselect and batch pre-fetch optimizations.
Lazy collection initialization
Lazy object initialization - Hibernate can use runtime-generated proxies (CGLIB) or interception injected through byte code instrumentation at build-time.

2. Why not implement instance-pooling in Hibernate?

Firstly, it would be pointless. There is a lower bound to the amount of garbage Hibernate creates every time it loads or updates and object - the garbage created by getting or setting the object's properties using reflection.
More importantly, the disadvantage of instance-pooling is developers who forget to reinitialize fields each time an instance is reused. We have seen very subtle bugs in EJBs that don't reinitialize all fields in ejbCreate.
On the other hand, if there is a particular application object that is extremely expensive to create, you can easily implement your own instance pool for that class and use the version of Session.load() that takes a class instance. Just remember to return the objects to the pool every time you close the session.

3. Does Hibernate use runtime reflection?

Many former C or C++ programmers prefer generated-code solutions to runtime reflection. This is usually justified by reference to the performance red-herring. However, modern JVMs implement reflection extremely efficiently and the overhead is minimal compared to the cost of disk access or IPC. Developers from other traditions (e.g. Smalltalk) have always relied upon reflection to do things that C/C++ needs code-generation for.
In the very latest versions of Hibernate, "reflection" is optimised via the CGLIB runtime byte code generation library. This means that "reflected" property get / set calls no longer carry the overhead of the Java reflection API and are actually just normal method calls. This results in a (very) small performance gain.

4. How do I use Hibernate in an EJB 2.1 session bean?

1. Look up the SessionFactory in JNDI.
2. Call getCurrentSession() to get a Session for the current transaction.
3. Do your work.
4. Don't commit or close anything, let the container manage the transaction.

5. What’s the easiest way to configure Hibernate in a plain Java application (without using JNDI)?

Build a SessionFactory from a Configuration object.

6. What is Middlegen?

Middlegen is an open source code generation framework that provides a general-purpose database-driven engine using various tools such as JDBC, Velocity, Ant and XDoclet.

7. How can I count the number of query results without actually returning them?

Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();
8. How can I find the size of a collection without initializing it?

Integer size = (Integer) s.createFilter( collection, "select count(*)" ).uniqueResult();

9. How can I order by the size of a collection?

Use a left join, together with group by
select user
from User user
left join user.messages msg
group by user
order by count(msg)

10. How can I place a condition upon a collection size?

If your database supports subselects:
from User user where size(user.messages) >= 1
or:
from User user where exists elements(user.messages)
If not, and in the case of a one-to-many or many-to-many association:
select user
from User user
join user.messages msg
group by user
having count(msg) >= 1
Because of the inner join, this form can't be used to return a User with zero messages, so the following form is also useful
select user
from User as user
left join user.messages as msg
group by user
having count(msg) = 0

11. How can I query for entities with empty collections?

from Box box
where box.balls is empty
Or, try this:
select box
from Box box
left join box.balls ball
where ball is null

12. How can I sort / order collection elements?

There are three different approaches:
1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or < set > or < map >. This solution does a sort in memory.
2. Specify an order-by attribute of < set >, < map > or < bag >, naming a list of table columns to sort by. This solution works only in JDK 1.4+.
3. Use a filter session.createFilter( collection, "order by ...." ).list()

13. Are collections pageable?

Query q = s.createFilter( collection, "" );
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();
I have a one-to-one association between two classes. Ensuring that associated objects have matching identifiers is bug-prone. Is there a better way?
< generator class="foreign" >
< param name="property" > parent < / param >
< / generator >
I have a many-to-many association between two tables, but the association table has some extra columns (apart from the foreign keys). What kind of mapping should I use?
Use a composite-element to model the association table. For example, given the following association table:
create table relationship (
fk_of_foo bigint not null,
fk_of_bar bigint not null,
multiplicity smallint,
created date )
you could use this collection mapping (inside the mapping for class Foo):
< set name="relationship" >
< key column="fk_of_foo" / >
< composite-element class="Relationship" >
< property name="multiplicity" type="short" not-null="true" / >
< property name="created" type="date" not-null="true" / >
< many-to-one name="bar" class="Bar" not-null="true" / >
< / composite-element >
< / set >
You may also use an with a surrogate key column for the collection table. This would allow you to have nullable columns.
An alternative approach is to simply map the association table as a normal entity class with two bidirectional one-to-many associations.
In an MVC application, how can we ensure that all proxies and lazy collections will be initialized when the view tries to access them?
One possible approach is to leave the session open (and transaction uncommitted) when forwarding to the view. The session/transaction would be closed/committed after the view is rendered in, for example, a Servlet filter (another example would by to use the ModelLifetime.discard() callback in Maverick). One difficulty with this approach is making sure the session/transaction is closed/rolled back if an exception occurs rendering the view.
Another approach is to simply force initialization of all needed objects using Hibernate.initialize(). This is often more straightforward than it sounds.

14. How can I bind a dynamic list of values into an in query expression?

Query q = s.createQuery("from foo in class Foo where foo.id in (:id_list)");
q.setParameterList("id_list", fooIdList);
List foos = q.list();

15. How can I bind properties of a JavaBean to named query parameters?

Query q = s.createQuery("from foo in class Foo where foo.name=:name and foo.size=:size");
q.setProperties(fooBean); // fooBean has getName() and getSize()
List foos = q.list();

16. Can I map an inner class?

You may persist any static inner class. You should specify the class name using the standard form i.e. eg.Foo$Bar

17. How can I assign a default value to a property when the database column is null?

Use a UserType.

18. How can I truncate String data?

Use a UserType.

19. How can I trim spaces from String data persisted to a CHAR column?

Use a UserType.

20. How can I convert the type of a property to/from the database column type?

Use a UserType.

21. How can I get access to O/R mapping information such as table and column names at runtime?

This information is available via the Configuration object. For example, entity mappings may be obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory.

22. How can I create an association to an entity without fetching that entity from the database (if I know the identifier)?

If the entity is proxyable (lazy="true"), simply use load(). The following code does not result in any SELECT statement:
Item itemProxy = (Item) session.load(Item.class, itemId);
Bid bid = new Bid(user, amount, itemProxy);
session.save(bid);

23. How can I retrieve the identifier of an associated object, without fetching the association?

Just do it. The following code does not result in any SELECT statement, even if the item association is lazy.
Long itemId = bid.getItem().getId();
This works if getItem() returns a proxy and if you mapped the identifier property with regular accessor methods. If you enabled direct field access for the id of an Item, the Item proxy will be initialized if you call getId(). This method is then treated like any other business method of the proxy, initialization is required if it is called.

24. How can I manipulate mappings at runtime?

You can access (and modify) the Hibernate metamodel via the Configuration object, using getClassMapping(), getCollectionMapping(), etc.
Note that the SessionFactory is immutable and does not retain any reference to the Configuration instance, so you must re-build it if you wish to activate the modified mappings.

25. How can I avoid n+1 SQL SELECT queries when running a Hibernate query?

Follow the best practices guide! Ensure that all and mappings specify lazy="true" in Hibernate2 (this is the new default in Hibernate3). Use HQL LEFT JOIN FETCH to specify which associations you need to be retrieved in the initial SQL SELECT.
A second way to avoid the n+1 selects problem is to use fetch="subselect" in Hibernate3.
If you are still unsure, refer to the Hibernate documentation and Hibernate in Action.
I have a collection with second-level cache enabled, and Hibernate retrieves the collection elements one at a time with a SQL query per element!
Enable second-level cache for the associated entity class. Don't cache collections of uncached entity types.

26. How can I insert XML data into Oracle using the xmltype() function?

Specify custom SQL INSERT (and UPDATE) statements using and in Hibernate3, or using a custom persister in Hibernate 2.1.
You will also need to write a UserType to perform binding to/from the PreparedStatement.

27. How can I execute arbitrary SQL using Hibernate?

PreparedStatement ps = session.connection().prepareStatement(sqlString);
Or, if you wish to retrieve managed entity objects, use session.createSQLQuery().
Or, in Hibernate3, override generated SQL using , , and in the mapping document.
I want to call an SQL function from HQL, but the HQL parser does not recognize it!
Subclass your Dialect, and call registerFunction() from the constructor.

28. Why to use HQL?
• Full support for relational operations: HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns.
• Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is easy to use. This eliminates the need of creating the object and populate the data from result set.
• Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any.
• Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the applications.
• Support for Advance features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.
• Database independent: Queries written in HQL are database independent (If database supports the underlying feature).

JSP Interview Questions

1. What is JSP?
JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web applications in a portable, secure and well-defined way. The JSP Technology allows us to use HTML, Java, JavaScript and XML in a single file to create high quality and fully functionaly User Interface components for Web Applications.


2. What do you understand by JSP Actions?

JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.

There are six JSP Actions:

< jsp : include / >

< jsp : forward / >

< jsp : plugin / >

< jsp : usebean / >

< jsp : setProperty / >

< jsp : getProperty / >


3. What is the difference between < jsp : include page = ... > and < % @ include file = ... >?

Both the tags include information from one JSP page in another. The differences are:

< jsp : include page = ... >

This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful while modularizing a web application. If the included file changes then the new content will be included in the output automatically.

< % @ include file = ... >

In this case the content of the included file is textually embedded in the page that have < % @ include file=".."> directive. In this case when the included file changes, the changed content will not get included automatically in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.

4. What is the difference between < jsp : forward page = ... > and response.sendRedirect(url)?

The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.

sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect also kills the session variables.


5. Name one advantage of JSP over Servlets?

Can contain HTML, JavaScript, XML and Java Code whereas Servlets can contain only Java Code, making JSPs more flexible and powerful than Servlets.

However, Servlets have their own place in a J2EE application and cannot be ignored altogether. They have their strengths too which cannot be overseen.

6. What are implicit Objects available to the JSP Page?

Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:

application
config
exception
out
page
pageContext
request
response and
session

7. What are all the different scope values for the < jsp : useBean > tag?

< jsp : useBean > tag is used to use any java object in the jsp page. Here are the scope values for < jsp : useBean > tag:

a) page
b) request
c) session and
d) application


8. What is JSP Output Comments?

JSP Output Comments are the comments that can be viewed in the HTML 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.

16. Can you extend JSP technology?

Yes. JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions & tag libraries can be developed to enhance/extend its features.

17. What do you understand by JSP translation?

JSP translation is an action that refers to the convertion of the JSP Page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality.

18. How can you prevent the Browser from Caching data of the Pages you visit?

By setting properties that prevent caching in your JSP Page. They are:
<% response.setHeader("pragma","no-cache");//HTTP 1.1 response.setHeader("Cache-Control","no-cache"); response.setHeader("Cache-Control","no-store"); response.addDateHeader("Expires", -1); response.setDateHeader("max-age", 0); //response.setIntHeader ("Expires", -1); //prevents caching at the proxy server response.addHeader("cache-Control", "private"); %>

19. How will you handle the runtime exception in your jsp page?

The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page. You can define the error page to which you want the request forwarded to, in case of an exception, in each JSP Page. Also, there should be another JSP that plays the role of the error page which has the flag isErrorPage set to True.

20. What is JavaServer Pages Standard Tag Library (JSTL) ?

A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and functions.


21. What is JSP container ?

A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.

22. What is JSP custom action ?

A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP page by a taglib directive. Custom actions are used to encapsulate recurring tasks in writing JSP pages.

23. What is JSP custom tag ?

A tag that references a JSP custom action.

24. What is JSP declaration ?

A JSP scripting element that declares methods, variables, or both in a JSP page.

25. What is JSP directive ?

A JSP element that gives an instruction to the JSP container and is interpreted at translation time.

26. What is JSP document ?

A JSP page written in XML syntax and subject to the constraints of XML documents.

27. What is JSP element ?

A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or a scripting element.


28. What is JSP expression ?

A scripting element that contains a valid scripting language expression that is evaluated, converted to a String, and placed into the implicit out object.


29. What is JSP expression language ?

A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression.


30. What is JSP page ?

A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is translated into and handles requests as a servlet.


31. What is JSP scripting element ?

A JSP declaration, scriptlet, or expression whose syntax is defined by the JSP specification and whose content is written according to the scripting language used in the JSP page. The JSP specification describes the syntax and semantics for the case where the language page attribute is "java".


32. What is JSP scriptlet ?

A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is "java".

33. What is JSP tag file ?

A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet.

34. What is JSP tag handler ?

A Java programming language object that implements the behavior of a custom tag.
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on JSPs that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list.