Core Java Interview Questions with Answers

What is object-oriented programming?

Object-oriented programming organizes a program around its data(i.e. objects) and a set of well-defined interfaces to that data. An object-oriented program can be characterized as “data controlling access to code”.

What is an object?

The object is an real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword.

What are the four main principles of OOP?

The four main principles that make an language Object Oriented are :

Abstraction is the concept of OOP that “shows” only essential attributes and “hides” unnecessary information. Using abstract class/Interface we express the intent of the class rather than the actual implementation.

abstract class Bike{
  abstract void run();
}
class Honda4 extends Bike{
  void run(){
    System.out.println("running safely");
  }
  public static void main(String args[]){
    Bike obj = new Honda4();
    obj.run();
  }
}
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by the Honda class.

Inheritance expresses “is-a” and/or “has-a” relationship between two objects. Inheritance is the procedure in which one class inherits the attributes and method of another class.

Polymorphism is the ability of programming language to present the same interface for several different underlying data types. It basically means “one name many forms”. There are two types of polymorphism - Static polymorphism is achieved by using method overriding and Dynamic polymorphism is achieved by using method overloading.

class Shapes {
  public void area() {
    System.out.println("The formula for area of ");
  }
}
class Triangle extends Shapes {
  public void area() {
    System.out.println("Triangle is ½ * base * height ");
  }
}
class Circle extends Shapes {
  public void area() {
    System.out.println("Circle is 3.14 * radius * radius ");
  }
}
class Main {
  public static void main(String[] args) {
    Shapes myShape = new Shapes();  // Create a Shapes object
    Shapes myTriangle = new Triangle();  // Create a Triangle object
    Shapes myCircle = new Circle();  // Create a Circle object
    myShape.area();
    myTriangle.area();
    myShape.area();
    myCircle.area();
  }
}
A superclass named “Shapes” has a method “area()”. Subclasses of “Shapes” can be “Triangle”, “circle”, “Rectangle”, etc. Each subclass has its way of calculating area. Using Inheritance and Polymorphism, the subclasses can use the “area()” method to find the area’s formula for that shape.

Encapsulation refers to the hiding of data implementation by restricting access to public methods. Encapsulation bundles the data with the methods that operate on that data. It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities.

class A {
  private int x = 20;
}
class B extends A {
  int y = 50;
}
class C extends A {
  private int z = 10;
}
Here, Class A and Class C are tightly encapsulated classes. Class B is not a tightly encapsulated class because of non-private variable y. Anyone can access it directly from outside the class.

What is the Constructor? How many types of constructors are used in Java?

A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes.

There are two types of constructors in Java:

Default Constructor When you do not explicitly define a constructor for a class, then Java creates a default constructor for the class. The default constructor automatically initializes all instance variables to zero. Once you define your own constructor, the default constructor is no longer used.

Parameterized Constructor is the one which can initialize the instance variables with the given values. In other words, we can say that the constructors which can accept the arguments are called parameterized constructors.

Explain this and super keywords in java?

Sometimes a method will need to refer to the object that invoked it. To allow this java uses this keyword. this is a reference to the object on which the method was invoked.

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you create the instance of the subclass, an instance of the parent class is created implicitly which is referred by super reference variable.

class Main {
    int v;

    Main(int v){
        this.v = v;
        System.out.println("this reference = " + this);
    }

    public static void main(String[] args) {
        Main obj = new Main(8);
        System.out.println("object reference = " + obj);
    }
}
this reference = Main@23fc625e
object reference = Main@23fc625e

In the above example, we created an object named obj of the class Main. We then print the reference to the object obj and this keyword of the class. Here, we can see that the reference of both obj and this is the same. It means this is nothing but the reference to the current object.

Explain final, finally, and finalize keyword in java?

final keyword can be used with class, variables, and methods. A final class cannot be inherited, a final method cannot be overridden and a final variable cannot be reassigned.

finally keyword is used to create a block of code that follows a try-catch block. A finally block of code always executes, whether or not an exception has occurred.

finalize method is used just before object is destroyed, it is used for clean up processing just before object is garbage collected.

What is method overloading? Why method overloading is not possible by changing the return type in java?

Method overloading is the polymorphism technique that can be achieved — by changing the number of arguments and by changing the data type of an arguments. Method overloading increases the readability of program.

In java, method overloading is not possible by changing the return type of the program because it introduces ambiguity.

class Adder{
    static int add(int a, int b){
        return a+b;
    }
    static double add(int a, int b){
        return a+b;
    }
}
class Test{
    public static void main(String[] args){
        System.out.println(Adder.add(11,11));       // Ambiguity
    }
}
Compile Time Error (Reason : System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be called?)

What is method overriding? Can we override the static method?

In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. Method overriding forms the basis for one of Java’s most powerful concepts: dynamic method dispatch. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism.

No, we can’t override the static method because the static method is the part of the class, and it is bound with class whereas instance method is bound with the object, and static gets memory in class area, and instance gets memory in a heap.

Explain static variable, static method, static block? Why is the main method static?

Static Variable is used to refer to the common property of all objects, it belongs to the class rather than object. Static variables make your program more efficient.

Static Method belongs to the class rather than the object. A static method can access and change the value of the static variable.

Static Block is a block of code which contains code that executes at class loading time. It helps to initialize the static data member.

class Test{
    static int a = 3;
    static int b;
    static void m(int x){
        System.out.println("x = " + x);
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
    static{
        System.out.println("Static block initialized.");
        b = a*4;
    }
    public static void main(String[] args){
        m(42);
    }
}
Static block initialized.
x = 42
a = 3
b = 12

As soon as the Test class is loaded, all of the static statements are run. First, a is set to 3, then the static block executes, which prints a message and then initializes b to a*4 or 12. Then main( ) is called, which calls m( ), passing 42 to x. The three println( ) statements refer to the two static variables a and b, as well as to the local variable x.

Main method is static because the object is not required to call the static method. If we make the main method non-static, JVM will have to create its object first and then call main() method which will lead to the extra memory allocation.

What is the Inheritance? What are the advantages of Inheritance in Java?

Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

There are five types of inheritance in Java - Single-level inheritance, Multi-level inheritance, Multiple Inheritance, Hierarchical Inheritance, Hybrid Inheritance.

Advantages of Inheritance in java are -

Runtime polymorphism cannot be achieved without using inheritance.

Inheritance provides data hiding.

Inheritance provides code reusability.

Method overriding cannot be achieved by inheritance.

Why multiple inheritance is not supported in java?

Java doesn’t support multiple inheritance because of two reasons -

  1. In Java, every class is a child of object class. When it inherits from more than one super class, subclass gets the ambiguity to acquire the property of Object class.

  2. In Java, every class has a constructor

class A{
    void msg(){
        System.out.println("Hello");
    }
}
class B{
    void msg(){
        System.out.println("Welcome");
    }
}
class C extends A,B{
    public static void main(String[] args){
        C obj = new C();
        obj.msg();
    }
}
Compile time error

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have the same method or different, there will be a compile time error.

What is static and dynamic polymorphism?

Static Polymorphism is a polymorphism that is resolved during compile time, method overloading is an example of compile time polymorphism. Method overloading allows us to have more than one method having the same name.

class Calculator{
  int add(int a, int b){
    return a+b;
  }
  int  add(int a, int b, int c){
     return a+b+c;
  }
}
public class Test{
  public static void main(String[] args){
    Calculator obj = new Calculator();
    System.out.println(obj.add(10, 20));
    System.out.println(obj.add(10, 20, 30));
  }
}
30
60

Dynamic Polymorphism is a process in which a call to an overridden method is resolved at runtime, it is also called as runtime polymorphism. Method overriding is an example of runtime polymorphism.

class ABC{
   public void myMethod(){
	System.out.println("Overridden Method");
   }
}
public class XYZ extends ABC{

   public void myMethod(){
	System.out.println("Overriding Method");
   }
   public static void main(String args[]){
	ABC obj = new XYZ();
	obj.myMethod();
   }
}
Overriding Method

Explain static binding and dynamic binding?

In static binding, the type of the object is determined at compile-time whereas, in the dynamic binding, the type of the object is determined at runtime.

Static Binding

class Dog{
  private void eat(){
    System.out.println("Dog is eating.");
  }
  public static void main(String[] args){
    Dog d1 = new Dog();
    d1.eat();
  }
}

Dynamic Binding

class Animal{
  void eat(){
    System.out.println("animal is eating...");
  }
}
class Dog extends Animal{
  void eat(){
    System.out.println("dog is eating...");
  }
  public static void main(String args[]){
    Animal a=new Dog();
    a.eat();
  }
}

What is the abstraction? What is the abstract class? Can there be an abstract method without an abstract class?

Abstraction is a process of hiding the implementation details and showing only functionalities. It helps you to focus on what the object does instead of how it does it. There are two ways to achieve abstraction : Abstract Class and Interface.

A class declared as abstract is known as an abstract class. It needs to be extended and its method implemented. It cannot be instantiated. It can have abstract methods, non-abstract methods, constructors, and static methods. It can also have the final methods which will force the subclass not to change the body of the method.

No, if there is an abstract method in a class, that class must be abstract.

What is the interface? How to declare an interface?

An interface is the blueprint of the class. It has static constants and abstract methods. Interface is used to achieve abstraction and multiple inheritance in java. It also represents IS-A relationship.

To declare an interface we’ve to use interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.

What are the differences between abstract class and interface?

Abstract ClassInterface
The abstract class can provide the implementation of the interface.The interface can’t provide the implementation of the abstract class.
An abstract class can have instance variables.An interface can’t have instance variable.
An abstract class can have the constructor.The interface can’t have the constructor.
An abstract class can have static methods.The interface can’t have static methods.
A Java abstract class can have class members like private, protected, etc.Members of a Java interface are public by default.
The abstract keyword is used to declare an abstract class.The interface keyword is used to declare an interface.
An abstract class can be extended using keyword extends.An interface class can be implemented using keyword implements.

What is the encapsulation? What are the benefits of encapsulation?

Encapsulation is a mechanism of wrapping the data and code acting on the data together as a single unit. To achieve encapsulation we’ve to declare the variables of a class private and provide public setter and getter methods to modify and view the variables values.

Benefits of encapsulation -

It’s easy to perform unit testing through encapsulation.

It provides you the control over the data.

We can make the class read-only or write-only with the help of setter and getter methods.

What is Exceptional Handling? How many types of exceptions are there in java?

Exception Handling is a mechanism that is used to handle runtime errors. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

There are mainly two types of exceptions: checked and unchecked. Here, the error is considered as the unchecked exception. Checked Exception are the classes that extend Throwable class except RuntimeException and Error are known as checked exceptions, e.g., IOException, SQLException, etc. Checked exceptions are checked at compile-time. Unchecked Exception are the classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, etc. Unchecked exceptions are not checked at compile-time.

Explain the workflow of try, catch, throw, throws and finally?

Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception using catch and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run- time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.

Why String objects are immutable in java?

Java uses the concept of string literal. Suppose there are three or more reference variable, all refer to one object “dog”. If one reference variable changes the value of the object, it’ll be affected by all the reference variables. That is why String objects are immutable in Java. Features of string which makes string objects immutable.

ClassLoader in Java uses a String object as an argument. Consider, if the String object is modifiable, the value might be changed and the class that is supposed to be loaded might be different. String is immutable to avoid this kind of misunderstanding.

Thread Safe as the String object is immutable we don’t have to take care of the synchronization that is required while sharing an object across multiple threads.

Security Immutable String objects, like class loading, avoid subsequent mistakes by loading the correct class. As a result, the application programme becomes more secure.

Heap Space String’s immutability helps to keep heap memory use to a minimum. The JVM checks whether the value already exists in the String pool when we try to declare a new String object. If it already exists, the new object is given the same value. This feature allows Java to make optimal use of memory space.

What is serialization and deserialization?

In Java, serialization is a method of writing an object’s state to a byte stream. Hibernate, RMI, JPA, EJB, and JMS technologies all make use of it. It is mostly used to travel the state of objects on the network (which is known as marshaling). Serializable interface is used to perform serialization. It proves useful when you need to save the current state of a programme to a file. At a later point of time, the content of this file can be restored using deserialization. A class can become serializable by implementing the Serializable interface. Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization.

What are Wrapper classes? When autoboxing and unboxing occurs?

Wrapper classes are classes that allow primitive types to be accessed as objects. In other words, we can say that wrapper classes are built-in java classes which allow the conversion of objects to primitives and primitives to objects. The process of converting primitives to objects is called auto-boxing, and the process of converting objects to primitives is called unboxing. There are eight wrapper classes Boolean, Character, Byte, Short, Integer, Long, Float, Double.

Autoboxing and Unboxing can occur when we expect wrapper class object, and primitive data type is provided or vice versa.

  • Adding primitive types into Collection like ArrayList in Java.
  • Creating an instance of parameterized classes.
  • Java automatically converts primitive to object whenever one is required and another is provided in the method calling.
  • When a primitive type is assigned to an object type.

What is a singleton class?

A singleton class is a class that can have only one object at a time. After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created. To make a class singleton, we either make its constructor private or use the static getInstance method.

class Database {
   private static Database dbObject;

   private Database() {      
   }

   public static Database getInstance() {

      // create object if it's not already created
      if(dbObject == null) {
         dbObject = new Database();
      }

       // returns the singleton object
       return dbObject;
   }

   public void getConnection() {
       System.out.println("You are now connected to the database.");
   }
}

class Main {
   public static void main(String[] args) {
      Database db1;

      // refers to the only object of Database
      db1= Database.getInstance();
      
      db1.getConnection();
   }
}