CodingJump border
Java Interview Questions
Published on

Java Interview Questions


In this post, you’ll find some of the most important interview questions for Java. Most of the questions would relate to the Java language, for example, String Pool, intern() function, classes, inheritance, etc. All the questions related to Java Collections would be present in a different blog post.

Table of Contents

What is Java?

Java is an object-oriented, robust, secure, platform-independent, high-performance, Multithreaded, and portable programming language.

What is JVM?

JVM interprets the Java Bytecode that is machine-independent and close to the native code.

What is JIT?

JIT takes care of converting the instruction set of a Java virtual machine (JVM) to a specific CPU instruction set. JIT compiles parts of the bytecode with similar functionality simultaneously and reduces the amount of time needed for compilation.

What is a class loader?

The class loader is a subsystem of JVM which is used to load class files.

What are the types of class loaders?

  1. Bootstrap ClassLoader – rt.jar, which contains all the Java standard classes like java. util, java.lang,,, etc.
  2. Extension ClassLoader – Java loads all the required JRE extension jar files in %JAVA_HOME%/jre/lib/ext folder
  3. System ClassLoader – Loads all required jar files from Application classpath

What is JRE?

JREs complete form is Java Runtime Environment. It is the implementation of JVM. It contains a set of libraries + other files that JVM uses at runtime.

How many types of memory can be allocated in Java?

  1. Class (Method) Memory
  2. Heap
  3. Stack
  4. Program Counter
  5. Native Method Stack

Different types of Constructors in Java?

  1. Default Constructor
  2. Parameterized Constructor

Do we have a copy constructor in Java?

Java doesnt off the self-support copy constructor, but we can create it ourselves.

class Complex {
    private double re, im;

    public Complex(double re, double im) { = re; = im;

    // copy constructor
    Complex(Complex c) {
        re =;
        im =;

public class Main {
    public static void main(String[] args) {
        Complex c1 = new Complex(10, 15);
        Complex c2 = new Complex(c1); // calling copy constructor

Does the overriding of hashCode() method have any performance implication?

A poor hash code function will result in frequent collisions in HashMap, which eventually will increase the time for adding an object into HashMap. From Java 8 onwards, though, collision will not impact performance as much as it does in earlier Java versions because after a threshold, the linked list will be replaced by a binary tree, which will give you O(logN) performance in the worst case as compared to O(n) of a linked list.

What is the latest LTS version of Java?

Java 11 which launched in September 2018.

What is the release cycle for Java?

Java has a 6 months release cycle, i.e., March & September. And every 3 years, there is an LTS release. The next LTS release will be in September 2021, which will be Java 17.

What is the static block?

A static block is used to initialize the static data member of the class. It is executed before the main method at the time of classloading.

class StaticBlock{
    static{System.out.println("static block is invoked");}
    public static void main(String args[]){
        System.out.println("Hello main");

Can we execute a program without the main() method?

No, It was possible before Java 7 using the static block. Since Java 7, it is not possible.

What will be the initial value of an object reference which is defined as an instance variable?

All object references are initialized to null in Java.

Can we make constructors static?

Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error. If we want to initialize static values to the inner static class, we can use static blocks.

Can we make the abstract methods static in Java?

No. In Java, if we make the abstract methods static, It will become part of the class, and we can directly call it without instantiating an object, which is unnecessary. Calling an undefined method is entirely useless therefore, it is not allowed.

Can we have a static keyword in a top-level class?

No, in Java we cannot have static defined on class unless it’s an inner class.

Access modifiers in Java?

  1. Default
  2. Private
  3. Protected
  4. Public

How is Protected in Java different from C#?

Protected in Java also gives access to the package automatically – there’s nothing in Java that is as restrictive as C#’s protected (in terms of only being available within subclasses).

Can we declare the static variables and methods in an abstract class?

Yes, we can declare.

What is this keyword in java?

this keyword is a reference variable that refers to the current object.

Can this keyword be used to refer to static members?

Yes, we can use this keyword to refer to static members. However, you dont need to declare an object to refer to, not recommended for best practice.

What is constructor chaining in Java?

Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object.

public class Employee
    int id,age;
    public Employee (int age)
        this.age = age;
    public Employee(int id, int age)
        this(age); = id;

The same chaining concept can be used for the call base class constructor.

class Person
    String name,address;
    int age;
    public Person(int age, String name, String address)
        this.age = age; = name;
        this.address = address;
class Employee extends Person
    float salary;
    public Employee(int age, String name, String address, float salary)
        this.salary = salary;

What is Inheritance?

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. There are five types of inheritance in Java.

  • Single-level inheritance
  • Multi-level inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance Multiple inheritance is not supported in Java through class.

What is aggregation in Java?

Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to another class it owns. For E.g. Employee class has reference to the Address object

What is a composition in Java?

When an object contains the other object, it cannot exist without the existence of a container object. E.g., A class contains students. A student cannot exist without a class. There exists composition between class and students.

What is super in Java?

The super keyword in Java is a reference variable used to refer to the immediate parent class object.

What is method overloading with type promotion?

By Type promotion is method overloading, we mean that one data type can be promoted to another implicitly if no exact matching is found.

class TypePromotion{
  void sum(int a,long b){System.out.println(a+b);}

  public static void main(String args[]){
  TypePromotion obj=new TypePromotion();
  obj.sum(20,20);//now second int literal will be promoted to long

What is the difference between method overloading vs overriding?

For overloading the parameters are different and present in the same class whereas for overriding the parameters are the same, the methods are present parent & subclasses.

Can we override the static method?

No, you can’t override the static method because they are part of the class, not the object.

Can we override the private methods?

No, as those are not visible to subclasses.

Can we change the scope of the overridden method in the subclass?

Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method.

What is the use of the final keyword in Java?

The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override)

Can you declare the main method as final?

Yes, you can declare.

public static final void Main(string[] args)
// Code Here

Can we declare a constructor as final?

No, you cannot declare constructors as final as they can never be inherited. They are not like normal methods. However, if you try to do so, The compiler will throw an error.

Can abstract methods be declared as final?

No, it is not possible, as they need to be implemented by the child classes, making no sense to make them final.

Can we declare an interface as final?

We cannot declare an interface as final because some classes must implement it to provide its definition.

What is Runtime Polymorphism?

Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. The determination of the method to be called is based on the object being referred to by the reference variable.

class Bike{
  void run(){System.out.println("Running");}
class Activa extends Bike{
  void run(){System.out.println("Push start Running.");}
  public static void main(String args[]){
    Bike b = new Activa (); // upcasting b to child object.
        // Activa.Run will be called instead of Bike.Run as we are referring to Activa object;

Is Runtime Polymorphism by data members possible?

No, We can override the member functions but not the data members.

class Bike{
    int speedlimit=50;
class Ducati extends Bike{
    int speedlimit=150;
    public static void main(String args[]) {
        Bike obj=new Ducati();
        System.out.println(obj.speedlimit); //output will still be 50 as speedlimit of Bike only will appear.

What is the difference between static binding and dynamic binding?

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

What is an instanceof operator?

The instanceof is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has a null value, it returns false. An object of subclass type is also a type of parent class. For example, if Dog extends Animal then the object of Dog can be referred by either Dog or Animal class.

class Example{
    public static void main(String args[]){
        Example s=new Example();
        System.out.println(s instanceof Example); //true

What is abstraction?

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Can there be an abstract method without an abstract class?

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

Can we define private and protected modifiers for the members in interfaces?

No, they are implicitly public.

What is the package?

A package is a group of classes, interfaces, and sub-packages. It provides access protection and removes naming collisions.

Do I need to import java.lang package any time?

No. It is by default loaded internally by the JVM.

What is the static import?

By static import, we can access the static members of a class directly, and there is no to qualify it with the class name.

Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block.

Is there any case when finally will not be executed?

Finally, the block will not be executed if the program exits (either by calling System.exit() or by causing a fatal error that causes the process to abort).

Can an exception be rethrown?


What is exception propagation?

An exception is first thrown from the top of the stack, and if it is not caught, it drops down the call stack to the previous method; if not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.

What is String Pool?

The string pool is the space reserved in the heap memory used to store the strings. The main advantage of using the String pool is whenever we create a string literal; the JVM checks the “string constant pool” first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn’t exist in the pool, a new string instance is created and placed in the pool. Therefore, it saves memory by avoiding duplicacy.

Are string objects immutable?

Yes, string objects are immutable. As they are stored in an object pool, if we change the string then a new string gets created in the pool. For example, let’s say we have a variable x which refers to a string called “Coding” if we append “Jump” to it, then it will create a new instance in the string pool, and this variable x will refer to that new string.

What is the String intern function?

The intern method returns the String object reference from the string pool.

public class Test
    public static void main (String args[])
        String s1 = "CodingJump";  // This creates string in StringPool
        String s2 = new String("CodingJump"); // This creates string in Heap Memory
        System.out.println(s1 == s2.intern()); // true, because it points to StringPool
        System.out.println(s1 == s2); // false, because the pointers are different

What is the purpose of toString() method in Java?

The toString() method returns the string representation of an object. If you print any object, the java compiler internally invokes the toString() method on the object.

Why is CharArray() preferred over String to store the password?

String stays in the string pool until the garbage is collected. If we store the password into a string, it stays in the memory for a longer period, and anyone having the memory dump can extract the password as clear text. On the other hand, Using CharArray allows us to set it to blank whenever done with the password. It avoids the security threat with the string by enabling us to control the memory.

How can you create an anonymous class?

Anonymous classes are the classes that are automatically declared and instantiated within an expression.

  1. Implementing abstract class
  2. Implementing interface
abstract class Person {
    abstract void eat();
interface Person2 {
    void talk();
class TestAnnonymousInner {
    public static void main(String args[]) {
        Person p1 = new Person() {
            void eat() {
                System.out.println("Eat Fruits");
        Person2 p2 = new Person2() {
            public void talk() {
                System.out.println("Hello World");

Here Person/Person2 is an abstract class/interface, for which we are creating the class implementation directly i.e. we are not creating a new class with implementation, these classes are similar to the concept of lambda functions.

Can an interface be nested?

Yes, it can be declared inside the interface.

interface Showable{
	void show();
	interface Message{
		void msg();

Can a class have an interface?

Yes, it can be defined within the class.

public class InterfaceInsideClassExample {
   interface InnerInterface {
      void hello();
   class Inner implements InnerInterface {
      public void hello() {
         System.out.println("Welcome to CodingJump!");
   public static void main(String args[]) {
      Inner obj = new InterfaceInsideClassExample().new Inner();

Can an Interface have a class?


interface CodingJump {
   void addBlog(Blog b);
   void removeBlog(Blog b);
   public class Blog {
      String blogName;
      int issueDate;
      int returnDate;

What is Garbage Collection?

Garbage collection is a process of reclaiming unused runtime objects. It is performed for memory management. In other words, we can say that It is the process of removing unused objects from the memory to free up space and make this space available for Java Virtual Machine.

What is the purpose of the finalize() method?

The finalize() method is invoked just before the object is garbage collected. It is used to perform cleanup processing.

public class FinalizeTest {
    public void finalize()
        System.out.println("Object is garbage collected");
    public static void main(String[] args) {
        new FinalizeTest();
        new FinalizeTest();

What is Daemon thread?

Daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection.

What is the purpose of the Runtime class?

Java Runtime class is used to interact with a java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory, etc. The Runtime.getRuntime() method returns the singleton instance of the Runtime class.

What is the transient keyword?

If you define any data member as transient, it will not be serialized. By determining transient keywords, the value of the variable need not persist when it is restored.

What is an interface?

The interface is a blueprint for a class that has static constants and abstract methods. It can be used to achieve full abstraction and multiple inheritances.

Can I import the same package/class twice? Will the compiler complain?

One can import the same package or the same class multiple times. Neither compiler nor JVM complains about it. However, the JVM will internally load the class only once, no matter how many times you import the same class.

Explain the hierarchy of Java Exception classes?

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error.

  • Throwable
    • Exception
      • IOException
      • SQLException
      • ClassNotFoundException
      • RuntimeException
    • Error
      • StackOverflowError
      • VirtualMachineError
      • OutOfMemoryError

What is the checked exception?

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.

What is object cloning?

Object cloning is a way to create an exact copy of an object. The clone() method of the Object class is used to clone an object the java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don’t implement a Cloneable interface, the clone() method generates a CloneNotSupportedException.

What is the purpose of the strictfp keyword?

Java strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable.

Is Java Applet Supported?

Applet support ended in March 2019. Oracle announced in January 2016 that Applets would be deprecated in Java SE 9, and the technology was removed in Java SE 11.

What is a locale?

A Locale object represents a specific geographical, political, or cultural region.

import java.util.*;
public class LocaleExample {
	public static void main(String[] args) {
		Locale locale=Locale.getDefault();

What is the difference between equals() and == in Java?

Equals() method is defined in Object class in Java and used to check equality of two objects defined by business logic. == or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. == operator will be true only if the object reference is the same, even if the inside contents of the object are the same. We have to implement the Equals() method and use it to check if the contents are the same.

Can Stack Memory be accessed by two different threads in Java?

Stack memory is separate for each thread and cant be accessed by another thread. If we have a use case of shared memory, then well have to use Heap memory. A thread can only access its own thread stack. An object’s member variables are stored on the heap along with the object itself.

What is multithreading?

Multithreading is a process of executing multiple threads simultaneously.

  1. Threads share the same address space.
  2. The thread is lightweight.
  3. The cost of communication between the processes is low.

What is the difference between preemptive scheduling and time slicing?

Preemptive scheduling – the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing – a task executes for a predefined slice of time and then reenters the ready tasks pool.

What is context switching?

In Context switching, the state of the process (or thread) is stored to be restored, and execution can be resumed from the same point later. Context switching enables multiple processes to share the same CPU.

What is the difference between wait() and sleep() method?

The wait() method is defined in the Object class when called releases the lock. The sleep() method is defined in the Thread class. Doesn’t release the lock.

Can we make the user thread as daemon thread if the thread is started?

No, if you do so, it will throw IllegalThreadStateException. We can only create a daemon thread before starting the thread.

What is the purpose of the Synchronized block?

The Synchronized block can be used to perform synchronization on any specific resource of the method. Only one thread can execute on a particular resource, and all other threads that attempt to enter the synchronized block are blocked.

What is the deadlock?

Deadlock is a situation where every thread is waiting for a resource held by some other waiting thread.

How can deadlock be avoided?

  1. Avoid Nested lock
  2. Avoid Unnecessary lock
  3. Use more Join Methods

What is the volatile keyword in java?

Volatile keyword is used in multithreaded programming to achieve thread-safety.

How does the volatile keyword help solve thread safety?

Imagine that only Thread 1 increments the counter variable, but both Thread 1 and Thread 2 may read the counter variable from time to time. If the counter variable is not declared volatile, there is no guarantee about when the counter variable’s value is written from the CPU cache back to main memory. This means that the counter variable value in the CPU cache may not be the same as in the main memory. Only one thread reads and writes the value of a volatile variable, and other threads only read the variable. The reading threads are guaranteed to see the latest value written to the volatile variable. If two threads are both reading and writing to a shared variable, then using the volatile keyword for that is not enough. It would be best to use a synchronized in that case to guarantee that the variable’s reading and writing is atomic.

If a Generic Type Is Omitted When Instantiating an Object, Will the Code Still Compile?

Generics were retrofitted to most of the standard Java classes such as collections as Generics only came into existence from Java 7. List list = new ArrayList(); // would still compile

What Is a Bounded Type Parameter?

The bounded type parameter is a generic type with extends keyword, i.e., only certain classes are allowed. class Sample <T extends Number> For the above example T generic type will only allow objects which are of type Number or its sub classes. Here is one more similar example.

class Print<T extends Jump> {
    public void print(T t)
class Jump {}
class CodingJump extends Jump {}
public class HelloWorld{
     public static void main(String []args){
        Print<CodingJump> g = new Print<CodingJump>();
        g.print(new CodingJump());

What Is a Wildcard Type?

A wildcard type represents an unknown type. It’s detonated with a question mark**?** Lets assume we have a class hierarchy as below.

What is an Upper bounded wildcard? ? extends Animal – Here we are telling the compiler to accept Animal and sub classes of animal, i.e., Dog, Cat, RedCat What is a Lower bounded wildcard? ? super Cat – Here we are telling the compiler to accept cat and subclass of cat which can be Animal and Object

What is a higher order function?

A higher-order function is a function that either takes a function (method) as a parameter or returns a function. Such as Collections.sort(), etc.

Is using @Override annotation compulsory?

No, it is not compulsory, but it has more benefits when used.

  1. If the programmer has made a mistake in function name the compiler will complain saying that there is no function to override.
  2. If the programmer is going to change the signature of the overridden method then the compiler will again complain, which helps in rectification of error at compile time.

Explain diamond patterns in inheritance?

This is sometimes referred to as Deadly Diamond of Death.

The ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?

What do you understand by an instance variable and a local variable?

Instance variables – These variables are present in the class; these are accessible by all the class methods. Local variables – These variables are declared inside a method; they have scope only in the method.

Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList?

In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is not possible. The data members/objects present in the ArrayList have references to the objects located at various sites in the memory. Thus, storing actual objects or non-primitive data types (like Integer, Double, etc.) occurs in various memory locations. However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations.

Why does Java not make use of pointers?

Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with pointers’ help. The usage of pointers can make the procedure of garbage collection quite slow and erroneous.

Differentiate between a String, StringBuffer, and a StringBuilder?

Storage area In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, heap memory is the storage area. Mutability A String is immutable, whereas both the StringBuilder and StringBuffer are mutable. Efficiency It is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. Thread-safe StringBuilder and StringBuffer are used in the case of a threaded environment, whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads.

Explain about final, finally and finalize keywords?

Final Mostly used to restrict inheritance of methods or classes. If we declare it in front of a variable, the value gets fixed and cannot be changed later. Finally Used after a try or catch block, the section of code that executes even if an exception is present or not. Finalize This function is overridden so that the garbage collector knows to call it when deleting objects.

Is exceeding the memory limit possible in a program despite having a garbage collector?

Yes, it is quite possible as GC will only delete objects if they are not referenced. If the developer still keeps holding on to the references, then GC will not collect. This scenario is called a Memory Leak, the common cause of excessive memory usage and cause of memory limit. But if the program requires too much memory, which is not available in the system, it can also cause the program to hit memory limits.

Why is synchronized used?

Synchronization assists in resolving the issue and the resource is shared by a single thread at a time.

public synchronized int increase() {
	increase_counter = increase_counter + 1;
	return increase_counter;

Even if multiple threads are calling this method, the counter will get incremented correctly. Synchronized blocks can be used inside the method also

public void add(int value) {
       this.count += value;

When you are writing equals() method, which other method or methods do you need to override?

hashcode(), Hashtable and HashMap use a hashcode() function.

Can two objects which are not equal have the same hashCode?


How do you avoid NullPointerException, while comparing two Strings in Java?

Let’s assume we have two strings a, b; if we know that a cannot be null, but b can be anything, then the best way to use is a.equals(b) instead of b.equals(a) as if b is null, then we can get NullPointerException.

What happens if you compare an object to null using equals()?

When a null object is passed as an argument to equals() method, it should return false; it must not throw NullPointerException.

What is Serialization in Java?

Object Serialization in Java is a process used to convert Objects into a binary format which can be persisted into a disk or sent over the network. Making a class Serializable in Java is very easy; your Java class needs to implements interface, and JVM will take care of serializing object in the default format

What is the difference between Serializable and Externalizable interface in Java?

Externalizable provides us writeExternal() and readExternal() methods, which give us the flexibility to control java serialization mechanisms instead of relying on Java’s default serialization.

What is serialVersionUID? What would happen if you don’t define this?

SerialVersionUID is used for version control of objects. You can specify serialVersionUID in your class file also. A consequence of not specifying serialVersionUID is that when you add or modify any field in the class, then the already serialized class will not recover because serialVersionUID generated for a new class and an old serialized object will be different.

While serializing you want some of the members not to serialize?

Declare it either a static or a transient based on your need, and it will not be included during the Java serialization process.

What will happen if one of the members in the class doesn’t implement a Serializable interface?

If you try to serialize an object of a class that implements Serializable, but the object includes a reference to a non- Serializable class, then a NotSerializableException will be thrown at runtime.

What are the compatible changes and incompatible changes in Java Serialization Mechanism?

Compatible Changes

  • Addition of fields
    • From transient/static to normal field
    • From private to public fields
    • New fields added

Incompatible Changes

  • Once a class implements the Serializable interface, you cannot later make it implement the Externalizable interface
  • Deleting fields can cause a problem
  • Renaming fields i.e. in turn deleting fields
  • You cannot alter the position of the class in the class hierarchy.
  • You cannot change the name of the class or the package it belongs to

What is the difference between Java 11 and Java 8?


  • The appletviewer tool. It was deprecated in JDK 9
  • JMC (Java Mission Control). However, it is available as a separate downloadable module.


  • Nest-Based Access Control – Nests allow classes and interfaces that are logically part of the same code entity, but which are compiled to distinct class files, to access each other’s private members without the need for compilers to insert accessibility-broadening bridge methods

What is a singleton class?

A singleton class in java can have only one instance, and hence all its methods and variables belong to just one instance. Singleton class concept is useful for situations when there is a need to limit the number of objects for a class.

// Java program implementing Singleton class
class Singleton
    // static variable single_instance of type Singleton
    private static Singleton single_instance=null;

    // variable of type String
    public String s;

    // private constructor restricted to this class itself
    private Singleton()
        s = "Hello World";

    // static method to create an instance of Singleton class
    public static Singleton GetInstance()
        // To ensure only one instance is created
        if (single_instance == null)
            single_instance = new Singleton();
        return single_instance;
class Main
    public static void main(String args[])
        // instantiating Singleton class with variable x
        Singleton x = Singleton.GetInstance();

        // instantiating Singleton class with variable y
        Singleton y = Singleton.GetInstance();

        // instantiating Singleton class with variable z
        Singleton z = Singleton.GetInstance();

        // changing variable of instance x to upper case, we can see that s is HELLO WORLD for all instances
        x.s = (x.s).toUpperCase();

        System.out.println("String from x is " + x.s);
        System.out.println("String from y is " + y.s);
        System.out.println("String from z is " + z.s);

Can we have any other return type than void for the main method?

No, Java class main method can have only a void return type for the program to get successfully executed. Nonetheless, if you absolutely must return a value at the completion of the main method, you can use System.exit(int status)

Is there a way to increase the size of an array after its declaration?

Arrays are static, and once we have specified their size, we can’t change it. If we want to use such collections where we may require a change of size (no of items), we should prefer vector over the array.

What happens if you remove the static modifier from the main method?

Program compiles successfully. But at runtime throws an error NoSuchMethodError.

Explain about Passing and Returning Objects in Java?

When we pass a primitive type to a method, it is passed by value, but objects are passed by reference, so any changes to the object in function will be permanent.

Explain about var keyword in Java?

In Java 10, the var keyword allows local variable type inference, which means the type for the local variable will be inferred by the compiler, so you dont need to declare that.

var map=new HashMap<string,string>();
var listofMovies=new HashMap<>>();</string,string>

For using an abstract class which keyword do we use implements or extends?

As we need to extend the functionality of the abstract class, though we still need to implement some of the functions in it, we still use extends keyword.

What keywords do we use for using interfaces?

If we are extending the interface’s functionality by another interface, then we can use extends; if we are going to implement the interface in a class, then we use the implements keyword.

What are the advantages of immutable objects?

  • Simplicity – An immutable class can just be in one externally visible state. On the contrary, a mutable object can have a lot of states.
  • Thread safety – Immutable objects are inherently thread-safe. They do not require synchronization.
  • Enables reuse – Immutable objects encourage to cache or store the frequently used instances rather than creating one each time. Similar to String Pool
  • Building blocks for other objects – The immutable objects make a great building block for building other objects (mutable or immutable). An example is immutable objects make a great fit to be used as keys of a map and in sets.

How to implement immutable Java class?

  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • Don’t provide setter methods for variables.
  • Initialize all the fields via a constructor
final class ImmutableExample {
    private final int id;
    private final String name;
    public ImmutableExample(int id, String name) { = id; = name;

What is a Thread Pool in Java?

Java Thread pool represents a group of worker threads that are waiting for the job and that get reused many times. In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.

import java.util.concurrent.*;
class WorkerThread implements Runnable {
    private String message;
    public WorkerThread(String s){
    public void run() {
        System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
        processmessage(); //call processmessage method that sleeps the thread for 2 seconds
        System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name
    private void processmessage() {
        try {  Thread.sleep(2000);  } catch (InterruptedException e) { e.printStackTrace(); }
public class CodingJumpThreadPool {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5); //creating a pool of 5 threads
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker); //calling execute method of ExecutorService
        while (!executor.isTerminated()) {   }
        System.out.println("Finished all threads");

What is the difference between Thread & Runnable?

Thread Runnable
Need to extend Thread class Need to implement Runnable interface

As we are extending the Thread class we can’t extend another class as Java doesn’t support multiple inheritances, we have to create a subclass in that case.

As we are implementing an interface we can extend to another class directly.

What is HATEOAS?

If your are building a hypermedia-driven REST service with Spring HATEOAS: a library of APIs that you can use to create links that point to Spring MVC controllers, build up resource representations, and control how they are rendered into supported hypermedia formats (such as HAL). With Hypermedia as the Engine of Application State (HATEOAS), a client interacts with a network application whose application servers provide information dynamically through hypermedia. A REST client needs little to no prior knowledge about how to interact with an application or server beyond a generic understanding of hypermedia.