Java Interview Questions -25

Java Interview Questions -25

1. What’s the usage of Configuration Interface in hibernate?

Configuration interface of hibernate framework is used to configure hibernate. It’s also used to bootstrap hibernate. Mapping documents of hibernate are located using this interface.

2. How can we use new custom interfaces to enhance functionality of built-in interfaces of hibernate?
We can use extension interfaces in order to add any required functionality which isn’t supported by built-in interfaces.

3. Should all the mapping files of hibernate have .hbm.xml extension to work properly?

No, having .hbm.xml extension is a convention and not a requirement for hibernate mapping file names. We can have any extension for these mapping files.

4. What are POJOs and what’s their significance?

POJOs( Plain Old Java Objects) are java beans with proper getter and setter methods for each and every properties.
Use of POJOs instead of simple java classes results in an efficient and well constructed code.

5. What’s HQL?

HQL is the query language used in Hibernate which is an extension of SQL. HQL is very efficient, simple and flexible query language to do various type of operations on relational database without writing complex database queries.

6. What is criteria API?

Criteria is a simple yet powerful API of hibernate which is used to retrieve entities through criteria object composition.

7. What are the benefits of using Hibernate template?

Following are some key benefits of using Hibernate template:
a. Session closing is automated.
b. Interaction with hibernate session is simplified.
c. Exception handling is automated.

8. What’s Hibernate?

Hibernate is a popular framework of Java which allows an efficient Object Relational mapping using configuration files in XML format. After java objects mapping to database tables, database is used and handled using Java objects without writing complex database queries.

9. What is ORM?

ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework which maps database tables with Java Objects and then provides various API’s to perform different types of operations on the data tables.

10. How can we see hibernate generated SQL on console?

We need to add following in hibernate configuration file to enable viewing SQL on the console for debugging purposes:

1<property name="show_sql">true</property>

11. What are the two types of collections in hibernate?

Following are the two types of collections in hibernate:
a. Sorted Collection
b. Order Collection

12. What’s the difference between and session.saveOrUpdate() methods in hibernate?

Sessionsave() method saves a record only if it’s unique with respect to its primary key and will fail to insert if primary key already exists in the table.
saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.

13. What the benefits are of hibernate over JDBC?

a. Hibernate can be used seamlessly with any type of database as its database independent while in case of JDBC, developer has to write database specific queries.
b. Using hibernate, developer doesn’t need to be an expert of writing complex queries as HQL simplifies query writing process while in case of JDBC, its job of developer to write and tune queries.
c. In case of hibernate, there is no need to create connection pools as hibernate does all connection handling automatically while in case of JDBC, connection pools need to be created.

14. How can we get hibernate statistics?

We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below:

15. What is transient instance state in Hibernate?

If an instance is not associated with any persistent context and also, it has never been associated with any persistent context, then it’s said to be in transient state.

16. How can we reduce database write action times in Hibernate?

Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.

17. What’s the usage of callback interfaces in hibernate?

Callback interfaces of hibernate are useful in receiving event notifications from objects. For example, when an object is loaded or deleted, an event is generated and notification is sent using callback interfaces.

18. When an instance goes in detached state in hibernate?

When an instance was earlier associated with some persistent context (e.g. a table) and is no longer associated, it’s called to be in detached state.

19. What the four ORM levels are in hibernate?

Following are the four ORM levels in hibernate:
a. Pure Relational
b. Light Object Mapping
c. Medium Object Mapping
d. Full Object Mapping

20. What the two methods are of hibernate configuration?

We can use any of the following two methods of hibernate configuration:
a. XML based configuration ( using hibernate.cfg.xml file)
b. Programmatic configuration ( Using code logic)

21. What is the default cache service of hibernate?

Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and TreeCache and default cache service of hibernate is EHCache.

22. What are the two mapping associations used in hibernate?

In hibernate; we have following two types of mapping associations between entities:
a. One-to-One Association
b. Many-to-Many Association

23. What’s the usage of Hibernate QBC API?

Hibernate Query By Criteria (QBC) API is used to create queries by manipulation of criteria objects at runtime.

24. In how many ways, objects can be fetched from database in hibernate?

Hibernate provides following four ways to fetch objects from database:
a. Using HQL
b. Using identifier
c. Using Criteria API
d. Using Standard SQL

25. How can we reattach any detached objects in Hibernate?

Objects which have been detached and are no longer associated with any persistent entities can be reattached by calling session.merge() method of session class.

26. What are different ways to disable hibernate second level cache?

Hibernate second level cache can be disabled using any of the following ways:
a. By setting use_second_level_cache as false.
c. Using cache provider as org.hibernate.cache.NoCacheProvider

27. What is ORM metadata?

All the mapping between classes and tables, properties and columns, Java types and SQL types etc is defined in ORM metadata.

28. Which one is the default transaction factory in hibernate?

With hibernate 3.2, default transaction factory is JDBCTransactionFactory.

29. What’s the role of JMX in hibernate?

Java Applications and components are managed in hibernate by a standard API called JMX API. JMX provides tools for development of efficient and robust distributed, web based solutions.

30. How can we bind hibernate session factory to JNDI ?

Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file.

31. In how many ways objects can be identified in Hibernate?

Object identification can be done in hibernate in following three ways:
a. Using Object Identity: Using == operator.
b. Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent same row.

32. What different fetching strategies are of hibernate?

Following fetching strategies are available in hibernate:
1. Join Fetching
2. Batch Fetching
3. Select Fetching
4. Sub-select Fetching

33. What are derived properties in hibernate?

Derived properties are those properties which are not mapped to any columns of a database table. Such properties are calculated at runtime by evaluation of any expressions.

34. What’s the difference between load() and get() method in hibernate?

Load() methods results in an exception if the required records isn’t found in the database while get() method returns null when records against the id isn’t found in the database.
So, ideally we should use Load() method only when we are sure about existence of records against an id.

35. Does hibernate support polymorphism?

Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism associations are supported in all mapping strategies of hibernate.

36.What are considered as a web component?

Java Servlet and Java Server Pages technology components are web components. Servlets are Java programming language that dynamically receive requests and make responses. JSP pages execute as servlets but allow a more natural approach to creating static content.

37.What is JSF?

JavaServer Faces (JSF) is a user interface (UI) designing framework for Java web applications. JSF provide a set of reusable UI components, standard for web applications.JSF is based on MVC design pattern. It automatically saves the form data to server and populates the form date when display at client side.

38. Define Hash table

HashTable is just like Hash Map,Collection having key(Unique),value pairs. Hashtable is a collection Synchronozed object .It does not allow duplicate values but it allows null values.

39.What is Hibernate?

Hibernate is a open source object-relational mapping and query service. In hibernate we can write HQL instead of SQL which save developers to spend more time on writing the native SQL. Hibernate has more powerful association, inheritance, polymorphism, composition, and collections. It is a beautiful approach for persisting into database using the java objects. Hibernate also allows you to express queries using java-based criteria .

40. What is the limitation of hibernate?

Slower in executing the queries than queries are used directly.
Only query language support for composite keys.
No shared references to value types.

41. What are the advantage of hibernate.

Hibernate is portable i mean database independent, Vendor independence.
Standard ORM also supports JPA
Mapping of Domain object to relational database.
Hibernate is better then plain JDBC.
JPA provider in JPA based applications.

42.What is ORM?

ORM stands for Object-Relational mapping. The objects in a Java class which is mapped in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

43.Difference between save and saveorupdate

save() – This method in hibernate is used to stores an object into the database. It insert an entry if the record doesn’t exist, otherwise  not.
saveorupdate () -This method in the hibernate is used for updating the object using identifier. If the identifier is missing this method calls save(). If the identifier exists, it will call update method.

44.Difference between load and get method?

load() can’t find the object from cache or database, an exception is thrown and the load() method never returns null.
get() method returns null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance get() never returns a proxy.

45. What are the benefits of ORM?

Vendor independence

46.What the Core interfaces are of hibernate framework?

Session Interface
SessionFactory Interface
Configuration Interface
Transaction Interface
Query and Criteria Interface

47. What is the file extension you use for hibernate mapping file?

The name of the file should be like this : filename.hbm.xml

48.What is J2EE?

J2EE means Java 2 Enterprise Edition. The functionality of J2EE is developing multitier web-based applications .The J2EE platform is consists of a set of services, application programming interfaces (APIs), and protocols.

49.What are the four components of J2EE application?

Application clients components.
Servlet and JSP technology are web components.
Business components (JavaBeans).
Resource adapter components

50.What are types of J2EE clients?

Application clients
Java Web Start-enabled clients, by Java Web Start technology.
Wireless clients, based on MIDP technology.

51.What is the file name of hibernate configuration file?

The name of the file should be like this : hibernate.cfg.xml

52.How hibernate is database independent explain?

Only changing the property
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property> and
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
full database can be replaced.

53.How to add hibernate mapping file in hibernate configuration file?

By <mapping resource=” filename.hbm.xml”/>

54.Define connection pooling?

Connection pooling is a mechanism reuse the connection.which contains the number of already created object connection. So whenever there is a necessary for object, this mechanism is used to directly get objects without creating it.

55.What is the hibernate proxy?

An object proxy is just a way to avoid retrieving an object until you need it. Hibernate 2 does not proxy objects by default.

56.What is HQL?

HQL stands for Hibernate Query Language. Hibernate allows to the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.

57.What are the Collection types in Hibernate ?

Set, List, Array, Map, Bag

58.What is a thin client?

A thin client is a program interface to the application that does not have any operations like query of databases, execute complex business rules, or connect to legacy applications.

59.Differentiate between .ear,  .jar and .war files.

.jar files: These files are with the .jar extenstion. The .jar files contains the libraries, resources and accessories files like property files.
.war files: These files are with the .war extension. The .war file contains jsp, html, javascript and other files for necessary for the development of web applications.
.ear files: The .ear file contains the EJB modules of the application.

60. What are the JSP tag?

In JSP tags can be divided into 4 different types.

61.How to access web.xml init parameters from jsp page?

For example, if you have:
<context-param> <param-name>Id</param-name> <param-value>this is the value</param-value></context-param>
You can access this parameter
Id: <h:outputText value=”#{initParam['Id']}”/>

62.What are JSP Directives? Directives <%@page language=”java” %>
2. include Directives: <%@ include file=”/header.jsp” %>
3. taglib Directives <%@ taglib uri=”tlds/taglib.tld” prefix=”html” %>

63.What is the EAR file?

An EAR file is a JAR file with an .ear extension. A J2EE application with all of its modules is delivered in EAR file.

64.What is Struts?

Struts framework is a Model-View-Controller(MVC) architecture for designing large scale applications. Which is combines of Java Servlets, JSP, Custom tags, and message. Struts helps you to create an extensible development environment for your application, based on published standards and proven design patterns. Model in many applications represent the internal state of the system as a set of one or more JavaBeans.The View is most often constructed using JavaServer Pages (JSP) technology.The Controller is focused on receiving requests from the client and producing the next phase of the user interface to an appropriate View component. The primary component of the Controller in the framework is a servlet of class ActionServlet. This servlet is configured by defining a set of ActionMappings.

65.What is ActionErrors?

ActionErrors object that encapsulates any validation errors that have been found. If no errors are found, return null or an ActionErrors object with no recorded error messages.The default implementation attempts to forward to the HTTP version of this method. Holding request parameters  mapping and request  and returns set of validation errors, if validation failed; an empty set or null

66.What is ActionForm?

ActionForm is a Java bean that associates one or more ActionMappings. A java bean become FormBean when extend org.apache.struts.action.ActionForm class. ActionForm object is automatically populated on the server side which data has been entered by the client from UI. ActionForm maintains the session state for web application.

67.What is action mapping??

In action mapping we specify action class for particular url ie path and diffrent target view ie forwards on to which request response will be forwarded.The ActionMapping represents the information that the ActionServlet knows about the mapping of a particular request to an instance of a particular Action class.The mapping is passed to the execute() method of the Action class, enabling access to this information directly.

68.What is the MVC on struts.

MVC stands Model-View-Controller.
Model: Model in many applications represent the internal state of the system as a set of one or more JavaBeans.
View: The View is most often constructed using JavaServer Pages (JSP) technology.
Controller: The Controller is focused on receiving requests from the client and producing the next phase of the user interface to an appropriate View component. The primary component of the Controller in the framework is a servlet of class ActionServlet. This servlet is configured by defining a set of ActionMappings.

69.What are different modules in spring?

There are seven core modules in spring
The Core container module
O/R mapping module (Object/Relational)
DAO module
Application context module
Aspect Oriented Programming
Web module
MVC module

70.What is Spring?

Spring is a light weight open source framework  for the development of enterprise application that resolves the complexity of enterprise application development also providing a cohesive framework for J2EE application development. Which is primarily based on IOC (inversion of control) or DI (dependency injection) design pattern.

71.Functionality of ActionServlet and RequestProcessor?

Receiving the HttpServletRequest
Populating JavaBean from the request parameters
Displaying response on the web page Issues
Content type issues handling
Provide extension points.

72.What is the file name of hibernate configuration file?

The name of the file should be like this : hibernate.cfg.xml

73.What the three inheritance models are of hibernate?

Hibernate has following three inheritance models:
a. Tables Per Concrete Class
b. Table per class hierarchy
c. Table per sub-class

74. What’s the use of version property in hibernate?

Version property is used in hibernate to know whether an object is in transient state or in detached state.

75. What is attribute oriented programming?

In Attribute oriented programming, a developer can add Meta data (attributes) in the java source code to add more significance in the code. For Java (hibernate), attribute oriented programming is enabled by an engine called XDoclet.

76. What’s the use of session.lock() in hibernate?

session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.

77. How can we map the classes as immutable?

If we don’t want an application to update or delete objects of a class in hibernate, we can make the class as immutable by setting mutable=false

78. What’s general hibernate flow using RDBMS?

General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.

79. What is Light Object Mapping?

Light Object Mapping is one of the levels of ORM quality in which all entities are represented as classes and they are mapped manually.

80.What’s difference between managed associations and hibernate associations?

Managed associations relate to container management persistence and are bi-directional while hibernate associations are unidirectional.

81.What is default scope in Spring?


82. What are advantages of Spring usage?

Pojo based programming enables reuse component.
Improve productivity and subsequently reduce development cost.
Dependency Injection can be used to improve testability.
Spring required enterprise services without a need of expensive application server.
It reduces coupling in code and improves maintainability.

83.What are the Benefits  Spring Framework ?

Light weight container
Spring can effectively organize your middle tier objects
Initialization of properties is easy ? no need to read from properties file
application code is much easier to unit test
Objects are created Lazily , Singleton – configuration
Spring’s configuration management services can be used in any architectural layer, in whatever runtime environment

84.How to Create Object without using the keyword “new” in java?

Without new the Factory mehtods are used to create objects for a class. For example
Calender c=Calender.getInstance();
here Calender is a class and the method getInstance() is a Factory method which can create object for Calender class.

85. What is servlet?

Servlets is a server side components that provide a powerful mechanism for developing server side programs. Servlets is a server as well as platform-independent and Servlets are designed for a various protocols. Most commonly used HTTP protocols. Servlets uses the classes in the java packages javax.servlet, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.http.HttpSession;. All servlets must implement the Servlet interface, which defines life-cycle methods.

86.Servlet is pure java object or not?

Yes, pure java object.

87.What are the phases of the servlet life cycle?

The life cycle of a servlet consists of the following phases:
1.Servlet class loading
2.Servlet instantiation
3.the init method
4.Request handling (call the service method)
5.Removal from service (call the destroy method)

88.What must be implemented by all Servlets?

The Servlet Interface must be implemented by all servlets.

89.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Ã¥¹¼reated 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();

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

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

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

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

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

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

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

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

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

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

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

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

Both are same and there is no difference between them.

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

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

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

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

102.What are the two scope types for formbeans?

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

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

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

104.When should we use SwtichAction?

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

105. What are the benefits of Struts framework?

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

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

Following Steps are required for Struts1 to Struts2 migration:
Move Struts1 actionForm to Struts2 POJO.Convert Struts1 configuration file (struts-config.xml) to Struts2 configuration file (struts.xml)

107. How properties of a form are validated in Struts?

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

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

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

109.What are disadvantages of Struts?

Although Struts have large number of advantages associated, it also requires bigger learning curve and also reduces transparency in the development process.
Struts also lack proper documentation and for many of its components, users are unable to get proper online resources for help.

110.What’s the use of file in Struts Validation framework? file is used to define specific error messages in key value pairs for any possible errors that may occur in the code.
This approach helps to keep the code clean as developer doesn’t need to embed all error messages inside code.

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

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

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

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

Also Read:



Post a Comment