Important Core Java Interview Questions and Answers

Core Java Interview Questions and Answers

This is a Collection of very important core java interview questions with answers.

These questions will help students and job seekers to gain confidence to appear and get success in java interviews.

Lot of importance is given to a candidate’s ability to answer core java questions in a java job interview.

For private Online Core Java Training with java interview preparation you may contact me.

Core Java Interview Questions and Answers

1. What is a class?

A class is a user defined datatype. It is a frame of all the objects that can be created using it. A class can contain data properties and functional properties.


2. What is an object?

An object is an instance of a class. Each object will contain its own copies of the instance variables and the functions defined in a class. To create an object we use the new keyword.

  1. Soldier s1=new Soldier();

new Soldier() will create an object and make s1 is a reference variable of Soldier type that refers to the Soldier object created.

3. What is difference between instance variable and reference variable?

The data properties in a class are declared with variables. These variables are called instance variables. Example in the Soldier class we have declared two data properties the x coordinate and the y coordinate representing the location of  a soldier. These data properties are called instance variables.

Each object of the Soldier class will have its own copies of the instance variable. e.g the first soldier object will have its own x and y and the second soldier object will have its own copy of x and y.

Reference variable is the variable that can refer to objects. Eg Soldier s1 is a Soldier type reference variable that can refer to Soldier type of objects.

4. Explain garbage collection in java.

When an object in the memory doesn’t have any reference variable pointing to it, java considers it a useless object, unnecessarily occupying memory. Java periodically searches for such type of hanging objects and removes them from memory. This procedure is called automatic garbage collection. We can tell the jvm to start the garbage collection by calling the function System.gc()

5. What is function overloading?

Function overloading is one type of polymorphism in which the function name is same but the parameter list is different. The number or nature of the parameters may be different.

6. What is a Constructor and its use?

A Constructor is just like a function with the same name as the class name and no return type, not even void. Constructors are generally used to initialize instance variables during object creation.

7. What is this keyword in java?

The keyword “this” refers to the current class object.

8. What is super keyword in java?

The “super” keyword in java refers to the parent class object.

9. What is static keyword in java?

The keyword static can be put in front of a variable , function or a block in java. To access a static variable or a static function we don’t need to create an object. We cann access a static variable or a function directly through the class name e.g classname.function() or classname.variable.
A static variable is shared among all objects of the class.

10. What is the significance of the main function being static?

The function main is the starting point of program execution. There is no need for the jvm to create an object of the class to access the main function. So the main function is made static.

11. What is the use of inheritance in programming?

The main benefit of inheritance is code reusability. The properties of the parent class are available in the child classes. The child class inherit from the parent class using the extends keyword.

12. Does java support multiple inheritance?

Java doesn’t support multiple inheritance through classes but supports through interfaces. Class A extends B,C is not possible but class A implements X,Y is possible provided X and Y are interfaces.

13. What is difference between Path and CLASSPATH?

Path is an environment variable that guides the operating system from where it will search for executable files.

CLASSPATH is an environment variable that helps to educate the JVM from where it will start searching for .class files. generally we store the root of the package heirarchy in the CLASSPATH environment variable.

We also store the location of external jar files in the environment variable, so that the jvm can locate the class files within it.

14. What is function overriding?

Same function name and same parameter list, and can happen during inheritance only.

15. Explain run time polymorphysm.

Java resolves dynamically at run time, which function to call, based on which sub class is referred by the super class reference variable just before the function is called.
Figure f=new Rectangle(); f.area();
In the above code the area of the rectangle class get called because just before the function is called, the reference variable is pointing to a Rectangle object.

16. What is an abstract class?

Any class can be made abstract by just putting the abstract keyword in front of the class. But if a class contains one or more abstract functions, we are bound to make the class abstract.

We cannot create an object of an abstract class.

Abstract classes are generally used to create the frame of the project, or the top level class.

Subclass of an abstract class has to provide implementation of all the abstract functions present in the super class, else the subclass will also become abstract.

We can also implement run time polymorphism through abstract classes.

17. What is Object class?

Object class is an inbuilt class present in the java.lang package. It is the super class of all classes in java.

Whenever we create a class, by default it is the subclass of the object class. We can override non final functions of the Object class in any class eg toString(), equals() etc.

18. What is the use of toString function?

The toString function gets automatically inherited in all java classes from the Object class. We can override the toString function. When ever we print an object of a class, by default the toString function of the class gets called. So if we want to give a customizable output when printing an object, we can override the toString function.

19. Explain about different access specifiers.

The different access specifiers are public, private, protected and the default.

private properties are accessible from only within the same class.

public properties are accessible from anywhere.

no modifier properties are accessible only from within the same package.

protect properties are accessiable from the same package, but out side the package it is accessiable provided it is done from a sub class.

20. What are the differences between an abstract class and an interface?

An abstract class can contain both function definitions and function declarations, but an interface can contain only function declarations.

An abstract class is extended by using the extends keyword while an interface is implemented using the implements keyword.

Multiple inheritance is not supported through classes or abstract classes but is supported through interfaces.

21. What is final keyword in java?

The final keyword in java can be used infront of a variable, function or a class.

If a final keyword is placed infront of a variable, it acts like a constant. It cannot be modified.

Eg final int YES=100;

By convention final variables are in upper case. They are declared and initilized in the same line.

Function defined as final cannot be overridden in the subclasses.

Classes defined as final cannot be subclassed or inherited.

22. What are wrapper classes, and their use?

Java provides special classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.

Most of the collection classes store objects and not primitive data types. Wrapper classes also provide many utility methods. And since we create instances of these classes we can store them in any of the collection classes and pass them as a collection. Also we can pass them as method arguments where a method expects an object.

23. What is an exception in java?

Exceptions are run time errors. e.g int i=1/0; This code doesn’t show any error during compile time, but when we run the code we get an ArithmeticException.

24. What is exception handling?

When we run a program that has error, java creates an appropriate exception type of object and throws it. Then the default exception handler of java handles the exception. But the default exception handler stops the program execution abruptly and gives a non understandable output.
So we are not satisfied by the default exception handler’s exception handling. So we want to handle the exception on our own so that the program will not stop abruptly and also give a non understandable output. We can do exception handling on our own using try and catch block.

25. What is the use of printStackTrace() method?

It helps to trace the exception step by step. It helps to find how the exception occured step by step.

26. Explain custom exception class.

We need a custom exception class to represent a custom problem. There are many inbuilt exception classes in java like ArithmeticException that represents arithmetic problems, ArrayIndexOutOfBounds exception to represent array related problems. But we need custom exception classes to represent custom problems, or our own problems. e.g ProductNotFoundException is a custom exception class representing a problem which occurs if a product is not found during the search. To create a custom exception class we have to extend the inbuilt Exception class.

27. Explain the use of throw keyword.

The throw key word is used to manually throw exception objects. If there is a division by zero or array problem java creates an appropriate exceptin object and throws it. But if there is a custom problem, java will not throw the exception but we have to manually throw the exception objects on our own using the throw keyword.


Here NoProductFoundException is a custom exception class. If product is not found then we are manually creating an object of NoProductFoundException class and throwing it using throw keyword.

28. What is the use of throws keyword?

The throws keyword is used to delegate the exception handling mechanism to the caller of the function. When we define a function and we don’t want to put try and catch block than we can use throws keyword. The caller of the function has to put the try and catch blocks, or handel the exception.


29. What is the difference between checked and unchecked exceptions?

Checked exceptions are those exceptions that cannot be handled by the default exception handler of java. So we have to manually handle the exception using try catch block. All the custom exceptions are checked exceptions.

Unchecked exceptions are those exceptions that can be handled by the default exception handler of java. eg ArithmeticException, NullpointerException etc.

Please check again we are updating this with more Core Java interview questions

Why Multiple Inheritance in Java not supported?

Multiple Inheritance in Java is not supported

For making Java language simple and avoid complexities present in earlier languages like c++, the founder of java(James Gosling) decided that java shouldn’t support Multiple Inheritance.

In a white paper titled “Java: an Overview” James Gosling gives an idea on why multiple inheritance is not supported in Java.

Gosling on omission of Multiple Inheritance in Java

“JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. This primarily consists of operator overloading (although it does have method overloading), multiple inheritance, and extensive automatic coercions.”

Ambugity problem due to Multiple Inheritance

If we try to do multiple inheritance in java we will come across an ambiguity problem. We will discuss about it below using an example.

Multiple Inheritance in Java is Not Supported

We have a super class A having a function called fun().
Two subclasses B and C extend class A providing their own implementation of fun() function.

Assume class D inherits from class B and class C.
If we create an object of class D and try to access function fun() guess what will happen.
i.e D obj=new D();;

This will lead to ambiguity problem. Because it’s difficult for java to decide which version of fun() function to execute, fun() of class B or fun() of class C. The above problem is also referred as diamond problem.

In c++ we have multiple inheritance and the problem is resolved using scope resolution operator. But java founders wanted to keep java simple and avoid complexities. Concepts like pointers, operator overloading are also avoided in java language for the same reason.

Multiple Inheritance in Java is not much required

Extending from two different classes having different implementations of a function is not much required in real world.

Ejb1 vs Ejb2 vs Ejb3 | JavaTutorOnline

Ejb1 vs Ejb2 vs Ejb3

Ejb1 had limited functionality just as a lady bug that doesn’t do much work still is appreciated by people due to its beauty.

Ejb2 was very heavy like the Elephant with functionalities. Still to take proper use of the elephant power it had to be tamed, or Ejb2 was later simplified to Ejb3

Ejb3 is very simple having power and is serving the people very well like a cow giving milk to the universe.

Overview of EJB

Ejb is a platform for building ,reusable, portable and scalable business applications using java.

Ejb helps developers to concentrate on building business logic code without having to build infrastructure code comprising of functionalities including transactions, security, automated persistence that are provided by the Ejb container.

Ejb as Component

Ejbs are server side components that you can use to build parts of an application like business logic or persistence code. These components in Ejb3 are simple POJO with special power. Component means that the user need not know the inner working of the Component, he only needs to know what he has to give and what the Component will give you i.e. application behavior has to be completely encapsulated from the outside world.

There are 3 types of Ejbs. Session beans taking care of business logic. Entity Bean used for persistence. Message driven beans.

One of the most important use of Ejbs is its reusability. E.g. If there is a site for online books that is using an Ejb code for checking credit card. Then if we create another Website for CDs then we can reuse the same credit card Ejb. The first Ejb can be put as an Ejb component or a web service that is used by both applications.

uses Credit card Ejb

Ejb as Framework

The Ejb Container houses the Ejb components we develop. This Ejb Container together with the Ejb Component act as a Framework with predefined functionalities. This relieves the programmer from coding certain areas like transaction, security and persistence that are provide by the Ejb Container itself. Like if a programmer is creating a bean related to processing a credit card he need not create coding for the Transaction and Security that is provided by the Ejb Container Automatically.

We can use metadata annotations in our beans to specify what all services and functionalities we require. These are added dynamically when required during deployment. Metadata annotations is a way to specify the properties in a POJO, and these functionalities get automatically added. So we can say a POJO + Metadata annotation=Ejb3 bean. So we don’t need any outside xml configuration files.

Ejb is a specification which is followed by a large group of user vendors creating application server. So all have to follow the same specification making our applications portable.

Domain Driven Design

DDD is the preferred way as compared to the traditional four tired architecture followed by Ejb 2.

Following DDD the domain objects should contain buisness logic and shouldn’t be just a replica of database record. Incase of Ejb 2 beans were not POJOS and didn’t support OO features like inheritance, polymorphism.

Ejb3 helps follow DDD. Beans created using Ejb3 JPA supports polymorphism, inheritance etc.

Why choose EJB 3 among other technologies

Ease of use, Integrated solution stack— Ejb3 offers a complete stack of server solutions, including persistence, dependency injection, interceptors i.e. we won’t need to look for third party solutions to integrate in our application.

Ant Java Build Tool Tutorial | JavaTutorOnline

Ant Java Build Tool

Ant is a Java build tool. It is an open source program designed to help develop, and build big programs by automating the work tasks of compiling code, running tests, and Packaging the results for redistribution.

It is written completely in Java there by it is platform independent, easy to use, extensible, and scalable. It can be used in a small personal project, or it can be used in a large, project. It automates the entire build process.

In Ant build files are used to describe how to build a project. In the build file

developers list the high-level goals called the targets and actions to take to achieve each goal called the tasks. Each project contains multiple targets. Targets can depend on other targets. Targets contain tasks and Tasks do the work

Working with ANT

First ANT has to be downloaded and installed in the developers machine. Then the Path of the computer should be set to point to the bin directory of ANT. An environment variable called ANT_HOME should also be made in the System variables pointing to the installation directory of ANT.

A build.xml file should be created that will contain several targets that will further contain different tasks.

1) Target containing Tasks for creating build/classes directory to contain compiled files and creating a dist folder to contain the jar or war file of the project.

2) A Target to compile the java files in the source folder and put it into the build/classes folder.

3) A Target that will package the project to a jar or war file.

4) A Target to create the java docs of the project.

5) A Target to run all the tests on the project.

6) A Target to run the class file containing the main method.

After following the steps the user can simply type ant on the command line and ANT will read the “build.xml” and execute all the targets.

Some of the very important benefits of ANT are as follows:

Ant is free and Open Source. Ant makes it easy to bring developers into a project. It is widely supported. It integrates testing into the build processes and enables continuous integration. It runs inside Integrated Development Environments

Java Exception Handling Tutorial| How to Handle Exceptions in Java

What are Exceptions in Java?

An Exception in java is an object  that describes an exceptional condition in the program. A java exception object may be either generated in the code manually or automatically by the java run time system.

Java Exception Hierarchy

All types of java exceptions are subclass of the inbuilt class Throwable.  The two sub classes of Throwable are Exception and Error. The branch Exception deals with those exceptional conditions that the user program should handle. Exception further branches into RunTimeException and Checked Exceptions. RuntimeExceptions are those exceptions that are automatically defined for the programs that we write, like ArithmeticException, NullPointerException etc. The other branch is Error, which defines exceptions that are not expected to be handled by our program.

Java Exception Handling Hierarchy

A java program passes through compile time and run time. Exceptions are run time errors.

Exception is an inbuilt class in the java.lang package. There are many sub classes of Exception class like ArithmeticException, NullpointerException etc.

Depending upon the nature of the problem occurring during run time, java creates the appropriate Exception object and throws it.

For example:   int i = 1/0;  [Java will throw ArithmeticException type of object]

Why do we need to do Java Exception handling?

Java’s Default exception handlers  doesn’t do the work properly, they stop the program execution abruptly and gives  a weird output to the user. This is the reason why we should do exception handling. To do java exception handling  we have to use try and catch blocks. The lines of code that may throw some exception should be put in the try block and whatever we want to be done should be put in to the catch block.


Here, by doing 1/0, our program will stop abruptly. And it will give a weird error message. Like,


But on using try and catch the problem is overcome.

Try Catch Block in Java Exception Handling

  • Try Block– Those code that may lead to exceptions during run time are generally put inside the try block.
  • Catch Block– What ever we want to do when ever any exception occurs should be put in the catch block.

Due to the use of try catch block the above program will not stop abruptly, rather it will give a customized exception message during run time.

Multiple catch blocks

There are many sub classes of the class Exception like ArithmeticException, NullPointerException etc. During run time different type of exception may occur depending on different conditions. So to handle the problems differently in different circumstances we need to have multiple catch blocks.

In this example, if length is 0 than it will be caught by catch block handling ArithmeticException. If we go out of the range of the array an ArryIndexOutOfBoundException is thrown. Programs may have various type of exceptions which can be handled through multiple catch blocks. In this example third catch block is for general Exception type. The general Exception catch block should be put at the end.

How to Create Custom Exception Class?

There are some situations that is not an exception for java but it is an exception for our project. For example if you want to run your program only when user gives commandline input (this is your program need which is not an exception for java) so, this is the time when we manually create our own exception class. To create a custom exception we have to extent the inbuilt Exception class.

Throw Keyword

Throw keyword is used for manually throwing java exception objects.

When a custom exception object is thrown it has to be handled through try and catch blocks because it cannot be handled by the default exception handler of java.

Throws Keyword

When we define a function and we don’t want to put try and catch block than we can use throws keyword. The caller of the function has to put the try and catch blocks. Throws keyword is for delegating the exception handling mechanism to the caller of the function.


Checked and unchecked exception

Unchecked exceptions are those exceptions that can be handling by java’s default exception handlers. If we try to throw unchecked exception inside a function we don’t need to put try and catch block nor the throws.

Checked exceptions are those exceptions that can’t handle by java’s default exception handlers.
When a checked exception is thrown from inside a function we are bound to put the try and catch block or the throws declaration.

List of checked exceptions

ClassNotFoundExceptionClass not found
CloneNotSupportedExceptionAttempt to clone an object that does not implement the Cloneable interface
IllegalAccessExceptionAccess to a class is denied
InstantiationExceptionAttempt to create an object of an abstract class or interface
InterruptedExceptionOne thread has been interrupted by another thread
NoSuchFieldExceptionA requested field does not exist
NoSuchMethodExceptionA requested method does not exist

List of unchecked exceptions

ArithmeticExceptionArithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds
ArrayStoreExceptionAssignment to an array element of an incompatible type
ClassCastExceptionInvalid cast
IllegalArgumentExceptionIllegal argument used to invoke a method
IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked thread
IllegalStateExceptionEnvironment or application is in incorrect state
IllegalThreadStateExceptionRequested operation not compatible with current thread state
IndexOutOfBoundsExceptionSome type of index is out-of-bounds
NegativeArraySizeExceptionArray created with a negative size
NullPointerExceptionInvalid use of a null reference
NumberFormatExceptionInvalid conversion of a string to a numeric format
SecurityExceptionAttempt to violate security
StringIndexOutOfBoundsAttempt to index outside the bounds of a string
UnsupportedOperationExceptionAn unsupported operation was encountered