33 Java Interview Questions for Experienced in 2021: Part 3

33 Java Interview Questions for Experienced in 2021: Part 3
33 Java Interview Questions for Experienced in 2021: Part 3

Introduction

The Java programming language created by James Gosling in the early 1990s is one of the most popular programming languages. No wonder Java is the second most demanded programming language with around 70K job postings in January 2020, as per Indeed. Over 90% of the Fortune 500 companies still rely on Java for their development projects, and globally there are over 8 million Java developers.

So if you get an interview call for the Java developer role and are looking for a quick guide before your interview, then you have come to the right place. The whole blog consists of 100 interview questions divided into three parts: Beginner, Intermediate and Advanced. This article is Part 3 of the Java Interview Questions and Answer Series covering advanced-level Java Interview questions. Go through all the questions to enhance your chances of performing well in the interviews.

Advanced Java Interview Questions

Q1) What is Encapsulation?

Ans 1) Encapsulation in Java is a mechanism of wrapping the data(i.e., variables) and code acting on the data(methods) together as a single unit. The variables of an encapsulated class are hidden from other classes and can be accessed only using the methods of the current class. It is also known as Data hiding. Data hiding can be achieved by making all the instance variables private;

The Java bean class is an example of a fully encapsulated class. 

Consider the following example of an encapsulated class in Java.

class Student{
private String name;
// getter method for name
public String getName()
{
     return name;
}
    
// setter method for name
public void setName(String name)
{
     this.name = name;
}
    
}  // Student class ends here
public class Demo
{
public static void main(String args[])
{
           // Using the getter and setter methods defined above
     Student obj = new Student();
     obj.setName("Manvi");
     System.out.println(obj.getName());
     
}
}

The output of the above code will be

Manvi

Q 2) How can an encapsulated class achieve Read-only and write-only properties?

Ans) An encapsulated class can be made read-only by using only the getter methods, as shown in the following example.

class Student{
// Private data member, its value cannot be changed by any means
private String str = "Java Interview Questions";
// getter method for name
public String getStr()
{
     return str;
}
}  // Student class ends here
public class Demo
{
public static void main(String args[])
{
   Student obj = new Student();
           // Uncommenting the below code will generate compile-time error
           // obj.setStr(“Advanced Java Interview Questions”);
   System.out.println(obj.getStr());
}
}

An encapsulated class can be made write-only by using only the setter methods, as shown in the following example

class Student{
private String str;
// getter method for name
public void setStr(String str)
{
     this.str = str;
}
}  // Student class ends here
public class Demo
{
public static void main(String args[])
{
   Student obj = new Student();
   // uncommenting the below line will generate compile time error
   //System.out.println(obj.getStr());
   obj.setStr("Java Interview Questions");
}
}

Q3) Differentiate between Compile time and run time polymorphism.

Ans 3) 

Compile-Time PolymorphismRun-Time Polymorphism
The compiler examines the method signature at the compile-time and then determines which method to invoke for a given method call.
It is also known as static binding, early binding, and overloading as well.
Runtime polymorphism means at runtime, it is determined which method needs to be invoked for a given method call.
It is also known as dynamic binding, late binding, and overriding as well.
It can be achieved through static bindingIt can be achieved through dynamic binding.
It provides fast execution as the method that needs to be executed is known at the compile time.It provides comparatively slower execution as the method that needs to be executed is known at the runtime.

For more information and examples, you may refer to this.

Q4) What is the difference between Heap and Stack Memory?

Ans) 

Stack MemoryHeap Memory
Stack Memory contains local, primitives, and references to variables and objects in heap space.Whenever a new object is created, it’s always stored in the heap memory.
Stack memory cannot be accessed by other threadsObjects stored in the heap memory are globally accessible
Stack Memory is used by one thread of executionHeap memory resides from the start to the end of the application
Stack Memory follows LIFO or Last In First Out structure for freeing up memoryMemory management is based on the generation associated with each object.

Q 5) What is ClassLoader?

Ans) The Java ClassLoader is an abstract class belonging to the java.lang package and is responsible for loading classes from different sources at runtime. Classes are loaded according to the need. If a class needs another class for execution, then that class is loaded as well.

Every ClassLoader has a pre-defined location from where they load class files. Based on that there are three types of ClassLoader.

  • Bootstrap ClassLoader: Responsible for loading standard JDK class files from rt.jar and other core classes. It does not have any parent ClassLoaders and is also known as the Primodial ClassLoader.
  • Extensions ClassLoader: Responsible for delegating class loading requests to its parent. It loads files from jre/lib/ext directory or any other directory pointed by the system property java.ext.dirs.This is the child class of Bootstrap ClassLoader.
  • System ClassLoader: Responsible for loading classes found in the environment variable CLASSPATH, -classpath, or -cp command-line option. This is a child class of Extension ClassLoader.

Refer to the official documentation for more information.

Q 6) What are the principles of the functionality of a Java ClassLoader?

Ans) There are three principles of the functionality of a Java ClassLoder:

  • Delegation Model: The JVM and the Java ClassLoader uses the Delegation Hierarchy Algorithm for loading classes into the Java file. Basically, the JVM checks whether a class is already loaded or not when it comes across a class. If the class is already present, then the execution continues; else, the JVM asks the Java ClassLoder subsystem to load that particular class. Then the ClassLoader subsystem hands over the control to Application ClassLoader.
  • Visibility Model: It allows Child ClassLoader to see all the classes loaded by the parent ClassLoader. The parent ClassLoader cannot see all the classes loaded by the child ClassLoader
  • Uniqueness Principle: It allows to load a class once and is achievable using the delegation principle. It ensures that the child ClassLoader does not reload the class which is already loaded by the parent.

Q7) What are comparable interfaces?

Ans) The Java comparable interface found in java.lang package is used to order the objects of the user-defined classes. The compareTo method is used to compare objects. 

Q8) Does Java support Global variables?

Ans) Global variables are globally accessible. Java does not support Global variables, as it was designed to keep the object-oriented principles in mind, and as such, every variable in Java is either local or a  member of a class.

Also, Global variables break the referential transparency and create collisions in namespace management.

Q9)  What are Lambda Expressions?

Ans) Lambda expressions are used to express instances of single-method compactly and concisely. A lambda expression is a short block of code that takes in parameters and returns a value. They do not need a name and can be implemented right in the body of the method.

Syntax:

Single Parameter: parameter -> expression
Multiple Parameter: (parameter1, parameter2) -> expression

Lambda expressions cannot contain variables, assignments, statements such as if or for. An example of a Java Lambda expression with a single parameter is shown below

interface Sample{
    String display(String name);
}


public class Demo
{
    public static void main(String []args)
    {
        // Lambda expression with single parameter
        Sample s1 = (name)->{
            return "Hello " + name;
        };
        
        System.out.println(s1.display("Mark"));
        System.out.println(s1.display("Jack"));
    
    }
}

The output of the above code is:

Hello Mark
Hello Jack

Q10)  What is CopyOnWriteArrayList?

Ans 10) 

  • It’s a variant of ArrayList found in the collection interface wherein operations like add, set, and remove are implemented by creating a copy of the array. It is found in java.util.concurrent package and implements the List interface. 
  • Its also called the thread-safe version of ArrayList
  • Duplicates, Null and Heterogeneous objects are preserved.

Q 11) Why is bytecode important in Java?

Ans)  The compiler compiles the Java program to generate a class file or bytecode. The bytecode is a highly optimized set of instructions that are executed by the Java Virtual Machine and is platform-independent.

The bytecode implementation makes Java a platform-independent language.

To understand how compilation and interpretation work, refer to the blog

Q12) Difference between JAR and WAR files?

Ans) JAR Files: JAR or Java Archive is a package file format that contains libraries, resources, and metadata files. It has all the components to make a self-executable Java application. Compressing all the files helps to reduce the size of the application and is easier to transfer over the network. JAR files have an extension of .jar.

WAR Files: WAR or Web Application Resource or Web Application Archive that contains a collection of JAR files, JSP, Servlet, XML files, static web pages like HTML, and other resources that constitute a web application. Using war files allows us to test and deploy a web application easily, and it takes a minimum amount of time to transfer a file from client to server.

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

Ans) In ArrayList, data storage in the form of primitive data types like integer, float, etc is not possible, the data stored in the ArrayList have references to the objects which are located at various locations in the memory. That is why storage of non-primitive data types takes place in various memory locations.

In a nutshell, data stored in ArrayList have references in the Stack Memory, the references point to the actual data in the Heap memory.

Q14) Is it possible to exceed the memory limit possible despite having a garbage collector?

Ans) Garbage collector recognizes and eliminates the objects that are not required in the program anymore, objects that are unreachable, objects that go out of scope. The memory limit is exceeded for the program when the memory is released after the garbage collection is not enough for creating new objects. Moreover, exhaustion of heap memory can also occur if the objects are created in such a way that they remain in the memory forever. The garbage collector endeavors its level best to reclaim memory as much as possible, memory limits can still be exceeded.

Q15) What is the tradeoff between the usage of an unordered array versus the usage of an ordered array?

Ans) The tradeoff between usage of an unordered array versus the usage of an ordered array is:

  • Search-Complexity: In the case of an unordered array, the search time complexity is O(N) and in the case of an ordered array, the search time complexity is O(log N) where N is the number of elements in the array.
  • Insertion-Complexity: In the case of an ordered array, the insertion complexity is O(N), as it has to maintain the order of elements and in the case of an ordered array the insertion complexity is O(1)

Q16) What happens at runtime when the same class or package is imported twice in Java?

Ans) It is possible to import the same class or package twice in Java, there won’t be any compile-time or runtime errors. However, it is redundant as internally the JVM will load it only once.

Q17) If the code System.exit(0) is written at the end of the try block, will the finally block get executed?

Ans) The System.exit() method is used to terminate the current Java virtual machine running on the system. The control of the program after the System.exit(0) is immediately gone, the program gets terminated and the finally block will never be executed.

Refer to this to know more about the exception handling using try, catch, and finally.

Q18) What is double brace initialization in Java?

Ans 18) When using the collection framework, the creation and initialization of the objects can be done in a single step which otherwise is done in multiple steps using Double brace initialization.

Consider the following code wherein a HashSet is created using double brace initialization.

import java.util.HashSet;
import java.util.Set;
public class DoubleBraceDemo{

     public static void main(String []args)
     {
         Set<String> setString = new HashSet<String>()
         {
             {
                 add("ABC");
                 add("DEF");
                 add("GHI");
             }
         };
         System.out.println(setString);
     }
}

The output of the above code is:

[ABC, DEF, GHI]

In the above program, the first brace creates a new Anonymous inner class. This inner class is capable of accessing the behavior of their parent class i.e. HashSet in the above example. The second braces are instance initializers that are run when the anonymous inner class is instantiated.

Q19) When will an object be eligible for Garbage Collection in Java?

Ans 19) Some of the possible ways of making an object eligible for Garbage collection are:

Object Outside a Method: A method is stored in stack memory. When a method is called, JVM fetches it from the stack and executes it. After the execution of the method, it is popped out from the stack, and then all the variables inside it will be eligible for garbage collection.

public class Demo
{
    String str;
    Demo(String str)
    {
        this.str = str;
    }
    
    public static void demoMethod()
    {
        Demo obj1 = new Demo("Sample-String-1");
        Demo obj2 = new Demo("Sample-String-2");
    }
    
    protected void finalize() throws Throwable
    {
        System.out.println(this.str + " is garbage collected");
    }
    public static void main(String []args)
    {
        demoMethod();
        System.gc();
    }
}

The output of the above code is:

Sample-String-2 is garbage collected
Sample-String-1 is garbage collected

Reassignment: When you reassign a value to an existing reference variable, then the original object ends up being unreachable.

public class Demo
{
    String str;
    Demo(String str)
    {
        this.str = str;
    }
    protected void finalize() throws Throwable {
      System.out.println(this.str + " is garbage collected");
   }
    public static void main(String []args)
    {
       Demo obj = new Demo("Sample-Object-1");
       obj = new Demo("Sample-Object-2");
       System.gc();
    }
}

          The output of the above code is:

Sample-Object-1 is garbage collected

Nullifying the reference variable: When all the references to an object are changed to NULL, it becomes unreachable and is eligible for garbage collection.

public class Demo
{
    String str;
    Demo(String str)
    {
        this.str = str;
    }
    protected void finalize() throws Throwable {
      System.out.println(this.str + " is garbage collected");
   }
    public static void main(String []args)
    {
       Demo obj = new Demo("Sample-Object-1");
       obj = null;
       System.gc();
    }
}

The output of the above program is:

Sample-Object-1 is garbage collected

Anonymous Objects: The reference of the anonymous object is not stored anywhere, therefore after the first execution, the object cannot be called again.

public class Demo
{
    String str;
    Demo(String str)
    {
        this.str = str;
    }
    public void demoMethod()
    {
        System.out.println("Inside the method");
    }
    protected void finalize() throws Throwable {
      System.out.println(this.str + " is garbage collected");
   }
    public static void main(String []args)
    {
       new Demo("Sample-Object-1").demoMethod();
       System.gc();
    }
}

The output of the above program is:

Inside the method
Sample-Object-1 is garbage collected

Q 20) In which programming paradigm Java 8 falls.

Ans)

  • Object-Oriented Programming Language
  • Functional Programming Language
  • Procedural Programming Language
  • Logic Programming Language

Q 21) What is the difference between metaspace and PermGen?

Ans) 

PermGenMetaSpace
This is the memory area for storing class data like static variables, byte code, etc.The PermGen method area is replaced with MetaSpace.
64 Mb is allocated for PermGen by default.It can by default auto increase its size.
It is a special heap spaceSince Java 8, it is now a separate memory area in the native OS

Q22) What is servlet context?

Ans 22) Servlet Context is an interface belonging to the javax.servlet package. The interface defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

There is one context per “web application” per Java Virtual Machine. An object of ServletContext is created by the web container at the time of deploying the project, the object can be used to get configuration information from the web.xml file.

Q23) What will happen if the run() method of the Thread class is overridden?

Ans 23) If we don’t override The run() method of java.lang.Runnable interface nothing will happen as such. The program will compile successfully but no output will be generated because the run() method is with an empty implementation.

Consider the following example:

class Demo extends Thread{
// run() method is not overridden
     
}
public class DontOverrideRun { 
  public static void main(String[] args) { 
         System.out.println("Main method execution started"); 
         Demo thread1=new Demo(); 
         thread1.start(); 
         System.out.println("Main method execution ended"); 
  } 
}

The above program will compile successfully and will generate the following output.

Main method execution started
Main method execution ended

Q24) Difference between User Thread and Daemon Thread.

Ans 24)

User ThreadDaemon Thread
The JVM waits until user threads finish their work. It never exits until all user threads finish their work.The JVM will wait for daemon threads to finish their work. The JVM will exit as soon as all user thread finish their work,
User threads are created by the user to execute tasks concurrently.Daemon threads are created by the JVM.
They are designed to do some specific critical task of an applicationThey are designed to support user threads.
They are high-priority threadsThey are low-priority threads.

Q25) What is a Thread Pool?

Ans) A thread pool reuses previously existing threads to execute current tasks and offers a solution to the problem of thread cycle overhead and resource thrashing. Alternatively, using a thread pool can make it easier to control how many threads are active at a time.

Thread pools are often used in multi-threaded servers. Each connection arriving at the server via the network is wrapped as a task and passed on to a thread pool. The threads in the thread pool will process the requests on the connections concurrently.

Q26) What are volatile variables in Java?

Ans) The volatile keyword in Java is used to prevent modification of the value of a variable by different threads making it thread-safe. The volatile keyword does not cache the value of the variable, and the variable will always be read from the main memory.

Q27) What is Thread Starvation?

Ans) A situation where a thread won’t be able to have regular access to shared resources and is unable to proceed or make progress. This usually happens when other threads that have higher priority occupy the resources for too long.

Q28) Is it possible that each thread can have its own stack in multithreaded programming?

Ans) Each thread maintains its own stack area in memory in multithreaded programming. Because of the separate stack area, every thread is independent of each other.

Q29) Can you start a thread twice?

Ans) It is not possible to restart a thread. Running a thread again will throw a runtime exception i.e. java.lang.IllegalThreadStateException. 

class Demo extends Thread{
    public void run()
    {
        System.out.println("Thread is running");
    }
}
public class SampleThreadExecution { 
  public static void main(String[] args) { 
         System.out.println("Main method execution started"); 
         Demo thread1=new Demo(); 
         thread1.start(); 
         // Restarting the thread once again
         thread1.start();
         System.out.println("Main nethod execution ended"); 
  } 
}

The output of the above program is:

Q 30) What is the default method and why is it required?

Ans) Methods that are created inside the interface and tagged with default are known as Default Methods. The concept was introduced in Java 8 and is also known as non-abstract methods.

Consider the following example

interface DemoInterface
{
    default void display()
    {
        System.out.println("Default Method Executed");
    }
}


public class Demo implements DemoInterface
{
   public static void main(String[] args) 
   { 
       Demo obj = new Demo();
       obj.display();
   }
}

The default methods were introduced to provide backward compatibility so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class. 

Q 31) What is the lifecycle of a Servlet?

Ans) The lifecycle of the servlet is:

  • Servlet class is loaded
  • An instance of servlet class is created
  • The init() method is invoked
  • The service() method is invoked.
  • The destroy() method is invoked.

Q 32) Define JDBC drivers?

Ans) The JDBC driver is a software component that enables Java applications to interact with the database. JDBC makes it possible to establish a connection with a data source, send queries and update statements and process the results.

There are four types of JDBC drivers:

  • JDBC-ODBC bridge driver
  • Native-API driver
  • Network Protocol Driver
  • Thin driver

Q33) What is synchronization? Why use it?

Ans) Synchronization is a process in Java that enables a simple strategy to avoid thread interference and memory consistency errors. Synchronization can be achieved in three ways:

  • By using the Synchronized method
  • By synchronized block
  • By static synchronization

Synchronization makes sure that resource will be used by one thread at a time when one thread tries to access a shared resource. A real-life example will be if you have a URL and you need to know the number of requests made to it, in that case, two simultaneous requests can make the count erratic.

Q34) What is a Method Reference?

Ans 34)  Method Reference is a compact way of referring to a method or a functional interface. Double colon(::) is used for describing the method reference.

Syntax of Method Reference is class::methodName

Examples: Integer:: parseInt(str)

Frequently Asked Questions

What are the basic questions asked in the Java interview?

As a beginner questions related to Programming fundamentals, Input, and Output operations, Basic concepts are asked. You must refer to our structured interview questions listing to quickly revise all concepts.

What is Java best answer?

Java is a simple, fast, efficient, and secure programming language first developed by Sun Microsystem in 1995.Java was originally designed for embedded network applications running on multiple platforms. It is a portable, object-oriented, interpreted language. Most of the companies choose Java to build Desktop, Web, and Mobile applications.

What are the interview questions in Java for freshers?

You must refer to our structured questions listing to prepare for your next big tech interview
Beginner Level Questions
Intermediate Level Questions
Advanced Level Questions

What should I prepare for the Java interview?

To crack the Java interview, you must have sound knowledge of Data Structures and Algorithms, OOPs concepts, Java fundamentals, Collection Framework, JVM internals, JDBC. To get a structured question listing, you may refer to 100 Java Interview Question Series and for full preparation, you may try our Guided Path.

How do I crack Java?

The first step in preparing for an interview is to brush up on fundamental knowledge. You may expect questions related to fundamentals, OOPs concepts, DSA, Multithreading, Garbage collection, Collection Framework, JVM internals, Regular Expressions, etc. The difficulty level depends on experience and the job profile. You may refer to the 100 Java Interview Questions Series(Beginner, Intermediate, and Advanced) to get a listing of frequently asked Interview Questions along with detailed explanations of the solutions.

Key Takeaways

The article discussed frequently asked Java interview questions for professionals with an intermediate level of experience. Once you are done with this, you may check out our Interview Preparation Course to level up your programming journey and to get placed at your dream company. 

By: Manvi Chaddha