Spring Data JPA and Hibernate Interview Questions

In this tutorial series, we will discuss most important concepts which may be asked in interviews.

1.What Is Java Persistence API?

The Java Persistence API provides a specification for persisting, reading, and managing data from your Java object to relational tables in the database.
Mapping Java objects to database tables and vice versa is called Object-relational mapping (ORM) .

JPA is a specification and several implementations are available. Popular implementations are Hibernate, Spring Data JPA , Apache OpenJPA and
Toplink .

2. What is Hibernate Framework?

Hibernate ORM (Hibernate in short) is an object-relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. Hibernate handles object-relational impedance mismatch problems by replacing direct, persistent database accesses with high-level object handling functions.

Hibernate’s primary feature is mapping from Java classes to database tables, and mapping from Java data types to SQL data types. Hibernate also provides data query and retrieval facilities. It generates SQL calls and relieves the developer from the manual handling and object conversion of the result set.

Hibernate provides reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.

3. What are the benefits of using JPA framework in persistence layer?
  • Elimination of boilerplate code which earlier being added for JDBC.
  • These frameworks(Spring Data JPA and Hibernate) can be easily integrated into the applications.
  • Provides support for caching thus improves the performance.
  • It provides support for Native and Named queries so that we can write dynamic and complex queries.
  • Easily configurable using XML or JPA annotations.
  • Provides support for HQL same as SQL which has better performance.
4. What is the difference between SessionFactory and EntityManager ?

EntityManager interface is similar to sessionFactory in hibernate. EntityManager is under javax.persistance package but session and sessionFactory under org.hibernate.Session/sessionFactory package.

Entity manager is JPA specific and session/sessionFactory are hibernate specific.

EntityManager

@PersistenceContext
EntityManager entityManager;

public List<MyEntity> findById() {
  return entityManager
     .createQuery("from MyEntity where apples=7", MyEntity.class)
     .getResultList();
}

SessionFactory

@Autowired
SessionFactory sessionFactory;

public List<MyEntity> findById() {
  Session session = sessionFactory.getCurrentSession();
  List<?> result = session.createQuery("from MyEntity where id=1")
      .list();
  @SuppressWarnings("unchecked")
  List<MyEntity> resultCasted = (List<MyEntity>) result;
  return resultCasted;
}

Also EntityManger looks cleaner and is also easier to test because EntityManager can be easily mocked.

5. What is hibernate configuration file?

Hibernate configuration file contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.

6. What are the annotations used JPA implementation?

@Entity – This marks class as Entity

@Table – This maps class to database table

@Id – Marks the class variable as primary key column in table

@Column – Marks it as a column in table , we can also configure name attribute defining its name in database table

@GeneratedValue – Marking a field with the @GeneratedValue annotation specifies that a value will be automatically generated for that field. This is primarily intended for primary key fields .There are below types of strategies –

GenerationType.AUTO – It is the default generation type and lets the persistence provider choose the generation strategy.

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;

GenerationType.IDENTITY – The GenerationType.IDENTITY is the easiest to use but not the best one from a performance point of view. It relies on an auto-incremented database column and lets the database generate a new value with each insert operation. From a database point of view, this is very efficient because the auto-increment columns are highly optimized, and it doesn’t require any additional statements.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;

GenerationType.SEQUENCE – The GenerationType.SEQUENCE is my preferred way to generate primary key values and uses a database sequence to generate unique values.

If you don’t provide sequence name hibernate will provide its default sequence

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", updatable = false, nullable = false)
private Long id;

You can change that by referencing the name of a @SequenceGenerator in the generator attribute of the @GeneratedValue annotation. The @SequenceGenerator annotation lets you define the name of the generator, the name, and schema of the database sequence and the allocation size of the sequence.

GenerationType.TABLE – The GenerationType.TABLE gets only rarely used nowadays. It simulates a sequence by storing and updating its current value in a database table which requires the use of pessimistic locks which put all transactions into a sequential order. This slows down your application, and you should, therefore, prefer the GenerationType.SEQUENCE, if your database supports sequences, which most popular databases do

If you don’t provide sequence name hibernate will provide its default sequence

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "id", updatable = false, nullable = false)
private Long id;

Summary:

  1. AUTO: Hibernate selects the generation strategy based on the used dialect,
  2. IDENTITY: Hibernate relies on an auto-incremented database column to generate the primary key,
  3. SEQUENCE: Hibernate requests the primary key value from a database sequence,
  4. TABLE: Hibernate uses a database table to simulate a sequence.

package com.anup.springboot.pojo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
@author anup
*/
@Entity
@Table(name = "TODO")
public class Todo implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "TASK_NAME")
private String taskName;
@Column(name = "TASK_DESC")
private String taskDesc;
@Column(name = "STATUS")
private String status;
public Todo() {
super();
}
public Todo(Long id, String taskName, String taskDesc, String status) {
super();
this.id = id;
this.taskName = taskName;
this.taskDesc = taskDesc;
this.status = status;
}
//Setters and Getters
} 

7. Why is it advisable to use single instance of SessionFactory across your application?

There are some key points regarding one SessionFactory Object per application : –

1.Single Data Store : – It is single data store for your whole application. Although you can have multiple SessionFactory but each SessionFactory will have one different database associated with it.SessionFactory is a heavy weight object.

2.Thread Safe : – SessionFactory is thread safe so due to this feature many thread can access the SessionFactory.

3.Immutable : – Once the SessionFactory’s object is created you can not change or set the values of Session Facoty. Its internal state is set at the time of creation.

4.Singleton : – SessionFactory is built at the time of application startup and it follows the singleton design pattern.

Because creation of a SessionFactory is an extremely expensive process which involves parsing hibernate configuration/mapping properties and creating database connection pool .Creating a database connection pool requires establishing database connections (i.e creating Connection objects) which has overhead due to the time taken to locate the DB server , establish a communication channel and exchange information to do authentication.

So if you create a SessionFactory for every request , it implies that you are not using database connection pool to serve your request .You have to setup a new connection by the above overheaded process for every request instead of just getting the opened connection from the database connection pool.

8. What is Session Object in Hibernate and when its used?

We can create the Session object using SessionFactory. We create the session by calling openSession() method on factory object.

Session session = factory.openSession(); 

OR

Session session = factory.getCurrentSession(); 

Using this session object we can perform save,update,delete,get operations on the entities.

9. What is the difference between openSession and getCurrentSession methods?

Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations.

Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don’t need to close it. Once the session factory is closed, this session object gets closed.

10. What are the possible states of entity bean?

Entity bean can have below possible state –

  1. Transient: When ever we create a new object of Entity bean then we can say that is in Transient state,At that time any modification in the object state does not effect on database.
  2. Persistent: When ever the Object of entity bean associated with session we can say that is in persistent state, if any change in the object state , then that modification effects in database.
  3. Detached :When ever the object is removed from session then it enters in to detached state.Any modification on detached state object , does not effect in database.

/**
 * @author anup
 */
@Entity
@Table(name = "TODO")
public class Todo implements Serializable {
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "TASK_NAME")
    private String taskName;
    @Column(name = "TASK_DESC")
    private String taskDesc;
    @Column(name = "STATUS")
    private String status;

    public Todo() {
        super();
    }

    public Todo(Long id, String taskName, String taskDesc, String status) {
        super();
        this.id = id;
        this.taskName = taskName;
        this.taskDesc = taskDesc;
        this.status = status;
    }

    //Setters and Getters
}
class StateTest
{
    public static void main(String[]args)
    {
        SessionnFactory factory=new Configuration().configure("hibewrnate.cfg.xml").buildSessionFactpry();
        Sessiion session1=factory.openSession();
        Todo e1=new Todo(1l, "Wakeup", "Wake up at 7AM", "DONE"); //Entity bean in Transient sate.
        
        Transaction tx1=session1.beginTransaction();
        session1.save(e1); //Entity bean in persistent state
        e1.setTaskName("Running"); //Will effect in db
        tx1.commit();
        session1.close();
        //Now e1 in ditached state
        e1.setStream("Webservices"); //Will not effect in db

    }
}

11. Why do we need to have no-arg constructor entity bean?

The implementation of the default no arg constructor, is not mandatory . Only case where you need to specify it is when you declare another parametrized constructor. In Hibernate, no-arg constructor is used to loading database entities via Reflection .

12. Can you make entity class as final?

You can make an Hibernate Entity class final, but that’s not a good practice.
Generally, persistence providers make proxies of objects using some library like CGLIB or javassist. These proxies are creating runtime subclasses of the entities. That’s why they should not be final.

Since Hibernate uses proxy pattern for performance improvement, so in case of lazy association, by making an entity final, Hibernate will no longer be able to use proxy, because Java doesn’t allow extension of final class, thus limiting your performance improvement options.

13. What is the difference between get() and load() and when to use what ?

If no row with the given identifier value exists in the database, get() returns null. The load() method throws an ObjectNotFoundException. It’s your choice what error-handling you prefer.
More important, the load() method may return a proxy, a placeholder, without hitting the database. The get() method on the other hand never returns a proxy, it always hits the database.

  • Use get() when you want to load an object
  • Use load() when you need to obtain a reference to the object without issuing extra SQL queries, for example, to create a relationship with another object.

 public void savePost(long authorId, String text) {   
Post p = new Post();     
p.setText(text);   
// No SELECT query here. 
// Existence of Author is ensured by foreign key constraint on Post.     p.setAuthor(s.load(Author.class, authorId));     
s.save(p); } 

14. What is the first level cache in hibernate?

Hibernate by default provides first level cache. It caches the database objects i.e. entities to reduce number of queries made to database in a single transaction.

It is associated with Session object .As we create session object on demand from session factory and it is lost, once the session is closed. So first level cache is available till the time that session object is alive. It is available to session object only and is not accessible to any other session object in any other part of application.

Case 1: Below example shows the role of first level cache while retrieving Department object twice –

//Open the hibernate session
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
 
//fetch the department entity from database first time
Department department = (Department) session.load(DepartmentEntity.class, new Integer(1));
System.out.println(department.getName());
 
//fetch the department entity again
department = (Department) session.load(Department.class, new Integer(1));
System.out.println(department.getName());
 
session.getTransaction().commit();
HibernateUtil.shutdown();
 
Output:
 
Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
COMPUTER
COMPUTER

Its quiet clear from the logs that when we get the object second time , its doesn’t hit the database. Object is cached on the first load itself.

Case 2: Below example shows the role of first level cache while retrieving Department object from multiple sessions –

//Open the hibernate session
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

Session sessionDummy = HibernateUtil.getSessionFactory().openSession();
sessionDummy.beginTransaction();
 
//fetch the department entity from database first time
Department department = (Department) session.load(Department.class, new Integer(1));
System.out.println(department.getName());
 
//fetch the department entity again
department = (Department) session.load(Department.class, new Integer(1));
System.out.println(department.getName());
 
//fetch the department entity again
department = (Department) sessionDummy.load(Department.class, new Integer(1));
System.out.println(department.getName());

session.getTransaction().commit();
sessionDummy.getTransaction().commit();
HibernateUtil.shutdown();
 
Output:
 
Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
COMPUTER
COMPUTER
Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
COMPUTER

From the logs its quiet clear that when we load the object second time in single session, its doesn’t hit the database. But when we load the Object in different session, it hits the database again.

Remove Objects from First Level Cache –

Though we can not disable the first level cache in hibernate, but we can certainly remove some of objects from it when needed. This is done using two methods :

  • evict()
  • clear()

Here evict() is used to remove a particular object from cache associated with session, and clear() method is used to remove all cached objects associated with session. 

15. What is the second level cache in hibernate ?

Second level cache works on SesionFactory level. So irrespective of multiple sessions , second level cache will cache the data across all sessions.

This is apart from first level cache which is available to be used globally in session factory scope. Once session factory is closed, all cache associated with it die and cache manager also closed down.

There are multiple implementations of second level cache provided by many vendors like –

  1. EH Cache
  2. OS Cache
  3. Swarm Cache
  4. JBoss Cache

We need to add below dependency in maven –

<dependency>  
    <groupId>net.sf.ehcache</groupId>  
    <artifactId>ehcache</artifactId>  
    <version>2.10.3</version>  
</dependency>  

Also Entity class needs to be annotated with below annotations –

package com.myjavablog;
import javax.persistence.*;  
import org.hibernate.annotations.Cache;  
import org.hibernate.annotations.CacheConcurrencyStrategy;  
@Entity  
@Table(name="TODO")  
@Cacheable  
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)  
public class Todo implements Serializable {
   
}

Hibernate Configuration file hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>    
<!DOCTYPE hibernate-configuration PUBLIC    
          "-//Hibernate/Hibernate Configuration DTD 5.2.0//EN"    
          "http://hibernate.sourceforge.net/hibernate-configuration-5.2.0.dtd">    
    
<hibernate-configuration>    
    
    <session-factory>    
        <property name="show_sql">true</property>    
        <property name="hbm2ddl.auto">update</property>    
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>    
        <property name="connection.username">system</property>    
        <property name="connection.password">jtp</property>    
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>    
         
         <property name="cache.use_second_level_cache">true</property>   
         <property name="cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>  
         <mapping class="com.myjavablog.Todo"/>  
    </session-factory>    
</hibernate-configuration>  

Class to access the entity –

//Open the hibernate session
Session session1 = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

Session session2 = HibernateUtil.getSessionFactory().openSession();
sessionDummy.beginTransaction();
 
//fetch the department entity from database first time
Department department = (Department) session1.load(Department.class, new Integer(1));
System.out.println(department.getName());
 
//fetch the department entity again
department = (Department) session2.load(Department.class, new Integer(1));
System.out.println(department.getName());

session1.getTransaction().commit();
session2.getTransaction().commit();
HibernateUtil.shutdown();
 
Output:
 
Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
COMPUTER
COMPUTER

16. What is the difference between save() and persist() methods ?

Save()

  1. Returns generated Id after saving. Its Serializable return type.
  2. Saves the value to DB immediately and keeps track of the entity until the end of the session(I have tried to change the entity values outside of the transaction, it does not show any effect when session commits)
  3. save the changes to the db outside of the transaction.
  4. Assigns the generated id to the entity you are persisting
  5. Session.save() for a detached object will create a new row in the table.

Persist()

  1. Does not returns generated Id after saving. Its void return type.
  2. Saves the value to DB immediately and keeps track of the entity until the end of the session.(I have tried to change the entity values outside of the transaction, it does not show any effect when session commits)
  3. Does not save the changes to the db outside of the transaction.
  4. Assigns the generated id to the entity you are persisting
  5. session.persist() for a detached object will throw PersistentObjectException as it is not allowed.
17. What is the relationship and how to implement it?

Two entities can have relationship between them . In relational database, two tables are related to by foreign key .This can be implemented in hibernate through below annotations.

18.What is cascading and what are different types of cascading?

Two entities are related to each other via a foreign key relationship.
When we have relationship between entities, then we need to define how the different operations will affect the other entity. In hibernate we use CASCADE operations to handle this.

@Entity
@Table(name = "STUDENT")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column
    private String name;
    @Column
    private int mobile;
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "DEPT_ID")
    private Department department;

Here Many students can be a part of single department . DEPT_ID is foreign key in Student table is associated to ID in Department table.

Commonly used cascading types as defined in CascadeType enum are:

  1. None: No Cascading, it’s not a type but when we don’t define any cascading then no operations in parent affects the child.
  2. ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist. Basically all operations.
  3. SAVE_UPDATE: Cascades save and update, available only in hibernate.
  4. DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
  5. DETATCH, MERGE, PERSIST, REFRESH and REMOVE – for similar operations
  6. LOCK: Corresponds to the Hibernate native LOCK action.
  7. REPLICATE: Corresponds to the Hibernate native REPLICATE action.
19. How to log the queries generated by hibernate on console?

When we call methods like save,update,delete,get on entities in session then queries gets generated on backend by hibernate. We can see these queries on console by just adding below line to hibernate configuration file –

<property name="hibernate.show_sql">true</property>

20. What is Native SQL query in hibernate?

You can write your own queries and execute them against the database. For Hibernate Native SQL Query, we use Session.createSQLQuery(String query) to create the SQLQuery object and execute it.
Native SQL Query comes handy when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in Oracle Database.

21. What is Named Native SQL query in hibernate?

Hibernate provides Named Query that we can define at a central location and use them anywhere in the code. We can create named queries for both HQL and Native SQL.

Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery.

Serialization

1. What is the serialization?

Serialization is a process converting an object into a byte array. This byte array represents the class, version and internal state of the object. JVM can use this byte array to transmit/read the object over a network.

 

2. What is the purpose of serialization?

Some of the uses of serialization are:

  • Communication: It is used for transmitting an object over network between two machines.
  • Persistence: We can store the object’s state in a database and retrieve it from database later on.
  • Caching: Serialization can be used for caching to improve performance. We may need 10 minutes to build an object, but it may take just 10 seconds to de-serialize the object.
  • Cross JVM Synchronization: It can be used in same way across multiple JVM that follow different architecture.

 

3. What is Deserialization?

Deserialization is the process of reconstructing the object from the serialized state. It is the reverse process of serialization.

 

4. What is Serialization and Deserialization conceptually?

Serialization is to convert Object data into a stream of bytes. Deserialization is to convert a stream of bytes back into a copy of the original object.

 

5. Why do we mark a data member transient?

Member variables of an object are marked transient to indicate that they should not be serialized.

During serialization process the transient variables are not considered part of the persistent state of an object.

 

6. Is it allowed to mark a method as transient?

No, Java does not allow marking a method as transient. The transient keyword is valid only for member variables.

 

7. How does marking a field as transient makes it possible to serialize an object?

Let say we have a class ABC that implements Serializable interface, but it contains a member variable object of class XYZ that does not implement Serializable interface. Due to this it is not possible to Serialize the class ABC.

To solve this issue, we can mark the member variable XYZ as Transient in class ABC. This will allow us to serialize the class ABC.

 

8. What is Externalizable interface in Java?

Externalizable interface extends Serializable interface in Java. It is used for giving the Class control over saving and restoring the contents of its instances.

A class implements methods writeExternal() and readExternal() to store and restore the object.

 

9. What is the difference between Serializable and Externalizable interface?

Serializable is a marker interface but Externalizable is not a marker interface.

When we implement Serializable interface, the class is serialized automatically by default. We can override writeObject() and readObject()methods to control more complex object Serialization process.

In case of Externalizable, we use readExternal() and writeExternal() methods to give control to class for class’s serialization process.

Serializable interface is based on recursive algorithm.

Serializable gives you two options. One option is to provide custom way of serialization, the other default way. In Externalizable, you have to always implement readExternal() and writeExternal() methods.

A public no-arg constructor is needed while using Externalizable interface.

In Serialization, we need to define serialVersionUID. If it is not explicitly defined it will be generated automatically based on all the fields, methods of the class.

 

Internationalization

1. What is Locale in Java?

A Locale object represents a specific geographical, political, or cultural region. It is used to locale-sensitive operations in Java.

It helps is following the local conventions of a country, native or region. These conventions can be for formatting the dates, money, numbers etc.

 

2. How will you use a specific Locale in Java?

To use a specific Locale, we need to load that Locale. We can use ResourceBundle.getBundle(“Locale.UK”) method to load a Locale.

 

 

Packages

1. What is the purpose of package in Java?

A package is used to encapsulate a group of classes, interfaces and sub-packages. Often, it is a hierarchical structure of storing information. It is easier to organize the related classes and subpackages in this manner.

A Package also provides access protection for classes and interfaces. A package also helps in removing naming collision.

 

2. What is java.lang package?

In Java, java.lang package contains the classes that are fundamental to the design of Java programming language. The most important class in this package is Object class.

It also contains wrapper classes like- Integer, Boolean, Character etc. It provides Math class for mathematical operations.

 

3. Which is the most important class in Java?

It is an open-ended question with many answers. In my view, Object class is the most important class of Java programming language. It is the root of all the classes in Java. It provides some very important and fundamental methods.

 

4. Is it mandatory to import java.lang package every time?

No. By default, JVM loads it internally.

 

5. Can you import same package or class twice in your class?

If we import same package multiple times in a class, compiler includes it only once. So neither JVM nor Compiler gives any error/warning on including a package multiple times.

If you have two classes with same name, then you may get name collision on importing the class erroneously. JVM internally loads the class only one time.

 

6. What is a static import in Java?

Static import is similar to normal import declaration. Normal import allows us to import classes from packages without using package qualifier. Static import allows us to import static members from a class without using class qualifier.

 

7. What is the difference between import static com.test.Fooclass and import com.test.Fooclass?

First import is a static import and the second import is normal import of a class. First import allows us to import static members of class.

 

 

 

Static

1. In Java, why do we use static variable?

Whenever we want to have a common property for all objects of a class, we use a class level variable i.e. a static variable.

This variable is loaded in memory only once at the time of class loading. So it saves memory, since it is not defined per object in Java.

 

2. Why it is not a good practice to create static variables in Java?

Static variables are common to all the objects of a class. If a new object is created, there is no need to test the value of static variable. Any code that uses static variable can be in any state. It can be within a new object or at a class level. So the scope of static variable is open ended in a Java class.

If we want tighter control on scope, then variables should be created at the object creation level.

Also defining static variables is not a good practice because they go against the principles of Object Oriented Programming.

 

3. What is the purpose of static method in Java?

Java provides the feature of static method to create behavior at the class level. The static method is common to all the objects of a class. We do not need to create any object of a class to call a static method. So it provides convenience of not creating an object for calling it.

Also a static method can access and modify static data members. This also helps in keeping the behavior as well as state at the class level.

 

4. Why do we mark main method as static in Java?

The main method in Java is marked as static, so that JVM can call it to start the program. If main method is not static, then which constructor will be called by Java process?

As such it is a known as convention to mark main method static in Java. But if we remove the static, then there will be ambiguity. Java process may not know which method of a class to call to start the program.

So this convention helps in Java process to identify the starting code for a program in class that is passed as an argument to java process.

 

5. In what scenario do we use a static block?

At times, there is a class that has static member variables. These variables need some complicated initialization. At this time static block helps as a tool to initialize complex static member variable initialization.

The static block is executed even before the execution of main.Sometimes, we can also replace static block with a static method of class.

 

6. Is it possible to execute a program without defining a main() method?

No, with Java 7 onwards, you need a main() method to execute a program. In earlier versions of Java, there was a workaround available to use static blocks for execution. But now this gap has been closed.

 

7. What happens when static modifier is not mentioned in the signature of main method?

As per Java specification, main method has to be marked as static. It needs only one argument that is an array of String.

A program can compile with a non-static method. But on execution it will give NoSuchMethodError.

 

8. What is the difference between static method and instance method in Java?

Often, there is a need to define a behavior for a class that is not dependent on member variables of an object. Such behavior is captured in a static method. If there is a behavior dependent upon the member variables of an object, then we do not mark it static, it remains as instance method.

To call as static method, we do not need to create an object. We just call it with class name. But to call an instance method, we need to create/get an object first.

Instance member variables cannot be accessed by a static method. But an instance method can call both instance variables and static variables.

Final

1. How can you change the value of a final variable in Java?

Java does not allow changing the value of a final variable. Once the value is set, it cannot be changed.

 

2. Can a class be marked final in Java?

Yes a class can be marked final in Java. Once a class is marked final, it cannot be extended.

 

3. How can we create a final method in Java?

To mark a method, add modifier final to that method. A final method can not be overridden by a child class.

 

4. How can we prohibit inheritance in Java?

If you mark a class final, it cannot be extended. This will prohibit the inheritance of that class in Java.

 

5. Why Integer class in final in Java?

Integer class is a wrapper for int. If it is not marked final, then any other class can extend it and modify the behavior of Integer operations. To avoid this Integer wrapper class is marked as final.

 

6. What is a blank final variable in Java?

When we declare a final variable without giving any initial value, then it is called blank final variable.

 

7. How can we initialize a blank final variable?

A blank final instance variable can be initialized in a constructor.A blank final static variable can be initialized in the static block of class.

 

8. Is it allowed to declare main method as final?

Yes, we can mark the main method as final.

 

 

 

Immutable Class in Java

Here i am going to share some questions on Immutable classes in java –

      1. What is an immutable class?

Immutable class is a class which once created, it’s contents can not be changed.  It means any modification on immutable object will result in a new immutable object. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

Example: String , Integer , Float etc.

      2.  How can you create custom immutable class in java?

  • Declare all instance variables private and final : 
    If you make instance variable private, no outside class will be able to access instance variables and if you make them final, you can not change it.
  • Don’t provide setter methods :
    Don’t create setter method for any instance variables, hence there will be no explicit way to change state of instance variables.
  • Initialize all variables in constructor :
    You can initialize variables in constructor. You need to take special care while working with mutable object. You need to do deep copy in case of immutable objects.
  • Make your class final : 
    If you make your class final, no class will be able to extend it, hence will not be able override methods of this class.
  • Clone mutable objects while returning from getter method:
    If you return clone of object from getter method, it won’t return original object, so your original object will remain intact. If the getters return an Object reference such as Collections, Arrays or other class object, clone the object before returning. Make sure the object is deep clone and not shallow.

FinalClassDemo.java

/**
Mutable class example
*
*/
package com.myjavablog.javainterview;

import java.util.HashMap;
import java.util.Iterator;

public final class FinalClassDemo {

private final int id;

private final String name;

private final HashMap<String, String> testMap;

public int getId() {
return id;
}

public String getName() {
return name;
}

/**
* Accessor function for mutable objects
*/
public HashMap<String, String> getTestMap() {
// return testMap;
return (HashMap<String, String>) testMap.clone();
}

/**
* Constructor performing Deep Copy
*
* @param i
* @param n
* @param hm
*/

public FinalClassDemo(int i, String n, HashMap<String, String> hm) {
System.out.println("Performing Deep Copy for Object initialization");
this.id = i;
this.name = n;
HashMap<String, String> tempMap = new HashMap<String, String>();
String key;
Iterator<String> it = hm.keySet().iterator();
while (it.hasNext()) {
key = it.next();
tempMap.put(key, hm.get(key));
}
this.testMap = tempMap;
}

/**
* Constructor performing Shallow Copy
*
* @param i
* @param n
* @param hm
*/
/**
* public FinalClassDemo(int i, String n, HashMap<String,String> hm){
* System.out.println("Performing Shallow Copy for Object initialization");
* this.id=i; this.name=n; this.testMap=hm; }
*/

/**
* To test the consequences of Shallow Copy and how to avoid it with Deep Copy
* for creating immutable classes
*
* @param args
*/
public static void main(String[] args) {
HashMap<String, String> h1 = new HashMap<String, String>();
h1.put("1", "Final1");
h1.put("2", "Final2");

String s = "original";

int i = 10;

FinalClassDemo ce = new FinalClassDemo(i, s, h1);

// Lets see whether its copy by field or reference
System.out.println(s == ce.getName());
System.out.println(h1 == ce.getTestMap());
// print the ce values
System.out.println("ce id:" + ce.getId());
System.out.println("ce name:" + ce.getName());
System.out.println("ce testMap:" + ce.getTestMap());
// change the local variable values
i = 20;
s = "modified";
h1.put("3", "Final3");
// print the values again
System.out.println("ce id after local variable change:" + ce.getId());
System.out.println("ce name after local variable change:" + ce.getName());
System.out.println("ce testMap after local variable change:" + ce.getTestMap());

HashMap<String, String> hmTest = ce.getTestMap();
hmTest.put("4", "Final4");

System.out.println("ce testMap after changing variable from accessor methods:" + ce.getTestMap());

}

}

     3. What is Deep Copy vs Shallow Copy ?

Shallow Copy

  • Whenever we use default implementation of clone method we get shallow copy of object means it creates new instance and copies all the fields of object to that new instance and returns it as object type.
  • clone() method of the object class support shallow copy of the object.
  • If the object contains primitive as well as non-primitive or reference type variable in shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves.
  • If only primitive type fields or Immutable objects are there then there is no difference between shallow and deep copy in Java.
  • Refer lines 57-72 to see shallow copy constructor in above example.

Deep Copy

  • Whenever we need own copy not to use default implementation we call it as deep copy, whenever we need deep copy of the object we need to implement according to our need.
  • So for deep copy we need to ensure all the member class also implement the Cloneable interface and override the clone() method of the object class.
  • Refer lines 35-54 to see Deep copy constructor in above example.

When to use what
There is no hard and fast rule defined for selecting between shallow copy and deep copy but normally we should keep in mind that if an  object has only primitive fields, then obviously we should go for shallow copy, but if the object has references to other objects, then based on the requirement, shallow copy or deep copy should be done. If the references are not updated then there is no point to initiate a deep copy.

4.  What are the advantages of immutable class in java?

  • Immutable class is good for caching purpose because you don’t need to worry about the value changes. You can use static factory methods to provide methods like valueOf(), which can return an existing Immutable object from cache, instead of creating a new one.
  • Other benefit of immutable class is that it is inherently thread-safe, so you don’t need to worry about thread safety in case of multi-threaded environment.
  • The best use of the immutable objects is as the keys of a Map and values of Set.
  • Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.

Please feel free to comment in case of any doubts.

Method Overloading and Overriding

1. What is the other name of Method Overloading?

Method Overloading is also known as Static Polymorphism.

 

2. How will you implement method overloading in Java?

In Java, a class can have multiple methods with same name but different arguments. It is called Method Overloading. To implement method overloading we have to create two methods with same name in a class and do one/more of the following:

  • Different data type of parameters
  • Different number of parameters
  • Different sequence of data type of parameters.

 

3. What kinds of argument variations are allowed in Method Overloading?

Method Overloading allows two methods with same name to differ in: 1. Number of parameters 2. Data type of parameters 3. Sequence of data type of parameters.

 

4. Why it is not possible to do method overloading by changing return type of method in java?

If we change the return type of overloaded methods then it will lead to ambiguous behavior. How will clients know which method will return what type. Due to this different return type are not allowed in overloaded methods.

 

5. Is it allowed to overload main() method in Java?

Yes, Java allows users to create many methods with same name ‘main’. But only public static void main(String[] args) method is used for execution.

 

6. How do we implement method overriding in Java?

To override a method, we just provide a new implementation of a method with same name in subclass. So there will be at least two implementations of the method with same name. One implementation is in parent class. And another implementation is in child class.

 

7. Are we allowed to override a static method in Java?

No. Java does not allow overriding a static method. If you create a static method with same name in subclass, then it is a new method, not an overridden method.

 

8. Why Java does not allow overriding a static method?

To override a method, you need an instance of a class. Static method is not associated with any instance of the class. So the concept of overriding does not apply here.

Therefore, Java does not allow overriding a static method.

 

9. Is it allowed to override an overloaded method?

Yes. You can override an overloaded method in Java.

 

10. What is the difference between method overloading and method overriding in Java?

Differences between method overloading and overriding are:

  • Method overloading is static polymorphism. Method overriding is runtime polymorphism.
  • Method overloading occurs within the same class. Method overriding happens in two classes with hierarchy relationship.
  • Parameters must be different in method overloading. Parameters must be same in method overriding.
  • Method overloading is a compile time concept. Method overriding is a runtime concept.

 

11. Does Java allow virtual functions?

Yes. All instance methods in Java are virtual functions by default. Only class methods and private instance methods are not virtual methods in Java.

 

12. What is meant by covariant return type in Java?

A covariant return type of a method is one that can be replaced by a “narrower” type when the method is overridden in a subclass.

Let say class B is child of class A. There is a get() method in class A as well as class B. get() method of class A can return an instance of A, and get() method of class B return an instance of B. Here class B overrides get() method, but the return type is different.

Before Java 5, any method that overrides the method of parent class would have same return type.

From Java 5 onwards, a child class can override a method of parent class and the child class method can return an object that is child of object return by parent class method.

Inheritance

1. What is the purpose of ‘this’ keyword in java?

In Java, ‘this’ keyword refers to current instance of the object.

It is useful for differentiating between instance variables and local variables.

It can be used to call constructors. Or it can be used to refer to the instance.

In case of method overriding, this is used for falling the method of current class.

 

2. Explain the concept of Inheritance?

Inheritance is an important concept in Object Oriented Programming. Some objects share certain characteristics and behavior. By using Inheritance, we can put the common behavior and characteristics in a base class which also known as super class. And then all the objects with common behavior inherit from this base class.

It is also represented by IS-A relationship.

Inheritance promotes, code reuse, method overriding and polymorphism.

 

3. Which class in Java is superclass of every other class?

Java is an object oriented programming language. In Java, Object class is the superclass of every other class.

 

4. Why Java does not support multiple inheritance?

Multiple Inheritance means that a class can inherit behavior from two or more parent classes.

The issue with Multiple Inheritance is that both the parent classes may have different implementation for the same method. So they have different ways of doing the same thing. Now which implementation should the child class choose?

This leads to ambiguity in Multiple Inheritance. This is the main reason for Java not supporting Multiple Inheritance in implementation.

Lets say you have a class TV and another class AtomBomb. Both have method switchOn() but only TV has switchOff() method. If your class inherits from both these classes then you have an issue that you can switchOn() both parents, but switchOff will only switchOff() TV .

But you can implement multiple interfaces in Java.

 

5. In OOPS, what is meant by composition?

Composition is also known as “has-a” relationship. In composition, “has-a” relation relates two classes. E.g. Class Car has a steering wheel.

If a class holds the instance of another class, then it is called composition.

 

6. How aggregation and composition are different concepts?

In OOPS, Aggregation and Composition are the types of association relations. A composition is a strong relationship. If the composite object is destroyed, then all its parts are destroyed. E.g. A Car has a Steering Wheel. If Car object is destroyed, then there is no meaning of Steering Wheel.

In Aggregation, the relationship is weaker than Composition.

E.g. A Library has students. If a Library is destroyed, Students still exist. So Library and Student are related by Aggregation. A Library has Books. If Library is destroyed, the Books are also destroyed. Books of a Library cannot exist without the Library. So Book and Library are related by Composition.

 

7. Why there are no pointers in Java?

In Java there are references instead of pointers. These references point to objects in memory. But there is no direct access to these memory locations. JVM is free to move the objects within VM memory.

The absence of pointers helps Java in managing memory and garbage collection effectively. Also it provides developers with convenience of not getting worried about memory allocation and deallocation.

 

8. If there are no pointers in Java, then why do we get NullPointerException?

In Java, the pointer equivalent is Object reference. When we use a . it points to object reference. So JVM uses pointers but programmers only see object references.

In case an object reference points to null object, and we try to access a method or member variable on it, then we get NullPointerException.

 

9. What is the purpose of ‘super’ keyword in java?

‘super’ keyword is used in the methods or constructor of a child class. It refers to immediate parent class of an object.

By using ‘super’ we can call a method of parent class from the method of a child class.

We can also call the constructor of a parent class from the constructor of a child class by using ‘super’ keyword.

 

10. Is it possible to use this() and super() both in same constructor?

No, Java does not allow using both super() and this() in same constructor. As per Java specification, super() or this() must be the first statement in a constructor.

 

11. What is the meaning of object cloning in Java?

Object.clone() method is used for creating an exact copy of the object in Java. It acts like a copy constructor. It creates and returns a copy of the object, with the same class and with all the fields having same values as of the original object.

One disadvantage of cloning is that the return type is an Object. It has to be explicitly cast to actual type.

 

Bitnami