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 PDF version will be available later for download.
Following Related Technical Interview Questions and Answers will also be helpful.
Complete Java Interview Questions List
- What is object oriented programming. How java differs from other object orienting programming languages like C++?
- Explain installation and environment setup of java. Briefly explain what is JRE,JDK and JVM?
- What is polymorphism, Explain inheritance in java? Also explain overloading and overriding in java.
- What are different types of class loaders in java, explain class loading in java?
- What is difference between composition and aggregation?
- What is difference between abstract class and interface in java, also explain when to use what?
- Explain Serialization in java, what is use of Serial Version UID?
- Explain cloning concept, what is difference between shallow and deep cloning in java? Explain with example.
- What are immutable in java, how to create immutable class/fields/methods in java? Explain with example.
- What is equals and hashcode contract. Explain with example.
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.
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:
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:
Now click on Advance system settings link that is on the left pen of this page, this will open a window like this:
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:
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:
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.
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.
package com.javatutorial.polymorphism; public interface ICar { void setEngineCapacity(String engineCapacity); String getEngineCapacity(); }
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.
public class AudiImpl implements ICar { @Override public void setEngineCapacity(String engineCapacity) { // } @Override public String getEngineCapacity() { return null; } }
Now lets create BMWImpl class with our ICar interface implementation.
package com.javatutorial.polymorphism; public class BMWImpl implements ICar { @Override public void setEngineType(String engineType) { // } @Override public String getEngineType() { return null; } }
Lets create a Main class and try to understand the IS-A concept that is behind Polymorphism.
package com.javatutorial.polymorphism; public class Main { public static void main(String[] args) { ICar carAudi = new AudiImpl(); ICar carBMW = new BMWImpl(); getCarEngine(carAudi); } private static String getCarEngine(ICar car){ return car.getEngineType(); } }
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.
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.
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.
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.
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:
package com.javatutorial.polymorphism; public class Bike { private final Tyre type; public Bike(){ type = new Tyre("MRF"); } } class Tyre { private String brand; public Tyre(String brand){ setBrand(brand); } public void setBrand(String brand){ this.brand = brand; } public String getBrand(){ return brand; } }
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.
import java.util.ArrayList; import java.util.List; public class Company { List<Department> departmentList = new ArrayList<>(); } class Department{ String deptName; //getters and setters }
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:
public interface IVehicle { String getBrand(); String getModel(); String getEngineCapacity(); String getFuelType(); }
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:
public abstract class AbstractDieselVehicle implements IVehicle { @Override public String getFuelType() { return "Diesel"; } } public abstract class AbstractPetrolVehicle implements IVehicle { @Override public String getFuelType() { return "Petrol"; } }
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.
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.
public interface Serializable { }
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.
class Car implements Serializable{ private static final long serialVersionUID = 3L; private String model; private String make; public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } @Override public String toString() { return "Car{" + "model='" + model + '\'' + ", make='" + make + '\'' + '}'; } }
Lets serialize and deserialize, and check if we got the same object or not.
package com.javatutorial.serialization; import java.io.*; public class MainSerialization { public static void main(String[] args) throws IOException, ClassNotFoundException { Car car = new Car(); car.setMake("2016"); car.setModel("Audi-A3"); //Serialize ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.ser")); oos.writeObject(car); //Deserialize ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser")); Car objCar = (Car) ois.readObject(); System.out.println("Car object : " + objCar); } }
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:
So we got the same object that we serialized. This was the code running example of serialization concept.
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:
- Top 20 AngularJS Interview Questions
- Advanced Angular2 Interview Questions
- Top 15 Bootstrap Interview Questions
- ReactJS Interview Questions and Answers
- Top 10 HTML5 Interview Questions
- Must Have NodeJS Interview Questions
- BackboneJS Interview Questions
- Top 10 WCF Interview Questions
- Comprehensive Series of WCF Interview Questions
- Java Spring MVC Interview Questions
The post MUST Have Core Java Interview Questions appeared first on Web Development Tutorial.