Java Interview Reference Guide – Part 1

JAVA Object Oriented Concepts

Java in based on Object Oriented concepts, which permits higher level of abstraction to solve any problem in realistic way.

Object oriented approach conceptualize the problem solution in real-world object which are easier to reuse across the application. For example Chair, Fan, Dog, computer etc.

In Java, a class is a blueprints, template or prototype that define common behavior of object of same kind. An instance is realization of a particular class and all instances of a class have similar properties, as described in the class definition. For example, you can define a class called House with number of room as attribute and create instances such as house with 2 rooms, house with 3 rooms etc.


Below are few advantages of object oriented software development:

  • Less maintenance cost mostly because it is modular.
  • Better code reusability due to features such as inheritance and hence faster development.
  • Improved code reliability and flexibility
  • Easy to understand due to real-world modeling.
  • Better abstraction at object level.
  • Reduced complexity during the transitions from one development phase to another.

There are four main features of OOPS:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction


Encapsulate provides contract to other object to what to hide and what to expose which can be accessed other objects. In java we use private access modifier to hide method and variable to restrict from outer world. Java also provide different access modifier such as public, default, protected and private, which use to hide the visibility on different level but end goal is to encapsulate the things, which need not to change.  As per best practice A class should have only one reason to change and Encapsulate bring the reality to achieve “one-reason” design principle.

As per best practices in Encapsulation means hiding things that are expected to change often so to avoid breaking other classes.

Benefits: Below are few advantages of Encapsulation: 

  • We can protect the internal state on objects by hiding its attribute.
  • It Improves code modularity by preventing objects interacting with each other in an unexpected way.
  • Increases usability
  • It Maintain the contracts of specific object
  • Encapsulation promotes maintenance
  • Code changes can be made independently


Polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types). That means classes have different functionality while sharing a common interface and can be invoked dynamically by passing specific class reference.

The classic example is the Shape class and all the classes that can inherit from it (square, circle, dodecahedron, irregular polygon, splat and so on).

In this example, every class would have its own Draw () function and the client code could simply do:

Shape shape=new Square ();

Shape.area() to get the correct behavior for any shape.

The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way.

The process used by object-oriented programming language to implement run-time polymorphism is called dynamic binding.

Note: Polymorphism is the ability to select more specialized methods in runtime depending on the object being used to call it. Polymorphism could occur with no abstract classes involved.


  • Create Reusable code: It means once classes create, implemented and tested then it can be easily used without caring what written in the class.
  • It provides more generic and loosely coupled code.
  • Compile time is much lower and allow faster development.
  • Dynamic binding:
  • Same interface could be used for creating methods with different implementations
  • Complete implementation can be replaced by using same method signatures

Method Overriding to achieve Polymorphism: Overriding deals with two methods; one in the parent class and the other one in the child class and have the same name and signatures.

Overriding lets you define the same operation in different ways for different object types


while(it.hasNext()) {

Shape s = (Shape);

totalArea += s.area(dim); //polymorphic method call. Will call right object method



Method Overloading or Ad-hoc polymorphism or static polymorphism:

Overloading deals with multiple methods in the same class with the same name but different method signatures. Overloading lets you define the same operation in different ways for different data. Some time it says as static polymorphism but actually it is not polymorphism.

Method overloading is nothing more than having two methods with the same name but different argument lists. It has nothing to do with inheritance and polymorphism. An overloaded method is not the same as an overridden method. [Head First Java]

Parametric polymorphism through generics in Java:

Within a class declaration, a field name can associate with different types and a method name can associate with different parameter and return types. Java supports parametric polymorphism via generics.

An example is a list, which can accept the type of data it contains through generics.

    List<String> list = new ArrayList<String>();

Why we can’t override a static method in Java?

Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.

There were two considerations driving Java’s design that impacted this. One was a concern with performance: there had been a lot of criticism of Smalltalk about it being too slow (garbage collection and polymorphic calls being part of that) and Java’s creators were determined to avoid that. Another was the decision that the target audience for Java was C++ developers. Making static methods work the way they do had the benefit of familiarity for C++ programmers and was also very fast, because there’s no going up the class hierarchy to figure out which method to call, you go straight to the class and call the specified method. [Stack overflow]


It is the inclusion of behavior (i.e. methods) and state (i.e. variables) of a base class in a derived class so that they are accessible in that derived class. The key benefit of Inheritance is that it provides the formal mechanism for code reuse and avoids duplication

Inherited class extends application’s functionality by reusing parent behavior and adding new functionalities. This will make the design tight coupled because if you want to change the superclass, you must know all the details of the subclasses to avoid breaking

It is form of software reusability where new class (sub class) are created from already existing class (super class) which enhance the functionalities while using some of the properties from super class.

So if you have a Parents class, then you have a Child class that extends Parent, Child inherits all the things that Person has.


  • Improve reusability
  • Establishes logically “is a” relationship: e.g. Dog is a animal
  • Modularize code
  • Avoid duplicity


  • Tightly coupled: Subclass depends on parent class implementation that’s why tight couple.


Abstraction means develop class in terms of their interfaces and functionality, instead of their implementation details. Abstract class expose interfaces without including actual implementation. It separates the object implementation from its behavior or implementation.  Abstraction reduces the complexity by hiding irrelevant detail.


  • By using abstraction, we can separate the things that can be grouped to another type.
  • Frequently changing properties and methods can be grouped to a separate type so that the main type need not under go changes. This adds strength to the OOAD principle -”Code should be open for Extension but closed for Modification”.
  • Simplifies the representation of the domain models.

Difference between Abstraction and Encapsulation

Encapsulation is a strategy used as part of abstraction. Encapsulation refers to the state of objects – objects encapsulate their state and hide it from the outside; outside users of the class interact with it through its methods, but cannot access the classes state directly. So the class abstracts away the implementation details related to its state.

Abstraction is a more generic term; it can also be achieved by (amongst others) sub classing. For example, the class List in the standard library is an abstraction for a sequence of items, indexed by their position, concrete examples of a List are an ArrayList or a LinkedList. Code that interacts with a List abstracts over the detail of which kind of a list it is using [Stack overflow]

Abstraction is often not possible without hiding underlying state by encapsulation – if a class exposes its internal state, it can’t change its inner workings, and thus cannot be abstracted

What is abstract class and abstract method?

In design, you want the base class to present only an interface for its derived classes. This means, you don’t want anyone to actually instantiate an object of the base class. You only want to upcast to it (implicit upcasting, which gives you polymorphic behavior), so that its interface can be used. This is accomplished by making that class abstract using the abstract keyword.

Provide some restriction on to not to instantiate the abstract class and whoever use should implement the abstract method. And provide polymorphism

Abstract class can contain both abstract methods and concrete methods. In a class, if one method is declared abstract, the class must be declared abstract. However, reverse of this is not necessarily true. If class is declared abstract class, it may not have abstract method in it.

If a method does not provide actual implementation but just provides method signature, it is called abstract method. Actual implementation is left for the sub classes who extend abstract class.

Abstract method cannot be instantiated; another class can only extend it.

When to use an abstract class?

Abstract classes let you define some default behavior and force subclasses to provide any specific behavior.

For example: List is interface whereas AbstractList provide default behavior of List which can be used as is or refined in subclass e.g. ArrayList.

What is Interface?

The interface keyword takes this concept of an abstract class a step further by preventing any method or function implementation at all. You can only declare a method or function but not provide the implementation. The class, which is implementing the interface, should provide the actual implementation. The interface is a very useful and commonly used aspect in OO design, as it provides the separation of interface and implementation and enables you to:

Benefits on interface:

  1. Multiple inheritance
  2. Loose coupling-defined abstraction of operation as separate layer-underline implementation could be anything, JDBC, JPA, JTA etc.
  3. Program to interface not implement
  4. Polymorphism with dynamic bindingReveal an object’s programming interface without revealing its actual implementation.
  5. Abstract Layer: Separation concerns

Difference between interface and abstract class:

  • An interface is a contract to ask classes (whoever going to implement interface) to implement the interface the way it defines in interface. It is an empty shell with method declaration.
  • Abstract class define some common behavior and ask subclass to define uncommon or specific behavior to that class
  • Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public
  • When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don’t have to be defined
  • A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces.
  • A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility
  • Interface doesn’t contain constructor whereas Abstract class does.
  • Variables declared in a Java interface is by default final. An abstract class may contain non-final variables
  • Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc


Code reusability could be achieved by implementing inheritance or composition but the composition approach to code reuse provides stronger encapsulation than inheritance, because a change to a back-end class needn’t break any code that relies only on the front-end class.

Composition is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition for code reuse

Composition is about expressing relationships between objects. Think about the chair example. A chair has a Seat. A chair has a back. And a chair has a set of legs. The phrase “has a” implies a relationship where the chair owns, or at minimum, uses, another object. It is this “has a” relationship which is the basis for composition


  • Control the visibility
  • Implementation can replace run-tim
  • Loose coupled as interface class doesn’t depends on implementation.

Difference between Composition and Inheritance? 

No. Composition (has a) Inheritance (is a)
1 Advocates polymorphism and code reuse Advocates polymorphism and code reuse
2 Object is acquired at Done at run- time Object is acquired dynamically at compile-time
3 Implementation can be replaced at run-time Implementation can be replaced at compile-time
4 Subclass doesn’t depends parent class and favors loose coupling (specifically in interface driven) Subclass depends on parent class implementation that’s why tight couple
5 Used when House has a Bathroom. It is incorrect to say House is a bathroom Inheritance is Uni-directional. e.g. House is a Building. But Building is not a House

Note: Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code reuse.

Difference between Composition and aggregation in Object Relationship

Aggregation: Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole. It is weaker relationship. No cyclic dependency. Example: Order and product

Composition: Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted. It is stronger relationship. e.g. Polygon and points, order and order detail 


EDA – Event Driven Architecture

Event-driven architecture (EDA) is a push-based communication between publisher and consumer, which predominantly use for proactive notification in real time environment.
For e.g. Fraud notification from credit card Company, shipping, order fulfillment etc.
EDA use to communicate with consumer with minimum or no delay and avoid busy-wait thread stats.
EAD is a style of application architecture can be implemented in any language, which can improve responsiveness, throughput and flexibility.

An EDA is extremely loosely coupled than client/server paradigm because the publisher doesn’t know the identity of the consumers. This leads to an implementation which is easier to extend, evolve and maintain, giving you more flexibility and reducing maintenance cost.

Listener acts as asynchronous receiver, which automatically receives messages as they’re delivered on the channel.

1. EAD utilize existing resource efficiently.
2. This leads to an implementation which is easier to extend, evolve and maintain, giving you more flexibility and reducing maintenance cost.
3. This results in lower operational costs, increased utilization and happier end-users.
4. There is no direct coupling between the publisher and the consumer i.e. loosely coupled
5. Prevent block or wait in queue

Business needs to make more responsiveness and react to certain situation as they occur. An Event Driven Architecture (EAD) monitor changes in state and respond it in real time. Some scenario where need quick reaction we could use EDA, while other areas still pull and scheduled pattern could be used. The main point is to understand the use case scenario and advantage on it before using EDA.


Spring Integration: A lightweight integration Approach

Today’s application expects access of all business in enterprise environment regardless of application technologies, which require, seamless integration with desperate systems.
This integration can be achieved through wiring of desperate systems using Middleware technologies.
Integration platform enables environment for applications to share information with each other to make architecture high interoperable.
Spring Integration provides a mediation framework to build lightweight integration solution using routing and mediation, regardless of protocols. The Spring Integration is lightweight routing and mediation framework and doesn’t need heavy weight ESB container to deploy.
Spring Integration uses Message object to communicate, route and pass the data, which is nothing, but a wrapper on Java object consists of payload and header. Payload consist data which could be any type such as File, String, stream etc. and header consist generic information on message such as id, timestamp etc.
Message communicates to producer via channel, which decoupled source from destination and post the message to any protocols such as JMS, HTTP, Ldap, file etc.
Producers send Messages to a channel, and consumers receive Messages from a channel

Spring Integration_Simple
Simple Integration Application
Below example show how producer send an employee object to channel and publisher receive message from channel.
Download Source code: Download the full code download link.

Spring Dependency Maven configuration
For starting simple integration example we just need to add the core spring integration and spring context dependency to maven pom.xml. Moreover we also need Junit and spring test to enable unit testing


Spring Configuration
We have to configure channel and gateway in spring configuration to send and receive message


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns=""
 <context:component-scan base-package="org.springsample.integration"/>
 <gateway id="request" service-interface="org.springsample.integration.SentRequest"/>
 <channel id="sendRequest"/>
 <outbound-channel-adapter channel="sendRequest" ref="receiveResponse" method="processMessage" />

Here we created request gateway to send the message to channel and outbound adapter to receive message from the sendRequest channel.
Gateway of Spring Integration is entry points to send messages, which specify using Java Interface. Spring Integration automatically define proxy implementation at runtime
Request and Receive
Below we create the SentRequest and ReceiveResponse class to send and receive message as follows

package org.springsample.integration;
import org.springframework.integration.annotation.Gateway;
public interface SentRequest {
 public void process(Employee emp);


@Gateway annotation will indicate entry point to send message

package org.springsample.integration;
import org.springframework.integration.Message;
import org.springframework.integration.annotation.MessageEndpoint;
public class ReceiveResponse {
public void processMessage(Message<Employee> message) {
 Employee employee = message.getPayload();
 System.out.println("Message Received \n Name :"+employee.getName()+"/n Phone : "+employee.getPhone()+"/n Address :"+employee.getAddress());


@MessageEndpoint will indicate that it will receive message from channel via adapter.
Not but not leas below is Employee POJO

package org.springsample.integration;
public class Employee {
 private String name;
 private String title;
 private String address;
 private String phone;

public Employee(String name, String phone, String address) {;; this.address=address;
//……..Getter amd Setter

We can test this using spring test framework as below

package org.springbyexample.integration;
public class SpringIntegTest {
 private SentRequest request = null;
 public void testIntegration() {
 Employee emp = new Employee("John", "12345678", "Sunny Street Mac RG1");

Make sure you keep spring config file name SpringIntegTest-context in org/springbyexample/integration and should be in your class path
While running SpringIntegTest, it will display console message as follows
Message Received
Name :John/n Phone : 12345678/n Address :Sunny Street Mac RG1
Download Source code: Download the full code download link.
Spring Integration is open source simple integration that enhances loose coupling and make application integration easy and simpler. It will integrate, route and mediate the message across the channel and gateway in configurable way.
This article helps to understand about Spring Integration and will aid you to develop a simple integration application.

How to create JQuery DataTable using JSON and servlet

In this article I’ll introduce the basic coding that require to create JQuery DataTable using JSON passed by simple servlet.
DataTable is very powerful JQuery based grid with advance features which can be build in short span of time with customize features.

1. Download Latest JQuery DataTable download
2. Above download will provide two JQuery plugin jquery.js and queryTables.js

<script type="text/javascript"
charset="utf-8" src="/DataTables/media/js/jquery.js"></script>
<script type="text/javascript"
charset="utf-8" src="/DataTables/media/js/jquery.dataTables.js"></script>

3. Default stylesheet which shipped with latest DataTable download package

<style type="text/css" title="currentStyle">
 @import "../resources/css/demo_table.css";

Note:You can download full source code from Github link

Creating the DataTable

We can write below code to create the basic DataTable with data


<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var oTable = $('#tableId').dataTable( {
"processing": true,
"ajax": {
"url": "/ExampleDataTableJSON/DataTableServlet",
"dataSrc": "demo",
"type": "GET"
} );
} );

$(document).ready will ready to execute the javascript and var oTable = $(‘#tableId’).dataTable says that write DataTable on tableId place.

DataTables will adding sorting, filtering, paging and information to your table by default, providing the end user of your web-site with the ability to control the display of the table and find the information that they want from it as quickly as possible.

The pointer tableId and column name will be defined in table tag as below


<table cellpadding="0" cellspacing="0" border="0"
<th width="10%">First Name</th>
<th width="10%">Last Name</th>
<th width="10%">Address 1</th>
<th width="10%">Address 2</th>

Above DataTable code invoke FeedServlet which will return JSON string as defined below

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String json = "{ \"demo\":[[\"First Name\",\"Last Name\","+
+\"Address1\",\"Address2\"],[\"First Name\",\"Last Name\",\"Address1\",\"Address2\"]]}";

Now either we can use servlet annotation or web.xml as below to register above FeedServlet




Incorporate the above point and deploy with server to view the result as follows:


JQuery DataTable Image

JQuery DataTabl

You can download full source code from Github link and most welcome to fork or update the same.


Grails – GORM Tutorial

Grails is known as domain driven language that means we can build application using bottom to top approach which is more nearer to object oriented programming. GORM (Grail Object Relational Mapping) uses intern Hibernate to map the domain with table which gives life to Domain modeling. If we combined everything just only based on domain we could build the whole web application. Scaffolding can bring domain design directly to visible state to business users with extra involvement Continue reading

Grails a Spring MVC Framework

Grails is based on the Model-View-Controller (MVC) architectural pattern and favors convention over configuration Grails framework build on top of Spring MVC. It uses URL to identify the action & view and process CRUD using domain. Business logic constitute in Grails services which could be wired with controller using Spring DI (Dependency Injection) mechanism. Continue reading