Java Intermediate Interview Questions

Table of Contents

Previous:-Java Interview Questions for Freshers

31. Apart from the security aspect, what are the reasons behind making strings immutable in Java?

A String is made immutable due to the following reasons:

  • String Pool: Designers of Java were aware of the fact that String data type is going to be majorly used by the programmers and developers. Thus, they wanted optimization from the beginning. They came up with the notion of using the String pool (a storage area in Java heap) to store the String literals. They intended to decrease the temporary String object with the help of sharing. An immutable class is needed to facilitate sharing. The sharing of the mutable structures between two unknown parties is not possible. Thus, immutable Java String helps in executing the concept of String Pool.
  • Multithreading: The safety of threads regarding the String objects is an important aspect in Java. No external synchronization is required if the String objects are immutable. Thus, a cleaner code can be written for sharing the String objects across different threads. The complex process of concurrency is facilitated by this method.
  • Collections: In the case of Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get modified during the period when it resides in the HashMaps. Consequently, the retrieval of the desired data is not possible. Such changing states pose a lot of risks. Therefore, it is quite safe to make the string immutable.

32. What is a singleton class in Java? And How to implement a singleton class?

Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed. 

Understand this with the help of an example-:

Consider the water jug in the office and if every employee wants that water then they will not create a new water jug for drinking water. They will use the existing one with their own reference as a glass. So programmatically it should be implemented as –

class WaterJug{
   private int waterQuantity = 500;
   private WaterJug(){}
   private WaterJug object = null;
   // Method to provide the service of Giving Water.
   public int getWater(int quantity){
       waterQuantity -= quantity;
       return quantity;
   // Method to return the object to the user.
   public static Waterjug getInstance(){
       // Will Create a new object if the object is not already created and return the object.
       if(object == null){
           object = new WaterJug();
       return object;

In the above class, the Constructor is private so we cannot create the object of the class. But we can get the object by calling the method getInstance(). And the getInstance is static so it can be called without creating the object. And it returns the object. Now with that object, we can call getWater() to get the water.

Waterjug glass1 = WaterJug.getInstance();

We can get the single object using this getInstance(). And it is static, so it is a thread-safe singleton class. Although there are many ways to create a thread-safe singleton class. So thread-safe classes can also be:

  • When singletons are written with double-checked locking, they can be thread-safe.
  • We can use static singletons that are initialized during class loading. Like we did in the above example.
  • But the most straightforward way to create a thread-safe singleton is to use Java enums.

33. Which of the below generates a compile-time error? State the reason.

  1. int[] n1 = new int[0];
  2. boolean[] n2 = new boolean[-200];
  3. double[] n3 = new double[2241423798];
  4. char[] ch = new char[20];

We get a compile-time error in line 3. The error we will get in Line 3 is – integer number too large. It is because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number (2241423798) is beyond the capacity of the integer. The maximum array size we can declare is – (2147483647).

Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The program will compile fine. But we get the runtime exception in line 2. The exception is – NegativeArraySizeException

Here what will happen is – At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.

34. How would you 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. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)
  • Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used 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.
// String
String first = "SoftwareTechIT";
String second = new String("SoftwareTechIT");
// StringBuffer
StringBuffer third = new StringBuffer("SoftwareTechIT");
// StringBuilder
StringBuilder fourth = new StringBuilder("SoftwareTechIT");

35. Using relevant properties highlight the differences between interfaces and abstract classes.

  • Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
  • Variable types: Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
  • Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
  • Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
  • Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;

Abstract class example:

public abstract class Athlete {
public abstract void walk();

Interface example:

public interface Walkable {
void walk();

36. Is this program giving a compile-time error? If Yes then state the reason and number of errors it will give. If not then state the reason.

abstract final class SoftwareTechIT{
2.    public abstract void printMessage();
3. }
4. class ScalarAcademy extends SoftwareTechIT{
5.    public void printMessage(){
6.        System.out.println("Welcome to Scalar Academy By SoftwareTechIT");
7.    }
8. }
9. class ScalarTopics extends ScalarAcademy{
10.    public void printMessage(){
11.        System.out.println("Welcome to Scalar Topics By Scalar Academy");
12.    }
13. }
public class Main{
        public static void main(String[] args) {
            SoftwareTechIT ib = new ScalarTopics();

The above program will give a compile-time error. The compiler will throw 2 errors in this.

  • [Illegal Combination of modifiers: abstract and final] at line 1.
  • [Cannot inherit from final ‘SoftwareTechIT’] at line 4.

It is because abstract classes are incomplete classes that need to be inherited for making their concrete classes. And on the other hand, the final keywords in class are used for avoiding inheritance. So these combinations are not allowed in java.

37. What is a Comparator in java?

Consider the example where we have an ArrayList of employees like( EId, Ename, Salary), etc. Now if we want to sort this list of employees based on the names of employees. Then that is not possible to sort using the Collections.sort() method. We need to provide something to the sort() function depending on what values we have to perform sorting. Then in that case a comparator is used.

Comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values. 

38. In Java, static as well as private method overriding is possible. Comment on the statement.

The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.

The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.

39. What makes a HashSet different from a TreeSet?

Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.

  • Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
  • Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
  • Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons.
  • Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects.

40. Why is the character array preferred over string for storing confidential information?

In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.

As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.

41. What do we get in the JDK file?

  • JDK– For making java programs, we need some tools that are provided by JDK (Java Development Kit). JDK is the package that contains various tools, Compiler, Java Runtime Environment, etc.
  • JRE –  To execute the java program we need an environment. (Java Runtime Environment) JRE contains a library of Java classes +  JVM. What are JAVA Classes?  It contains some predefined methods that help Java programs to use that feature, build and execute. For example – there is a system class in java that contains the print-stream method, and with the help of this, we can print something on the console.
  • JVM – (Java Virtual Machine) JVM  is a part of JRE that executes the Java program at the end.  Actually, it is part of JRE, but it is software that converts bytecode into machine-executable code to execute on hardware.

42. What are the differences between JVM, JRE and JDK in Java?

AbbreviationJava Development KitJava Runtime EnvironmentJava Virtual Machine
DefinitionJDK is a complete software development kit for developing Java applications. It comprises JRE, JavaDoc, compiler, debuggers, etc.JRE is a software package providing Java class libraries, JVM and all the required components to run the Java applications.JVM is a platform-dependent, abstract machine comprising of 3 specifications – document describing the JVM implementation requirements, computer program meeting the JVM requirements and instance object for executing the Java byte code and provide the runtime environment for execution.
Main PurposeJDK is mainly used for code development and execution.JRE is mainly used for environment creation to execute the code.JVM provides specifications for all the implementations to JRE.
Tools providedJDK provides tools like compiler, debuggers, etc for code developmentJRE provides libraries and classes required by JVM to run the program.JVM does not include any tools, but instead, it provides the specification for implementation.
SummaryJDK = (JRE) + Development toolsJRE = (JVM) + Libraries to execute the applicationJVM = Runtime environment to execute Java byte code.

43. What are the differences between HashMap and HashTable in Java?

HashMap is not synchronized thereby making it better for non-threaded applications.HashTable is synchronized and hence it is suitable for threaded applications.
Allows only one null key but any number of null in the values.This does not allow null in both keys or values.
Supports order of insertion by making use of its subclass LinkedHashMap.Order of insertion is not guaranteed in HashTable.

44. What is the importance of reflection in Java?

  • The term reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
  • Consider an example where we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. The static typing system of Java doesn’t allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to scan the object and identify if it has any method called “fooBar()” and only then call the method if needed.
Method methodOfFoo = fooObject.getClass().getMethod("fooBar", null);
methodOfFoo.invoke(fooObject, null);
  • Using reflection has its own cons:
    • Speed — Method invocations due to reflection are about three times slower than the direct method calls.
    • Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
    • Traceability — Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. One has to deep dive into the invoke() and proxy() method logs to identify the root cause.
  • Hence, it is advisable to follow solutions that don’t involve reflection and use this method as a last resort.

45. What are the different ways of threads usage?

  • We can define and implement a thread in java using two ways:
    • Extending the Thread class
class SoftwareTechITThreadExample extends Thread
   public void run()
       System.out.println("Thread runs...");  
   public static void main(String args[])
       SoftwareTechITThreadExample ib = new SoftwareTechITThreadExample();  
  • Implementing the Runnable interface
class SoftwareTechITThreadExample implements Runnable
   public void run()
       System.out.println("Thread runs...");  
   public static void main(String args[])
       Thread ib = new Thread(new SoftwareTechITThreadExample()); 
  • Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
  • start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.

46. What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?

There are a total of 3 different types of priority available in Java. 

MIN_PRIORITY: It has an integer value assigned with 1.
MAX_PRIORITY: It has an integer value assigned with 10.
NORM_PRIORITY: It has an integer value assigned with 5.

In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM. 

47. What is the difference between the program and the process?

  • A program can be defined as a line of code written in order to accomplish a particular task. Whereas the process can be defined as the programs which are under execution. 
  • A program doesn’t execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.

48. What is the difference between the ‘throw’ and ‘throws’ keyword in java?

  • The ‘throw’ keyword is used to manually throw the exception to the calling method.
  • And the ‘throws’ keyword is used in the function definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.

Example – 

class Main {
   public static int testExceptionDivide(int a, int b) throws ArithmeticException{
       if(a == 0 || b == 0)
           throw new ArithmeticException();
       return a/b;
   public static void main(String args[]) {
           testExceptionDivide(10, 0);
       catch(ArithmeticException e){
           //Handle the exception

Here in the above snippet, the method testExceptionDivide throws an exception. So if the main method is calling it then it must have handled the exception. Otherwise, the main method can also throw the exception to JVM.

And the method testExceptionDivide ‘throws’ the exception based on the condition.

49. What are the differences between constructor and method of a class in Java?

Constructor is used for initializing the object state.Method is used for exposing the object’s behavior.
Constructor has no return type.Method should have a return type. Even if it does not return anything, return type is void.
Constructor gets invoked implicitly.Method has to be invoked on the object explicitly.
If the constructor is not defined, then a default constructor is provided by the java compiler.If a method is not defined, then the compiler does not provide it.
The constructor name should be equal to the class name.The name of the method can have any name or have a class name too.
A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn’t make sense. Java throws compilation error saying – modifier final not allowed hereA method can be defined as final but it cannot be overridden in its subclasses.
Final variable instantiations are possible inside a constructor and the scope of this applies to the whole class and its objects.A final variable if initialised inside a method ensures that the variable cant be changed only within the scope of that method.

50. Identify the output of the below java program and Justify your answer.

class Main {
    public static void main(String args[]) {
        Scaler s = new Scaler(5);
class SoftwareTechIT{
        System.out.println(" Welcome to SoftwareTechIT ");
class Scaler extends SoftwareTechIT{
        System.out.println(" Welcome to Scaler Academy ");
    Scaler(int x){
        System.out.println(" Welcome to Scaler Academy 2");

The above code will throw the compilation error. It is because the super() is used to call the parent class constructor. But there is the condition that super() must be the first statement in the block. Now in this case, if we replace this() with super() then also it will throw the compilation error. Because this() also has to be the first statement in the block. So in conclusion, we can say that we cannot use this() and super() keywords in the same block.

51. Java works as “pass by value” or “pass by reference” phenomenon?

Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java. However, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:

  • Case 1: When the object is pointed to another location: In this case, the changes made to that object do not get reflected the original object before it was passed to the method as the reference points to another location.

For example:

class SoftwareTechITTest{
   int num;
   SoftwareTechITTest(int x){ 
       num = x; 
       num = 0; 
class Driver {
   public static void main(String[] args)
       //create a reference
       SoftwareTechITTest ibTestObj = new SoftwareTechITTest(20);
       //Pass the reference to updateObject Method
       //After the updateObject is executed, check for the value of num in the object.
   public static void updateObject(SoftwareTechITTest ibObj)
       // Point the object to new reference
       ibObj = new SoftwareTechITTest();
       // Update the value 
       ibObj.num = 50;
  • Case 2: When object references are not modified: In this case, since we have the copy of reference the main object pointing to the same memory location, any changes in the content of the object get reflected in the original object.

For example:

class SoftwareTechITTest{
   int num;
   SoftwareTechITTest(int x){ 
       num = x; 
       num = 0
class Driver{
   public static void main(String[] args)
       //create a reference
       SoftwareTechITTest ibTestObj = new SoftwareTechITTest(20);
       //Pass the reference to updateObject Method
       //After the updateObject is executed, check for the value of num in the object.
   public static void updateObject(SoftwareTechITTest ibObj)
       // no changes are made to point the ibObj to new location
       // Update the value of num
       ibObj.num = 50;

52. What is the ‘IS-A ‘ relationship in OOPs java?

‘IS-A’ relationship is another name for inheritance. When we inherit the base class from the derived class, then it forms a relationship between the classes. So that relationship is termed an ‘IS-A’ Relationship.

Example – Consider a Television (Typical CRT TV). Now another Smart TV  that is inherited from television class. So we can say that the Smart iv is also a TV. Because CRT TV things can also be done in the Smart TV.

So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ].

53. Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?

StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.

54. How to not allow serialization of attributes of a class in Java?

  • In order to achieve this, the attribute can be declared along with the usage of transient keyword as shown below:
public class SoftwareTechITExample { 
   private transient String someInfo; 
   private String name;
   private int id;
   // :
   // Getters setters
   // :
  • In the above example, all the fields except someInfo can be serialized.

55. What happens if the static modifier is not included in the main method signature in Java?

There wouldn’t be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError” error at the runtime.

56. Consider the below program, identify the output, and also state the reason for that.

public class Main{
public static void main(String[] args) {
 System.out.println(" Hello. Main Method. ");
public static void main(int[] args) {
 System.out.println(" Hello. Main Method2. ");

The output of the above program will be Hello. Main Method. This is because JVM will always call the main method based on the definition it already has. Doesn’t matter how many main methods we overload it will only execute one main method based on its declaration in JVM.

57. Can we make the main() thread a daemon thread?

In java multithreading, the main() threads are always non-daemon threads. And there is no way we can change the nature of the non-daemon thread to the daemon thread.

58. What happens if there are multiple main methods inside one class in Java?

The program can’t compile as the compiler says that the method has been already defined inside the class.

59. What do you understand by Object Cloning and how do you achieve it in Java?

  • It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:
protected Object clone() throws CloneNotSupportedException{
 return (Object)super.clone();
  • In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

60. How does an exception propagate in the code?

When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.

61. How do exceptions affect the program if it doesn’t handle them?

Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application tries to get the file from storage and the file doesn’t exist (This is the case of exception in java). And if this case is not handled properly then the application will crash. This will be a bad experience for users.  This is the type of error that cannot be controlled by the programmer. But programmers can take some steps to avoid this so that the application won’t crash. The proper action can be taken at this step.

62. Is it mandatory for a catch block to be followed after a try block?

No, it is not necessary for a catch block to be present after a try block. – A try block should be followed either by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the throws clause of the method.

63. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?

public int someMethod(int i){
       //some statement
       return 1;
   }catch(Exception e){
       //some statement
       return 999;
       //finally block statements

finally block will be executed irrespective of the exception or not. The only case where finally block is not executed is when it encounters ‘System.exit()’ method anywhere in try/catch block.

64. Can you call a constructor of a class inside the another constructor?

Yes, the concept can be termed as constructor chaining and can be achieved using this().

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

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 which are located at various sites in the memory. Thus, storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes place 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, hence every element does not require any reference to the next element.

66. Why does the java array index start with 0?

It is because the 0 index array avoids the extra arithmetic operation to calculate the memory address.

Example – Consider the array and assume each element takes 4-byte memory space. Then the address will be like this –

Now if we want to access index 4. Then internally java calculates the address using the formula-

[Base Address + (index * no_of_bytes)]. So according to this. The starting address of the index 4 will be – [100 + (4*4)] = 116. And exactly that’s what the address is calculated. 
Now consider the same with 1 index Array –

Now if we apply the same formula here. Then we get – 116 as the starting address of the 4th index. Which is wrong. Then we need to apply formula – [Base Address + ((index-1) * no_of_bytes)].

And for calculating this, an extra arithmetic operation has to be performed. And consider the case where millions of addresses need to be calculated, this causes complexity. So to avoid this, ) the index array is supported by java.

67. Why is the remove method faster in the linked list than in an array?

In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, indexes are used. So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is costlier than the adjustment of references.

Example – To Delete from the front of the linked list, internally the references adjustments happened like this.

The only thing that will change is that the head pointer will point to the head’s next node. And delete the previous node. That is the constant time operation.

Whereas in the ArrayList, internally it should work like this-

For deletion of the first element, all the next element has to move to one place ahead. So this copying value takes time. So that is the reason why removing in ArrayList is slower than LinkedList.

68. How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses.

There are a total of 4 overloaded methods for add() and addAll() methods available in List Interface. The below table states the description of all.

Return TypeMethod Description
booleanadd(Element e): This method is used for adding the element at the end of the List. The Datatype of the element is of any type it has been initially assigned with. It returns the boolean indicating successfully inserted or not.
voidadd(int index, Element e): This method is the overloaded version of add() method. In this, along with the element, the index is also passed to the method for the specific index the value needs to be inserted. 
booleanaddAll(Collection <extends ? Element > c): This method helps to add all elements at the end of collections from the list received in the parameter. It contains an iterator that helps to iterate the list and add the elements to the collection.
booleanaddAll(int index, Collection <extends ? Element > c): This is the overloaded method for addAll() method. In this along with the list, we can pass the specified index from which the list elements need to be added.

69. How does the size of ArrayList grow dynamically? And also state how it is implemented internally.

ArrayList is implemented in such a way that it can grow dynamically. We don’t need to specify the size of ArrayList. For adding the values in it, the methodology it uses is –

1. Consider initially that there are 2 elements in the ArrayList. [2, 3].

2. If we need to add the element into this. Then internally what will happen is-

  • ArrayList will allocate the new ArrayList of Size (current size + half of the current size). And add the old elements into the new. Old – [2, 3],    New – [2, 3, null, null].
  • Then the new value will be inserted into it. [2, 3, 4, null]. And for the next time, the extra space will be available for the value to be inserted.

3. This process continues and the time taken to perform all of these is considered as the amortized constant time. 

This is how the ArrayList grows dynamically. And when we delete any entry from the ArrayList then the following steps are performed –

1. It searches for the element index in the array. Searching takes some time. Typically it’s O(n) because it needs to search for the element in the entire array.

2. After searching the element, it needs to shift the element from the right side to fill the index.

So this is how the elements are deleted from the ArrayList internally. Similarly, the search operations are also implemented internally as defined in removing elements from the list (searching for elements to delete).

This Post Has 3 Comments

Leave a Reply