Java interview questions answers for experienced

 1.  What is the difference between overloading and overriding?

          If a class is overloaded with multiple method with same name and different method  signature is known as overloading.

           For example:-

                public class Calculator {

                    public static int add(int a,int b) { return a+b; }

                    public static int add(int a, int b, int c) { return a+b+c; }

                    public static double add(double d, double e) { return d+e; }


                 Here we have multiple methods with name add but the parameters are different based on  the number or based on the type. This concept is called overloading.


        When a child class or sub-class provide a specific implementation of a method that is already provided by one of its super-class or parent classes. When a method of child class has the same method signature and same return type(or sub-type) as a method in its super-class, then the method in the child class is said to override the method in the parent-class. This concept is called overriding.


              class Animal{
                    void eat(){
                        System.out.println("Animal eat method");
                class Cat extends Animal{
                    void eat() {
                       System.out.println("Cat eat method");


            class Main {
                    public static void main(String[] args)   {
                        Animal animal= new Animal();
                        Cat cat = new Cat();


                Animal eat method

                Cat eat method

· Overloading occurs between the method in same class whereas overriding occurs between parent and child class.

· In Overloading methods name are same but parameters are different whereas in Overriding method signature should be same.

· In Overloading method call is determined on the compile-time whereas Overriding method call is determined on runtime.

· Overloading method means compile time method is known as compile-time Polymorphism whereas overriding means runtime method call is known as runtime  polymorphism.

· Overloading will give error on compile-time and overriding on  runtime so if anyone will break overriding will cause serious issue than overloading.

· Performance wise overloading is better because it occurs at compile-time whereas overriding method occurs at runtime.

· Private and final can be used in overloading but can’t be used in overriding.

· Static method can be used in overloading but not in overriding because static method is not a run-time polymorphism.

2. Why is the  String class Immutable?

             Immutable class means once an object is created we can’t change or modified. In Java, all wrapper classes like Integer, Float, Double, Long, Short, Byte, Char, Boolean and String.
        The main factor of keeping String class as immutable are caching, security, synchronization and performance.
                The String literal concept with string pool is an important role to make performance fast. Actually when ever we are using string literal concept to make string object first it will check the value in the string pool and if is already available it will not create a new object in String pool simply it will refer the same object. So in this case it saves lot of JVM memory and performance is also fast due to not burden of creating new object.

                             Immutability provides security. For example, in an secure login applications, the username, password, details, etc. are passed as the String. As String is immutable, its value can’t be changed. Otherwise, any hacker could change the referenced value that will cause a serious security issues.
                Due to immutability, String is thread safe because it’s won’t be changed when accessed from multiple threads and if any thread try to changed the value, then instead of modifying the same string object value it will a new String will be created in the String pool.

3. How can we create an immutable class in Java?

        To create an immutable class in Java. We have to to follow below steps:-

    a. We have to declare the class as final or need to create private constructor so that the other the class can't be override.

    b. Define all fields as private and final.

    c. Don't provide the setter method so that the modification of the fields value or object reference fields not possible .

    d. In the getter methods, do not return actual object reference instead return a copy of the object.


                    public final class Employee {

                            private final String name;

                            private final int age;

                            private final String gender;

                       public String getName() {

                        return name;


                    public int getAge() {

                        return age;


                    public String getGender() {

                        return gender;



4. What is a Singleton class and how can we create it?

            A class which will allow to create only once object at a time is called singleton class.

           However if we try to create the object of a singleton class after the first object creation, the new reference variable will also point to the first object. 

        Design a Singleton class:-


· First, declare private constructor for the Singleton class. So that no other classes can instantiate or make objects from it.

· Declare a  private static variable of the same class that is the only instance of the class.

· Declare a static factory method with the return type as an object of this singleton class.

Design Singleton class with eager initialization process:-


public class SingletonTest {

    //Early, instance will be created instance at class loading time  

    private static final SingletonTest instance = new SingletonTest();

    //private constructor so other classes can instantiate or make objects from it.

    private SingletonTest(){}


    public static SingletonTest getInstance(){

        return instance;




Design Singleton class with lazy initialization process:-


public class SingletonTest {


    private static SingletonTest instance;


    private SingletonTest(){}


    public static SingletonTest getInstance(){

        if(instance == null){

            instance = new SingletonTest();


        return instance;




We have others approaches to make singleton class like Thred safe singleton, Enum, Refrection etc.

5. What is Spring bean and it’s scope?

             In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. 

    There are 5 bean scope supported by spring:-




Scopes a single bean definition to a single object instance per 

Spring IoC container.


Scopes a single bean definition to any number of object instances.


Scopes a single bean definition to the lifecycle of a single HTTP request;

 that is each and every HTTP request will have its own instance of a 

bean created off the back of a single bean definition. Only valid in the 

context of a web-aware Spring ApplicationContext.


Scopes a single bean definition to the lifecycle of a HTTP Session. 

Only valid in the context of a web-aware Spring ApplicationContext.

global session

Scopes a single bean definition to the lifecycle of a global 

HTTP Session. Typically only valid when used in a portlet context. 

Only valid in the context of a web-aware Spring ApplicationContext.

6. What is object class and what are the methods present inside it ?

            java.lang.Object is the parent class of all the classes in java by default. Every class has Object as a superclass.

    There are following methods inside Object class:-

            a. Hashcode:- 

                public int hashCode() -> return a hash code value for this object.

           b. Equals:- 

                   public boolean equals(Object obj) ->compares the given object to this object.

           c. toString:-

                  public String toString() -> returns the string representation of this object.

           d. Notify:-

                  public final void notify() -> wakes up single thread, waiting on this object's                                  monitor.      

           e. NotifyAll:-

                  public final void notifyAll() -> wakes up all the threads, waiting on this object's                           monitor.

           f. wait(long timeout):- 

                  public final void wait(long timeout)throws InterruptedException

             -> causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method). 

          g. wait(long timeout,int nanos):-

                  public final void wait(long timeout,int nanos)throws InterruptedException:- causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).

          h. wait:- 

                 public final void wait()throws InterruptedException:->causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).

         i. getClass() :- 

                 public final native Class<?> getClass():-> Returns the runtime class of this.

         j. clone:-

                 protected native Object clone() throws CloneNotSupportedException:-> Creates and returns a copy of this object.

        k. finalize:-

                protected void finalize() throws Throwable:-> Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

7.  Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class ?

        There are following reasons to have wait(), notify() and notifyAll() methods in Object class.

          a. wait(), notify() and notifyAll() methods being in Object class allows all the threads created on that object to communicate with other.

        b. Every Object has a monitor, acquiring that monitors allow thread to hold lock on object. But Thread class does not have any monitors.

         c. wait(), notify() and notifyAll() are used for inter-thread communication. But threads themselves have no knowledge of each others status. It is the shared object among the threads that acts as a communicator among the threads.

8. What are the differences between Optional.of vs Optional.ofNullable ?

        Optional.of :- It takes an elements and return Optional with the specified element. If the given element is null, then it will throw NullPointerException.

        Optional.ofNullable  :- It takes an element and return Optional with the specified element. If the given element is null, then it will return empty optional. 

9. What are the differences between stream intermediate operation and terminal operation?

        Intermediate operation return another stream as a result. Terminal operations can not be chained together.

    Intermediate operations are lazily loaded. It means When you call intermediate operations, they are actually not executed. It is just stored in the memory and executed when the terminal operation is called on the stream.

    intermediate operations doesn’t produce the result. It will just transform one stream to another stream. Whereas terminal operations produce the result.

     Intermediate operations:

            filter(), map(), flatMap(), distinct(), sorted(), skip(), limit(), peek()  

    Terminal Operations :

                      forEach(), reduce(), min(), max(), count(), collect(), toArray(), anyMatch(), allMatch(), findAny(), findFirst(),noneMathc().

10. What is Synchronization?

    Synchronization in java is a concept of  control the access of multiple threads to any shared resources. When multiple threads will try to do their operations on same shared resources then data inconsistency problem will happen. 

        In a real time scenario When we want to allow only one thread can access the shared resources we have option to go Synchronization.

Post a Comment (0)
Previous Post Next Post