MUST Have Core Java Interview Questions

By | April 5, 2017
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest

Another article in series of Technical Interview Questions and Answers on Web Development Tutorial covering Core Java Interview Questions this time. You will find more detailed answers to mostly asked interview questions during a technical interview. Java Interview Questions and Answers

Java Interview Questions PDF version will be available later for download.


Following Related Technical Interview Questions and Answers will also be helpful.


Complete Java Interview Questions List

Courses Online

What is object oriented programming. How java differs from other object orienting programming languages like C++?

Object oriented programming, primarily known as OOP, is a programming paradigm, which simplifies the development of software using some key concept provided to make development easier and faster.  An object is something that has state and behavior. An object can have data, fields, methods. Objects can talk, access to other objects. Access would be granted based on the modifiers. A class in OOP stores information and demonstrate the information using methods, so class is basically blueprint of an object.

Let’s talk in brief about different components of Object Oriented Programming:

  • Object
  • Class
  • Encapsulation
  • Abstraction
  • Polymorphism
  • Inheritance

Object:

Object is something that has state and behavior. We can easily relate object to some real world objects like machine, car etc.

Class:

Class is basically a logical collection of objects. That can have multiple methods, variables encapsulated in it.

Encapsulation:

As the name suggests, encapsulation is basically to encapsulate multiple logically related things together in an entity that is called class and provide proper access modifiers to the variables, so that these can not be accessed directly from outer world.

Abstraction :

Consider a scenario, where you are writing some logic that you don’t want to expose to outer world, so we just expose declaration of the thing to outer world with help of interfaces so that the implementation will be completely hidden from outer world, Like we have a code that checks if   an number is palindrome or not, so we need not show our logic to calling code. We will just create an interface which will have a method and takes a parameter of which will a number and return a boolean based on our computation.  This is called abstraction, where the calling code does not know anything about the implementation.

Polymorphism :

If we go by definition, polymorphism means one name many forms. The same we apply while writing code in a language that is object oriented. So practically we create methods that have the same name but differs in parameters, it is called polymorphism. Where a single method name have more than one implementation. In java we use concepts like method overloading and method overriding to achieve the same.

Inheritance:

Whenever we write code, we always think of re-usability or extension of the code that is already written. So in inheritance an object takes all or some properties of the class that is parent to this.

We will talk in detail about these concepts. This is very basic overview about Object oriented programming and object oriented programming concepts.

Now lets talk about Java, so Java is an object oriented programming language that is extensively used in software world to create highly secure, robust software.

The main and most important feature of java that make it differ from other OOP programming languages is that Java is platform independent. When we say platform independent then it means write once and run anywhere. Java compiler creates a byte code that can be executed across JVM’s that can be Linux, that can be Windows, that can be MAC and so on.

If we talk about some key differences between C++ and Java then, although both languages are object oriented programming languages but still there are some key differences between these two :

  • C++ is platform dependent language, whereas Java is platform independent language.
  • C++ support multiple inheritance, whereas java removes multiple inheritance, since it can cause DOD that is Diamond of Death problem.
  • Pointers, C++ has support for pointers, Java also has support but java internally uses pointers. Programmer doesn’t have to write pointer code explicitly.
  • C++ does not have multithreading support, whereas Java provides support for multi-threading.

And so and so on, there are many differences between these two languages but these are the key ones.

Back to top

Explain installation and environment setup of java. Briefly explain what is JRE,JDK and JVM?

First we need to download the executable file from http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html as per our operating system. One done with download the executable file , run the file and it will install java to our system and on successful installation the folder structure will look like this:Java Installation

So we have downloaded and installed the Java Development Kit and we are ready to go to code. Before processing forward we need to set the environment variable so that when we run java from command prompt operating system will aware what kind of program to run.

To achieve this, we need to traverse through the path below:Java Path

Now click on Advance system settings link that is on the left pen of this page, this will open a window like this:Java Environment Variables

Now clink on the highlighted one, that is Environment variables. Upon clicking this a new window will open, under this , click on new under System Variables and create a new System Variable and name it to JAVA_HOME, against variable value we need to path of java installation directory that is with my system is:

C:\Program Files\Java\jdk1.7.0_79.

Lets set this and see how it looks:Java Home Setting

Click on OK button and we are done with creating a new system variable JAVA_HOME. Next step is to add this variable to path. Under the same system variables there will a variable path, edit it and add JAVA_HOME to path.

That’s it we are good to go to write our first java code. Lets check with command prompt if the installation and configuration went fine or not:Java Installation and Configuration

So I have checked java version with command prompt, if there is anything wrong with configuration or installation this command will not get successfully executed and there will be error message. So this is a small way to check installation of java.

JRE is basically shorthand for Java Runtime Environment. It is basically the Java Virtual Machine where your Java programs run on. It also includes browser plugins for Applet execution.

JDK is shorthand used for Java Development Kit, which is the Software Development Kit for Java, including JRE, and the compilers and tools (like JavaDoc, and Java Debugger) to create and compile programs.

Usually, when you only care about running Java programs on your browser or computer you will only install JRE. It’s all you need. On the other hand, if you are planning to do some Java programming, you will also need JDK.

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

Back to top

What is polymorphism, Explain inheritance in java? Also explain overloading and overriding in java.

Polymorphism in object oriented programming is a concept where in an object can take one or more forms. Its like one name many forms. Any java object is elibigle to called polymorphic when an object “IS-A” kind of object. For example we have a parent class, then the eligible child classes can be Audi, BMW etc. So these child classes will extend the parent class that is Car and at the same time we can say Audi “IS-A” car, which makes Audi or BMW object polymorphic.

Lets understand the same with an example.

Here we will be creating a Car interface and this interface will have some methods that will be common to call cars.

So we have created a simple interface that is called Icar. This interface has two dummy methods that will setEngineCapacity and getEngineCapacity.

Now lets create impl classes for this.

First let say we create AudiImpl class that will for car audi.

Now lets create BMWImpl class with our ICar interface implementation.

Lets create a Main class and try to understand the IS-A concept that is behind Polymorphism.

So first thing to notice is that when the objects are polymorphic in nature we can create the objects with Interface reference. Now both AudiImpl and BMWImpl implements the ICar interface, so we can say that these two objects “IS-A” ICar type.

Next thing comes DynamicBinding,  which is the calling code even doesnot know on what type object the call is made. See getCarEngine method, here we are just passing objects from our main method but we are receiving the object in ICar interface and we made call to our actual object. This is beauty of polymorphism.

Now lets talk in brief about overloading and overriding.

We call Overloading, when two or more methods in one class have the same method name but different parameters.

We call Overriding, when two methods with the same method name and parameters. But Import point to note is one of the methods will be present in the parent class and the other is in the child class. Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class.

Back to top

What are different types of class loaders in java, explain class loading in java?

There are three kinds of class loaders in java :

  • Bootstrap (primordial)
  • Extensions
  • System

BootStrap or Primordial class loaders are class loaders that Loads JDK internal classes, java.* packages. Which will be defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar.

Extensions class loaders are class loaders that Loads jar files from JDK extensions directory. Which will be defined in the java.ext.dirs system property – usually lib/ext directory of the JRE.

 

System class loaders are class loaders that Loads classes from system classpath Which will be defined in the java.class.path property, which is set by the CLASSPATH environment variable or –classpath  command line options.System Class Loader

Class loaders are hierarchical, and maintain visibility. Bootstrap class loader have no visibility on the class loaded by Extension class loader and Extension class loader have no visibility over the classes loaded by classpath loader or System class loader.

Class loaders use a delegation model when loading a class. They request their parent to load the class first before they attempt to load it by their own. When a class loader loads a class, the child class loaders in the hierarchy will never load the class again, here classloaders maintain uniqueness.

Classes loaded by a child class loader have visibility over the classes loaded by its parents but not vice versa.

Back to top

What is difference between Composition and Aggregation?

Composition and Aggregation are concepts where two objects use each other’s functionality. When one object use functionality or services exposed by other object it is called Association.

Composition is when one object or one class associated with other class or object in such a way that the class can not have any meaning if other class is not present. Lets take an example of Bike, a Bike  have many objects like Tyres, Engine, Gear and so on, but when the bike is destroyed all these objects will also destroyed. These objects can not function if there is no car object. This concept is called Composition in java.

Aggregation is when two or more objects are associated with each other in such a way that if any of the object dies or destroyed, other one will still exist. Lets take an example, A Company can have many employees, when a scenario where Company is closed, Employee can join other company as well.

We can say composition is stronger than Aggregation.  A relationship between two objects is known as  an association, and an association when one object owns other is known as composition, while when an association one object uses another object is known as aggregation.Composition Vs Aggregation

So as we can see, Composition represents the strongest form of relation between objects where as Aggregation denotes a slightly weaker relationship between objects then composition, Association is most general form of relationship.

Lets take a practical example of Composition. Here we will create a Class name Bike, and other class as Tyre, that will have brand variable in it. Lets create this:

So as you can see Bike class constructor is initializing Tyre class, so the lifetime of class Tyre associated with Bike object, and whenever Bike class will destroyed the Tyre class will also destroyed. These both objects have strong relationship with each other and this is what we call Composition.

Lets take example of aggregation, here we will have a class Company and the company will have list of Departments. Now the difference with this is, Company class is not responsible for initializing the department class, and when the Company class will be destroyed the same Department class will not get destroyed, since both have their own life cycle. This is what we call Aggregation.

Back to top

Continue with More Java Interview Questions and Answers:

What is difference between Abstract class and Interface in Java, also explain when to use what?

In OOPS there is a principle called Abstraction, that is to abstract things from outer world. To achieve this interface and abstract classes are used.  Abstract classes are the classes in java that can have methods in such a way that some can have implementation and some will not have. These unimplemented methods are called abstract methods and we use abstract keyword to declare such methods. Now thing is we can not instantiate the abstract class. One more thing with abstract class is that there must be one method that will be abstract in this class to be called as abstract, if there is no abstract then we can not write class as abstract, the compiler will complain. Same if there is any abstract method in there and we declare the class as normal class then also compiler will complain and force us to declare class as abstract. These classes are meant to written for inheritance.

On the other hand interfaces are also abstract classes but these are pure abstract classes. Like we talked about the declaration and definition of methods in abstract  class like some can have some  may not have implementation, but in interfaces methods that we write are 100% abstract, mean there will only be declaration and the class that is implementing the interface, that class will have to provide the implementation. Methods declared in interfaces are by default abstract. We write these both to achieve abstraction. Like let say I have a service, whose job is to insert some data in database after some processing, so I will only provide the service interface to outer world with some methods. The actual processing will be done in the implementing class of this interface and the implementation I will hide from outer world. This is beauty of abstraction.

Lets take example of how we write abstract class and interface.

Lets create an interface named IVehicle that will have some methods in it:

So what we have done is we have created an interface named IVehicle with some methods in it, so every class that will implement this will have to provide implementation of these methods.

Now there are some methods, in which Brand, Model, EngineCapacity and FuelType will be provided. So now we will create one more level of abstraction and we will segregate the classes with one that have fuel type as diesel and one with fuel type as petrol. Why we will do this because all petrol cars object will not have to implement these methods. So we will create two abstract classes, lets create them:

So now we have created a hierarchy and added one level of abstraction. Every petrol type vehicle will have to extend the AbstractPetrolVehicle and every diesel type of vehicle will have to extend the AbstractDieselVehicle abstract class and the class have to provide the implementation for rest of the methods. Below is the example for AudiA3 class that extends AbstractPetrolVehicle and this class has to provide the methods implementation.

Back to top

Explain serialization in java, what is use of Serial Version UID?

Serialization is the process wherein object is converted into bytestream and it’s state is saved, so that the object can be travel over the network. In order to achieve serialization java provides Serializable interface, that is marker interface. So any object on which we need to achieve serialization, the class must extend Serializable interface.

The process from which the byte stream converted to java object again is known as deserialization. In this the persisted file or the serialized byte stream is converted in java object.

As we talked about the Serializable interface, the above pasted code is the code for this interface, as you can see there are no methods in this interface that’s why these type of interfaces are known as marker interface. They just let the jvm know that what type of object it is, rest JVM takes care of.

There can be a scenario wherein we don’t want to serialize all the fields of a class, and we want some fields should not get serialized, to achieve java provides one more keyword that is transient. All fields maked as transient will not be part of the serialization process.

Since serialization is the process where object’s state is persisted, so obviously the question comes in our mind, what about the static things. Since static variables are directly belong to a class and they don’t have anything to do with object. So the answer is that the static variables are not part of serialization  process as well, since first thing they belong to a class and not with an object and second is they are not part of object state.

SerialVersionUId , whenever we are going to serialize and our class implement serializable interface the IDE says something like this,

The serializable class doesn’t declare a static final serialVersionId of type Long.

So why it is always encouraged to use SerialVersionUID, basically this id is something unique that represents the object and whenever the object is being deserialized this id is being matched and if the id doesnot matches jvm throws InvalidClassException. This id is being placed just to ensure that the object is the same that it was at the time of serialization.

If one doesnot provide the serialVersionUId then the JVM automatically calculate the serialVersionUid and provide one. The same is calculated as the hashcode of the class and the membervariables and so.

One more question arises to our mind is that just above we talked about that the static variables are not part of serialization process since they doesnot belongs to the object state. And now we are talking about that the serialversionUid is used at the time of deserialization, meaning that the serialVersionUID is part of object byte array that is crated at the time of serialization. Its contradictory isn’t it ? Yes !! So what happens is that whenever the object is converted into the sequence of bytes at the time of serialization, then the serialVersionUid is added to the class metadata. And the same is travelled to the network so that whenever the deserialization process happenes the jvm quickly pickup the serialVesrionUID and matches it.

Lets take an example of the same:

First we will create a class name Car which is going to be serialize.

Lets serialize and deserialize, and check if we got the same object or not.

Lets run the code and see if got the same object that we serialize, with make as 2016 and model as Audi-A3.

Upon running the code what we got id:Serialization in Java

So we got the same object that we serialized. This was the code running example of serialization concept.
Back to top

Explain cloning concept, what is difference between shallow and deep cloning in java? Explain with example.

Cloning is a concept where in as the name suggests copy of an existing object is made. There are two types of cloning concepts in java, one is shallow cloning and other one is deep cloning. Both are used to make copy of an object, but there is subtle difference between these two, that we will talk in detail.

To clone some object in java, java provides clone() method, which does the duplication or cloning task. To use the clone method the class must implement Cloneable interface. If class or object whose clone needs to be created, doesnot implement Cloneable interface, jvm throws error. The clone() method is defined in Object class.

By default clone() methods gives shallow copy of the object. If one wants to have deep copy the clone method must be updated.

Shallow and Deep Copy:

Lets understand the concept with help of a diagram:Shallow Vs Deep Copy

Actual Object that have the Object2 in it. Upon performing shallow copy , in memory the objects will look like:Making Shallow Copy in Java

Lets check the memory footprint when deep copy is performed:Making Deep Copy in Java

As demonstrated in diagram, Shallow copy is something where the contents of an object are not duplicated, but the newly created object will also have reference to the existing object. That means if I update some in object1 the same will be reflected in cloned object as well. By default the Object class’s clone methods gives the shallow copy of an object.

Deep copy is the concept where the object is actually duplicated. When deep copy is made there will be two different object created. So in essence when we create deep copy there will be two different object and once we do some modification on object1 the same will never be reflect on object2.

Lets take an example which demonstrates cloning:

Back to top

What are immutable in java, how to create immutable class/fields/methods in java? Explain with example.

Immutable is something that is once created it can not be changed or modified. Immutability is a very important concept in terms of object state. Variables declared as immutable can be treated as constant, since they will never going to change. In java Strings are immutable, mean once declared a string it will never change, if we try to manipulate the string like add some to the same that will result in a new object but the main object will remain intact.

When we are going to create something immutable, final keyword is used. The same can be used with class, fields and methods of a class. There are something to take care or keep in mind when writing final, if a class declared as final the class cannot be extended. If variable is declared with final then the variable will not be reassigned.

When we write final class one thing that is very important and to keep in mind as well is that,

  • Remember the immutable objects cannot be modified so there will be no setters in the class that is going to be final.
  • Class should be declared as final so that no class can extend this.
  • Setting of variable values will be via constructor only.
  • If there is any thing in the immutable class that is mutable, then always always return the copy of it and never the original object.

Lets now create an immutable object, with three fields in it. So the fields will be id, name and a List. Lets create immutable class with these fields:

So our immutable class is ready and good to go. If you check the code properly so the values been set are set via constructor only, since there is no setter for any fields, which should and must not be present. Class is declared as final so that no class can extends this. If one try to extend class then the compiler will throw error. Check the code below compiler throws error in this case.

We have a mutable field List in our code, if we directly return the original object then the caller can change the object, so we are creating a new list and returning the same to calling code.

Back to top

What is equals and hashcode contract. Explain with example.

Both equals and hashcode methods comes with Object class. This class provides these two methods by default overridden with every class we create. Equals as the name suggests checks the equality of two objects, where as hashcode is unique for an object.

Lets see what oracle says about conract between equals and hashcode:

From https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

And about equals method:

We must override equals and hashcode in our class when writing java code. Since the object’s equals method has the following code:

So as you can see this method only checks for references of the object and not the actual object. Lets take a practical example. We are going to create a class that will have some fields and we will not override equals methods and we will check what happens when we call equals method to check equality of both.

Allright so we have created two objects of Home with same parameters and in main methods we are going to check if these both objects are equal or not. Lets run the above program and see if these are equal or not.

Upon running the code above what we got is:Test Equal HashcodeStrange !! isn’t it ? We have created both objects with exact same parameters then how come these two objects are not equal. Remember in the above section we talked about the equals method of object class that the methods only checks the references and not the value, and in memory we have created two different objects, that’s the reason we got output as false upon comparing two objects.

How to solve this now ? Well we need to override equals method and write our equals logic.

Lets write the code for equals now:

So now we have equals method in place in our Home class, lets run the code again and see if it made any difference?Hashcode Test

Now our code is returning the correct output as true. And why it is? Because we have overridden the equals method from super class and added our code for object equality.

That’s the reason it is always advisable to override equals and hashcode methods while writing any class in java.

Back to top
This Java Tutorial Series is continued and you can find more Java Interview Questions in next Web Development Tutorial here.

Top Technical Interview Questions and Answers Series:

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest