Java Faqs(Spring,struts)

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

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

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

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

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

6. What are features of Spring ?
• Lightweight:
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.
• Container:
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
7. 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.
8. 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.
9. 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.
10. 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.

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




12. What are the common implementations of the Application Context ?
The three commonly used implementation of 'Application Context' are
• ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code .
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
• FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code .
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
• XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

13. How is a typical spring implementation look like ?
For a typical Spring Application we need the following files:
• An interface that defines the functions.
• An Implementation that contains properties, its setter and getter methods, functions etc.,
• Spring AOP (Aspect Oriented Programming)
• A XML file called Spring configuration file.
• Client program that uses the function.
14. What is the typical Bean life cycle in Spring Bean Factory Container ?
Bean life cycle in Spring Bean Factory Container is as follows:
 The spring container finds the bean’s definition from the XML file and instantiates the bean.
 Using the dependency injection, spring populates all of the properties as specified in the bean definition
 If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
 If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
 If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
 If an init-method is specified for the bean, it will be called.
 Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
Q) What do you mean by Bean wiring ?
A) The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring.

Q) What do you mean by Auto Wiring?
A) 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.
1. no 2. byName 3. byType 4. constructor 5. autodirect

21. 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 a getWebApplicationContext() method.
22. What are ORM’s Spring supports ?
Spring supports the following ORM’s :
• Hibernate , iBatis , JPA (Java Persistence API)
• TopLink , JDO (Java Data Objects) ,OJB
23. 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
24. How to integrate Spring and Hibernate using HibernateDaoSupport?
Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps.
• Configure the Hibernate SessionFactory
• Extend your DAO Implementation from HibernateDaoSupport
• Wire in Transaction Support with AOP







25. What are Bean scopes in Spring Framework ?
The Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext). The scopes supported are listed below:
Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.



26. What is AOP?
Aspect-oriented programming, or AOP, is a programming technique that allows programmers 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.

27. How the AOP used in Spring?
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.

28. What do you mean by Aspect ?
A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).

29. What do you mean by JointPoint?
A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

30. What do you mean by Advice?
Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point.

31. What are the types of Advice?
Types of advice:
• Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
• After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
• After throwing advice: Advice to be executed if a method exits by throwing an exception.
• After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
• Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception
32. What are the types of the transaction management Spring supports ?
Spring Framework supports:
• Programmatic transaction management.
• Declarative transaction management.

33. What are the benefits of the Spring Framework transaction management ?
The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:
• Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
• Supports declarative transaction management.
• Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
• Integrates very well with Spring's various data access abstractions.

34. Why most users of the Spring Framework choose declarative transaction management ?
Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container.

35. Explain the similarities and differences between EJB CMT and the Spring Framework's declarative transaction management ?
The basic approach is similar: it is possible to specify transaction behavior (or lack of it) down to individual method level. It is
possible to make a setRollbackOnly() call within a transaction context if necessary. The differences are:
• Unlike EJB CMT, which is tied to JTA, the Spring Framework's declarative transaction management works in any environment. It can work with JDBC, JDO, Hibernate or other transactions under the covers, with configuration changes only.
• The Spring Framework enables declarative transaction management to be applied to any class, not merely special classes such as EJBs.
• The Spring Framework offers declarative rollback rules: this is a feature with no EJB equivalent. Both programmatic and declarative support for rollback rules is provided.
• The Spring Framework gives you an opportunity to customize transactional behavior, using AOP. With EJB CMT, you have no way to influence the container's transaction management other than setRollbackOnly().
• The Spring Framework does not support propagation of transaction contexts across remote calls, as do high-end application servers.

37. When to use programmatic and declarative transaction management ?
Programmatic transaction management is usually a good idea only if you have a small number of transactional operations.
On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure.

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

39. What are the exceptions thrown by the Spring DAO classes ?
Spring DAO classes throw exceptions which are subclasses of DataAccessException(org.springframework.dao.DataAccessException).Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception. These exceptions wrap the original exception.

40. 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.
41. What is Spring's JdbcTemplate ?
Spring's JdbcTemplate is central class to interact with a database through JDBC. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.
JdbcTemplate template = new JdbcTemplate(myDataSource);

42. What is PreparedStatementCreator ?
PreparedStatementCreator:
• Is one of the most common used interfaces for writing data to database.
• Has one method – createPreparedStatement(Connection)
• Responsible for creating a PreparedStatement.
• Does not need to handle SQLExceptions.
43. What is SQLProvider ?
SQLProvider:
• Has one method – getSql()
• Typically implemented by PreparedStatementCreator implementers.
• Useful for debugging.

44. What is RowCallbackHandler ?
The RowCallbackHandler interface extracts values from each row of a ResultSet.
• Has one method – processRow(ResultSet)
• Called for each row in ResultSet.
• Typically stateful.



45. What are the differences between EJB and Spring ?
Spring and EJB feature comparison.
Feature EJB Spring
Transaction management • Must use a JTA transaction manager.
• Supports transactions that span remote method calls. • Supports multiple transaction environments through its PlatformTransactionManager interface, including JTA, Hibernate, JDO, and JDBC.
• Does not natively support distributed transactions—it must be used with a JTA transaction manager.
Declarative transaction support • Can define transactions declaratively through the deployment descriptor.
• Can define transaction behavior per method or per class by using the wildcard character *.
• Cannot declaratively define rollback behavior—this must be done programmatically. • Can define transactions declaratively through the Spring configuration file or through class metadata.
• Can define which methods to apply transaction behavior explicitly or by using regular expressions.
• Can declaratively define rollback behavior per method and per exception type.
Persistence Supports programmatic bean-managed persistence and declarative container managed persistence. Provides a framework for integrating with several persistence technologies, including JDBC, Hibernate, JDO, and iBATIS.
Declarative security • Supports declarative security through users and roles. The management and implementation of users and roles is container specific.
• Declarative security is configured in the deployment descriptor. • No security implementation out-of-the box.
• Acegi, an open source security framework built on top of Spring, provides declarative security through the Spring configuration file or class metadata.
Distributed computing Provides container-managed remote method calls. Provides proxying for remote calls via RMI, JAX-RPC, and web services.


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.
• Service to Worker
• Dispatcher View
• Composite View (Struts Tiles)
• Front Controller
• View Helper
• Synchronizer Token

16.Can we have more than one struts-config.xml file for a single Struts application?
Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as follows:


action

org.apache.struts.action.ActionServlet


config/WEB-INF/struts-config.xml,
/WEB-INF/struts-admin.xml,
/WEB-INF/struts-config-forms.xml

.....

What are the different kinds of actions in Struts?
The different kinds of actions in Struts are:
• ForwardAction
• IncludeAction
• DispatchAction
• LookupDispatchAction
• SwitchAction
21.What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

22.How to use DispatchAction?
To use the DispatchAction, follow these steps :
• Create a class that extends DispatchAction (instead of Action)
• In a new class, add a method for every function you need to perform on the service – The method has the same signature as the execute() method of an Action class.
• Do not override execute() method – Because DispatchAction class itself provides execute() method.
• Add an entry to struts-config.xml

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



24.What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.

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

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

30.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.
31. What is DynaActionForm?
A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean.
What is the use of ?
repeats the nested body content of this tag over a specified collection.

36.What are differences between and
: 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.

: is used to retrieve and print the value of the bean property. has no body.


37.How the exceptions are handled in struts?
Exceptions in Struts are handled in two ways:
• Programmatic exception handling :
Explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of variable) needed when error occurs.
• Declarative exception handling :You can either define 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.



or

38.What is difference between ActionForm and DynaActionForm?
• An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml
• The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.
• The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
• ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.
• ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).
• DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

39.How can we make message resources definitions file available to the Struts framework environment?
We can make message resources definitions file (properties file) available to Struts framework environment by adding this file to struts-config.xml.

40.What is the life cycle of ActionForm?
The lifecycle of ActionForm invoked by the RequestProcessor is as follows:
• Retrieve or Create Form Bean associated with Action
• "Store" FormBean in appropriate scope (request or session)
• Reset the properties of the FormBean
• Populate the properties of the FormBean
• Validate the properties of the FormBean
• Pass FormBean to Action

1.What is ORM ?
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

2.What does ORM consists of ?
An ORM solution consists of the followig four pieces:
• API for performing basic CRUD operations
• API to express queries refering to classes
• Facilities to specify metadata
• Optimization facilities : dirty checking,lazy associations fetching
3.What are the ORM levels ?
The ORM levels are:
• Pure relational (stored procedure.)
• Light objects mapping (JDBC)
• Medium object mapping
• Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)
4.What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

5.Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
• Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
• Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
• Improved maintainability
o A lot less code to write
• Improved portability
o ORM framework generates database-specific SQL for you
6.What Does Hibernate Simplify?
Hibernate simplifies:
• Saving and retrieving your domain objects
• Making database column and table name changes
• Centralizing pre save and post retrieve logic
• Complex joins for retrieving related items
• Schema creation from object model

7.What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:


8.What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
• Programmatic configuration
• XML configuration (hibernate.cfg.xml)
9.What are the important tags of hibernate.cfg.xml?
Following are the important tags of hibernate.cfg.xml:




10.What are the Core interfaces are of Hibernate framework?
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.
• Session interface
• SessionFactory interface
• Configuration interface
• Transaction interface
• Query and Criteria interfaces

11.What role does the Session interface play in Hibernate?
The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();
Session interface role:
• Wraps a JDBC connection
• Factory for Transaction
• Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate?
The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();

13.What is the general flow of Hibernate communication with RDBMS?
The general flow of Hibernate communication with RDBMS is :
• Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
• Create session factory from configuration object
• Get one session from this session factory
• Create HQL Query
• Execute query to get list containing Java objects

14.What is Hibernate Query Language (HQL)?
Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

15.How do you map Java Objects with Database tables?
• First we need to write Java domain objects (beans with setter and getter).
• Write hbm.xml, where we map java class to table and database columns to Java class variables.
Example :








16.What’s the difference between load() and get()?
load() get()
Only use the load() method if you are sure that the object exists. If you are not sure that the object exists, then use one of the get() methods.
load() method will throw an exception if the unique id is not found in the database. get() method will return null if the unique id is not found in the database.
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. get() will hit the database immediately.


17.What is the difference between and merge and update ?
Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

18.How do you define sequence generated primary key in hibernate?
Using tag.
Example:-


SEQUENCE_NAME


19.Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

20.What do you mean by Named – SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:


SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name


Invoke Named Query :
List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();

21.How do you invoke Stored Procedures?






{ ? = call selectAllEmployees() }



22.Explain Criteria API
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") ) .add(Restrictions.like("address", "Boston")) .addOrder(Order.asc("name") ) .list();
23.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.

24.What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
• HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
• Common functions are simplified to single method calls.
• Sessions are automatically closed.
• Exceptions are automatically caught and converted to runtime exceptions.

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

26.If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
true


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

Example:

29.What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :-
sorted collection order collection
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is not large, it will be more efficient way to sort it. If your collection is very large, it will be more efficient way to sort it .
31.What is the advantage of Hibernate over jdbc?
Hibernate Vs. JDBC :-
JDBC Hibernate
With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
With JDBC, caching is maintained by hand-coding. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.
In JDBC there is no check that always every user has updated data. This check has to be added by the developer. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.



32.What are the Collection types in Hibernate ?
1. Bag
2. Set
3. List
4. Array
5. Map

33.What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
1. An implicit association join
2. An ordinary join in the FROM clause
3. A fetch join in the FROM clause.
4. A theta-style join in the WHERE clause.

34.Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

35.What is Hibernate proxy?
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

36.How can Hibernate be configured to access an instance variable directly and not through a setter method ?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

37.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
• dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
• dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

38.What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

39.What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

40.What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.

41.What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

42.What are the types of Hibernate instance states ?
Three types of instance states:
• Transient -The instance is not associated with any persistence context
• Persistent -The instance is associated with a persistence context
• Detached -The instance was associated with a persistence context which has been closed – currently not associated

43.How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.
44.What are the differences between EJB 3.0 & Hibernate
Hibernate Vs EJB 3.0 :-
Hibernate EJB 3.0
Session–Cache or collection of loaded objects relating to a single unit of work Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit
XDoclet Annotations used to support Attribute Oriented Programming Java 5.0 Annotations used to support Attribute Oriented Programming
Defines HQL for expressing queries to the database Defines EJB QL for expressing queries
Supports Entity Relationships through mapping files and annotations in JavaDoc Support Entity Relationships through Java 5.0 annotations
Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API Provides and Entity Manager Interface for managing CRUD operations for an Entity
Provides callback support through lifecycle, interceptor, and validatable interfaces Provides callback support through Entity Listener and Callback methods
Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships Entity Relationships are bidirectional or unidirectional


45.What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
• Table per class hierarchy
• Table per subclass
• Table per concrete class

JSP

1.What are the advantages of JSP over Servlet?
JSP is a serverside technology to make content generation a simple appear.The advantage of JSP is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.

2.What is the life-cycle of JSP?
When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class and compiles the class. It is this servlet that services the client requests.
A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:
Translation
Compilation
Loading the class
Instantiating the class
jspInit() invocation
_jspService() invocation
jspDestroy() invocation

3.What is the jspInit() method?
The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.

4.What is the _jspService() method?
The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.

5.What is the jspDestroy() method?
The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.

6.What JSP lifecycle methods can I override?
You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

7.How can I override the jspInit() and jspDestroy() methods within a JSP page?
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:
<%! public void jspInit() { . . . }%>
<%! public void jspDestroy() { . . . }%>

8.What are implicit objects in JSP?
Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects.The implicit objects available in JSP are as follows:
Request , response, pageContext ,session ,application ,out ,config ,page ,exception
The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.

9.What are the different types of JSP tags?
The different types of JSP tags are as follows:



10.What are JSP directives?
JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page
They are used to set global values such as a class declaration, method implementation, output content type, etc.
They do not produce any output to the client.
Directives are always enclosed within <%@ ….. %> tag.
Ex: page directive, include directive, etc.

11.What is page directive?
A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment.
Typically, the page directive is found at the top of almost all of our JSP pages.
There can be any number of page directives within a JSP page (although the attribute – value pair must be unique).
The syntax of the include directive is: <%@ page attribute="value">
Example:<%@ include file="header.jsp" %>

12.What are the attributes of page directive?
There are thirteen attributes defined for a page directive of which the important attributes are as follows:
import: It specifies the packages that are to be imported.
session: It specifies whether a session data is available to the JSP page.
contentType: It allows a user to set the content-type for a page.
IsELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.

13.What is the include directive?
There are thirteen attributes defined for a page directive of which the important attributes are as follows:
The include directive is used to statically insert the contents of a resource into the current JSP.
This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
The syntax of the include directive is as follows:
<%@ include file = "FileName" %>
This directive has only one attribute called file that specifies the name of the file to be included.

14.What are the JSP standard actions?
The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.
They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
Ex: include, forward, useBean,etc. object

15.What are the standard actions available in JSP?
The standard actions available in JSP are as follows:
: It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
: It forwards a response from a servlet or a JSP page to another page.
: It makes a JavaBean available to a page and instantiates the bean.
: It sets the properties for a JavaBean.
: It gets the value of a property from a JavaBean component and adds it to the response.
: It is used in conjunction with ;, ; to add a parameter to a request. These parameters are provided using the name-value pairs.
: It is used to include a Java applet or a JavaBean in the current JSP page.

16.What is the standard action?
The standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified classpath and type.

17.What are the scopes available in ?
The scopes available in are as follows:
page scope:: It specifies that the object will be available for the entire JSP page but not outside the page.
request scope: It specifies that the object will be associated with a particular request and exist as long as the request exists.
application scope: It specifies that the object will be available throughout the entire Web application but not outside the application.
session scope: It specifies that the object will be available throughout the session with a particular client.

18.What is the standard action?
The standard action forwards a response from a servlet or a JSP page to another page.
The execution of the current page is stopped and control is transferred to the forwarded page.
The syntax of the standard action is :

Here, targetPage can be a JSP page, an HTML page, or a servlet within the same context.
If anything is written to the output stream that is not buffered before , an IllegalStateException will be thrown.
Note : Whenever we intend to use or in a page, buffering should be enabled. By default buffer is enabled.

19.What is the standard action?
The standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context.The syntax of the standard action is as follows:

Here, targetPage is the page to be included in the current JSP.20.What is the difference between include directive and include action?
Include directive Include action
The include directive, includes the content of the specified file during the translation phase–when the page is converted to a servlet. The include action, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user.
The include directive is used to statically insert the contents of a resource into the current JSP. The include standard action enables the current JSP page to include a static or a dynamic resource at runtime.
Use the include directive if the file changes rarely. It’s the fastest mechanism. Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.
21.Differentiate between pageContext.include and jsp:include?
The standard action and the pageContext.include() method are both used to include resources at runtime. However, the pageContext.include() method always flushes the output of the current page before including the other components, whereas flushes the output of the current page only if the value of flush is explicitly set to true as follows:


22.What is the jsp:setProperty action?
You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:

...

In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.

A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:

...


Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.

23.What is the jsp:getProperty action?
The action is used to access the properties of a bean that was set using the action. The container converts the property to a String as follows:
If it is an object, it uses the toString() method to convert it to a String.
If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class.
The syntax of the method is:
Here, name is the id of the bean from which the property was set. The property attribute is the property to get. A user must create or locate a bean using the action before using the action.

24.What is the standard action?
The standard action is used with or to pass parameter names and values to the target resource. The syntax of the standard action is as follows:


25.What is the jsp:plugin action ?
This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.

26.What are scripting elements?
JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:
Expressions of the form <%= expression %> that are evaluated and inserted into the output,
Scriptlets of the form <% code %> that are inserted into the servlet's service method,
Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.

27.What is a scriptlet?
A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a servlet, the scriptlet code goes into the service() method. Hence, methods and variables written in scriptlets are local to the service() method. A scriptlet is written between the <% and %> tags and is executed by the container at request processing time.

28.What are JSP declarations?
As the name implies, JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the <%! and %> tags. A declaration is not included in the service() method when a JSP is translated to a servlet.

29.What is a JSP expression?
A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlets. An expression is written between the <%= and %> tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags.

30.How is scripting disabled?
Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows:

*.jsp
true






4 OOPS

1: What are the principle concepts of OOPS?
A : There are four principle concepts upon which object oriented design and programming rest. They are:
Abstraction
Polymorphism
Inheritance
Encapsulation (i.e. easily remembered as A-PIE).
Q2 : What is Abstraction?
Abstraction refers to the act of representing essential features without including the background details or explanations.

Q3 : What is Encapsulation?
A : Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.

Q4 : What is the difference between abstraction and encapsulation?
Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
Abstraction solves the problem in the design side while Encapsulation is the Implementation.
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.

Q5 : What is Inheritance?
A : Inheritance is the process by which objects of one class acquire the properties of objects of another class.
A class that is inherited is called a superclass.
The class that does the inheriting is called a subclass.
Inheritance is done by using the keyword extends.
The two most common reasons to use inheritance are:
To promote code reuse
To use polymorphism

Q6 : What is Polymorphism?
A : Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.

Q7 : How does Java implement polymorphism?
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods). In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).

Q8 : Explain the different forms of Polymorphism.
A : There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism.
Compile time polymorphism is method overloading.
Runtime time polymorphism is done using inheritance and interface.

Q9 : What is Dynamic Binding?
A : Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.

Q10 : What is method overriding?
A : Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.

Q11 : What is super?
A : super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.

Q12: How do you prevent a method from being overridden?
A : To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.
Example : public final void exampleMethod() {
// Method statements }
Q13: What is an Interface?
A : An interface is a description of a set of methods that conforming implementing classes must have.

Q14: Can we instantiate an interface?
A : No, You can’t instantiate an interface directly, but you can instantiate a class that implements an interface.

Q15: Do interfaces have member variables?
A : Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example.
Q16: What modifiers are allowed for methods in an Interface?
A : Only public and abstract modifiers are allowed for methods in interfes.

Q17 : What is a marker interface?
A : Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.

Q18: What is an abstract class?
A : Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.

Q19: Can we instantiate an abstract class?
A : An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

Q20 : What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Q21 : Can I import same package/class twice? Will the JVM load the package twice at runtime?
A: One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same class.

Q22 : How you can force the garbage collection ?
A : Garbage collection automatic process and can't be forced. We can call garbage collector in Java by calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.