Saturday, March 14, 2026

isAlive() And join() Methods in Java Multi-Threading

In this tutorial we'll see what are isAlive() and join() methods in Java, which give you precise control over thread lifecycle management, ensuring smoother synchronization and more predictable program behavior.

When working with multiple threads in Java, developers typically create threads and invoke the start() method to begin execution. Once started, the Java Virtual Machine (JVM) automatically calls the run() method when system resources and CPU are available. The thread then executes its task and eventually transitions to the terminated state.

But what if you need to trigger further processing only after a specific thread has finished? How can you reliably check whether a thread is still running or has ended?

This is where the isAlive() and join() methods in Java come into play. These two powerful methods in Java’s multithreading API allow you to:

  • isAlive()– Quickly verify if a thread is still active.
  • join()– Pause the execution of the current thread until the target thread completes.

isAlive() method in Java

isAlive() method is the member of the Thread class and its general form is–

public final boolean isAlive()

The isAlive() method in Java is used to check whether a thread is currently active. A thread is considered alive if it has been started using the start() method and has not yet reached the terminated state. When you call isAlive() on a thread object, it returns:

  • true- if the thread is still running or in a runnable state.
  • false- if the thread has finished execution or has not been started

This makes the isAlive() method a simple yet powerful way to monitor thread lifecycle and ensure that your program executes tasks in the correct order. By combining isAlive() with other multithreading techniques, developers can build more predictable and synchronized applications.

join() method in Java

Join() method is used when you want to wait for the thread to finish. Its general form is–

public final void join() throws InterruptedException

This method waits until the thread on which it is called terminates. There are three overloaded join functions.

  • public final void join()- Waits indefinitely for this thread to die.
  • public final void join(long millis)-Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
  • public final void join(long millis, int nanos)- Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.

Java Example code using join and isAlive()

Imagine a situation where your application spawns multiple threads to perform heavy computations. You want the user to see the message "Processing is done" only after all threads have completed their tasks.

In such cases, the join() method in Java is the ideal solution. By calling join() on a thread, the current thread (often the main thread) pauses execution until the specified thread finishes. This ensures that your program doesn’t move forward prematurely and that the final message is displayed only after all computations are complete

Now first let’s try to do something like this without using join() method.

class MyRunnableClass implements Runnable{
  @Override
  public void run() {
    for(int i = 0; i < 5 ; i++){
      System.out.println(Thread.currentThread().getName() + " i - " + i);
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }    
}
public class JoinExample {
  public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnableClass(), "t1");
    Thread t2 = new Thread(new MyRunnableClass(), "t2");
    Thread t3 = new Thread(new MyRunnableClass(), "t3");
     
    t1.start();
    t2.start();
    t3.start();
        
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());
        
    /*try {
        t1.join();        
        t2.join();
        t3.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }        
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());*/        
    System.out.println("Processing finished");
  }
}

Output

t1 Alive - true
t2 Alive - true
t3 Alive - true
Processing finished
t3 i - 0
t1 i - 0
t2 i - 0
t3 i - 1
t1 i - 1
t2 i - 1
t2 i - 2
t1 i - 2
t3 i - 2
t3 i - 3
t1 i - 3
t2 i - 3
t3 i - 4
t1 i - 4
t2 i – 4

Here it can be seen that the message is displayed much before the actual processing has finished.

Now let’s uncomment the code related to join and run the program again.

class MyRunnableClass implements Runnable{
  @Override
  public void run() {
    for(int i = 0; i < 5 ; i++){
      System.out.println(Thread.currentThread().getName() + " i - " + i);
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
}
public class JoinExample {
  public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnableClass(), "t1");
    Thread t2 = new Thread(new MyRunnableClass(), "t2");
    Thread t3 = new Thread(new MyRunnableClass(), "t3");
     
    t1.start();
    t2.start();
    t3.start();
    
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());
        
    try {
      t1.join();        
      t2.join();
      t3.join();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
        
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());
    
    System.out.println("Processing finished");
  }
}

Output

t1 Alive - true
t2 Alive - true
t3 Alive - true
t2 i - 0
t3 i - 0
t1 i - 0
t1 i - 1
t2 i - 1
t3 i - 1
t3 i - 2
t1 i - 2
t2 i - 2
t1 i - 3
t2 i - 3
t3 i - 3
t2 i - 4
t3 i - 4
t1 i - 4
t1 Alive - false
t2 Alive - false
t3 Alive - false
Processing finished

Now see how message is displayed only when the processing is actually finished and all the threads are terminated. The second print statements using isAlive() method confirms that the threads are not running any more.

That's all for this topic isAlive() And join() Methods in Java Multi-Threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between sleep And wait in Java Multi-Threading
  2. Creating a Thread in Java
  3. Synchronization in Java - Synchronized Method And Block
  4. Race Condition in Java Multi-Threading
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. Creating Custom Exception Class in Java
  2. Interface Static Methods in Java
  3. Fail-Fast Vs Fail-Safe Iterator in Java
  4. Java Lambda Expression And Variable Scope
  5. Find All Permutations of a Given String Java Program
  6. Abstraction in Java
  7. Java ReentrantReadWriteLock With Examples
  8. Bean Scopes in Spring With Examples

Friday, March 13, 2026

static Method Overloading or Overriding in Java

One of the most frequently asked interview questions in Java is: Can we overload static methods in Java? Can we override static methods in Java? These questions often confuse developers, yet understanding them is essential for mastering object-oriented programming concepts.

In this tutorial, we’ll explore the rules and limitations of static method overloading and static method overriding in Java. To set the stage, we’ll first revisit the basics of method overloading and method overriding in Java, and then dive into how these concepts apply specifically to static methods.

  • Method Overloading- When two or more methods with in the same class or with in the parent-child relationship classes have the same name, but the parameters are different in types or number the methods are said to be overloaded.
    Refer Method overloading in Java for better understanding.
  • Method Overriding- In a parent-child relation between classes, if a method in subclass has the same signature as the parent class method then the method is said to be overridden by the subclass and this process is called method overriding.
    Refer Method overriding in Java for better understanding.

Static method overloading in Java

In Java, static methods can be overloaded just like instance methods. This means you can define two or more static methods with the same name, as long as their parameter lists differ in type or number. Overloading static methods works exactly the same way as overloading non-static methods, and it is resolved at compile time.

Fail-Fast Vs Fail-Safe Iterator in Java

Understanding the difference between fail fast and fail safe iterator in Java is not only a popular Java Collections interview question but also a crucial concept for every developer. The collections which are there from Java 1.2 (or even legacy) like ArrayList, Vector, HashSet all have fail-fast iterator whereas Concurrent collections added in Java 1.5 like ConcurrrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet have fail-safe iterator.

In this guide, we’ll break down the key differences between fail-fast and fail-safe iterator in Java, highlight their behavior with practical examples, and then walk through Java programs that demonstrate how each type of iterator works in real-world scenarios.

Thursday, March 12, 2026

Interface in Java With Examples

In this tutorial, you’ll dive deep into the concept of Interface in Java, a powerful feature that enables developers to achieve complete abstraction in Java. An interface defines what a class must do, but leaves the details of how it should be done to the implementing class. This makes interfaces a cornerstone of clean, modular, and flexible Java programming


How does Interface differ from a class

Although an Interface in Java looks syntactically similar to a class, it differs in several important ways:

  • Interfaces cannot have instance variables, meaning they don’t maintain state.
  • Methods inside an interface are declared without a body and end with a semicolon.
  • An interface cannot be instantiated, so constructors are not allowed.
  • A class implements an interface rather than extending it.
  • An interface itself can extend multiple interfaces, supporting multiple inheritance in Java.

Please note that, Java 8 onward, it is possible to add a default implementation to a method in an interface as well as interface static methods and even Private Methods in Java Interface Java 9 onward, here we'll discuss interfaces in its normal form.

General form of interface in Java

access_modifier interface name {
 type final_var1 = value;
 type final_var2 = value;
 ----
 ----
 return_type method_name1(param_list);
 return_type method_name2(param_list);
 ----
 ----
}

When no access modifier is specified, an Interface in Java has default access, meaning it is visible only to other members within the same package. However, when an interface is declared as public, it becomes universally accessible and can be used by any program across different packages.

For top level interfaces only these two access modifiers (default and public) are permitted, there are nested interfaces which can be declared as public, private or protected. We'll discuss nested interfaces later in the post.

All variables declared inside an Interface in Java are implicitly public, static, and final. This means they act as constants: they must be initialized at the time of declaration and cannot be modified by the implementing class. Such behavior ensures consistency and prevents accidental changes across different implementations.

Similarly, all methods within an Interface in Java are implicitly abstract and public. These methods define the contract that any implementing class must fulfill, but they do not provide the actual implementation. By enforcing this rule, interfaces promote clean design, flexibility, and a clear separation of responsibilities in Java applications

Note that Java 9 onward you can also add private methods to a Java interface. Please refer Private Methods in Java Interface to know more about adding private methods in a Java interface.

Java Interface example

public interface MyInterface {
 int i = 10;
 Number method1();
 void method2(String Id);
}

Here is an interface MyInterface which has one variable i, which is public static final implicitly. There are 2 methods, one has no return type, one returns Number.

Implementing an Interface in Java

In Java, class uses implements keyword to implement an interface.

public class MyClass implements MyInterface { 
 public Integer method1() {
  System.out.println("in method 1" + i);  
  return null;
 }

 public void method2(String Id) {
  System.out.println("in method 2");  
 }
 public static void main(String[] args) {
  
 }
}

When implementing methods defined in interfaces there are several important points-

  • A class can implement more than one interface, in that case interfaces are separated with a comma.
     class class_name implements interface 1, interface 2{
     }
     
  • The methods of an interface that are implemented by a class must be declared public i.e. visibility can't be reduced.
  • The signature of the interface method must remain same while implementing it. In case of return type subclass of the return type as defined in interface can also be used. As in the above program method1 has the return type Number where as in the implemented method in the class has the return type Integer. It is permissible as Integer is the sub-class of Number.
  • The initialized variable in the interface is constant and it is not allowed to change that value in the implementing class. For example in the above program there is a variable i with value 10 if we try to change that value to 20 in the implementing class it will throw compiler error "The final field MyInterface.i cannot be assigned".
  • Any number of classes can implement an interface and each class is free to provide their own implementation. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.
  • A class can extend only one class, but a class can implement many interfaces. Which means multiple inheritance is not allowed in Java
  • An interface can extend another interface, similar to the way that a class can extend another class.

Extending an interface in Java

Just like class, if an interface in Java is inheriting from another interface it uses extends keyword.
An interface, unlike class, can extend more than one interface. If a class implements an interface that inherits another interface, it must provide implementation for all the methods that are there in the inheritance chain of interface.

Extending an interface Java Example

// Interface
public interface MyInterface {
 int i = 10;
 Number method1();
 void method2(String Id);
}
// extending interface
interface B extends MyInterface{
 void method3();
}

// class implements all methods of MyInterface and B
public class MyClass implements B {
 
 public Integer method1() {
  System.out.println("in method 1" + i);  
  return null;
 }

 public void method2(String Id) {
  System.out.println("in method 2");  
 }

 public void method3() {
  System.out.println("in method 3");  
 }
 public static void main(String[] args) {
  
 }
}

It can be seen that the class Myclass has to implement all the methods in the inheritance chain of the interface.

Partial implementation of interface by a class

If a class implements an interface but does not implement all the methods of that interface then that class must be declared as abstract.

public interface MyInterface {
 void method1();
 String method2(String Id);
}
implemnting java interface methods

Compiler error that class must implement methods declared in MyInterface interface.

But we can declare the class as abstract in that case

public abstract class AbstractClassDemo implements MyInterface {
 public static void main(String[] args) {
  System.out.println();
 }
}

Nested Interfaces in Java

An interface or a class can have another interface. Such an interface is known as nested interface or a member interface in Java.
A nested interface can be declared as public, private or protected. When a nested interface is used outside, it must be used as a fully qualified name i.e. must be qualified by the name of the class or interface of which it is a member.

Java nested interface Example

// Class with nested interface
class A{
 public interface TestInterface{
  void displayValue(String value);
 }
}

// class implementing the nested interface
class B implements A.TestInterface{
 public void displayValue(String value) {
  System.out.println("Value is " + value);
 }
}

public class MyClass{ 
 public static void main(String[] args) {
  // reference of class B assigned to nested interface
  A.TestInterface obRef = new B();
  obRef.displayValue("hello");
 }
}

Output

Value is hello

Interface and run time polymorphism

As we already know that there can't be an object of an interface, but interface can be used to create object references. As run time polymorphism in Java is implemented through the use of super class reference thus interface can be used to provide super class reference which holds references of sub-classes at run time and provide the appropriate functionality.

Run time polymorphism using interface Java Example

Let's assume that in an application there is a need to handle payment done through several modes like; cash, cheque, credit card etc. and based on the mode of the payment the functionality may be different.
This can be achieved through an interface where the interface defines a method payment and then several classes implement that interface and provide the functionality for the payment method according to the business needs. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.

public interface PaymentInt {
 public void payment(double amount);
}
// Cash Payment implementation of Payment interface
class CashPayment implements PaymentInt{
 // method implementation according to cash payment functionality
 public void payment(double amount) {
  System.out.println("Cash Payment of amount " + amount);
 }
}

//Cheque Payment implementation of Payment interface
class ChequePayment implements PaymentInt{
 // method implementation according to cheque payment functionality
 public void payment(double amount) {
  System.out.println("Cheque Payment of amount " + amount);  
 }
}

//CreditCard Payment implementation of Payment interface
class CreditCardPayment implements PaymentInt{
 // method implementation according to credit card payment functionality
 public void payment(double amount) {
  System.out.println("CreditCard Payment of amount " + amount);
 }
}

public class PaymentDemo {
 public static void main(String[] args) {
  // Payment interface reference holding the CashPayment obj
  PaymentInt paymentInt = new CashPayment();
  paymentInt.payment(134.67);
  // Payment interface reference holding the CreditCardPayment obj
  paymentInt = new CreditCardPayment();
  paymentInt.payment(2347.89);
  // Payment interface reference holding the ChequePayment obj
  paymentInt = new ChequePayment();
  paymentInt.payment(1567.45);
 }
}

Output

Cash Payment of amount 134.67
CreditCard Payment of amount 2347.89
Cheque Payment of amount 1567.45

It can be seen how at run time reference is changed and the appropriate payment method is called.

Points to note-

  • Interfaces help in achieving full abstraction in Java.
  • For top level interfaces only default and public access modifiers are permitted.
  • All the variables in interface are implicitly public, static and final.
  • All the methods in an interface are implicitly public and abstract.
  • The methods of an interface that are implemented by a class must be declared public.
  • If a class implements an interface but does not implement all the methods of that interface then that class must be declared as abstract.
  • A class can extend only one class, but implement many interfaces.
  • An interface, unlike class, can extend more than one interface.
  • An interface or a class can have another interface. Such an interface is known as nested interface or a member interface.
  • Any number of classes can implement an interface and each class is free to provide their own implementation. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.
  • With Java 8, it is possible to add a default implementation to a method in an interface.

That's all for this topic Interface in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Marker Interface in Java
  2. Difference Between Abstract Class And Interface in Java
  3. Interface Default Methods in Java 8
  4. Interface Static Methods in Java 8
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Polymorphism in Java
  2. final Keyword in Java With Examples
  3. Java Abstract Class and Abstract Method
  4. covariant return type in Java
  5. Varargs (Variable-length Arguments) in Java
  6. Difference between HashMap and ConcurrentHashMap in Java
  7. How to Loop Through a Map in Java
  8. Java Lambda Expression And Variable Scope

Wednesday, March 11, 2026

Matrix Subtraction Java Program

In this tutorial, we will explore how to write a Java Program for Matrix Subtraction, a process where corresponding elements of two matrices are subtracted index by index. Understanding matrix subtraction in Java not only strengthens your grasp of core programming concepts but also prepares you for solving real-world problems that rely on efficient handling of multidimensional data structures.

Understanding Matrix Subtraction

When you subtract two matrices subtraction is performed element by element, also known as index-wise subtraction. This means the element at position (0,0) in the first matrix is subtracted from the element at (0,0) in the second matrix, the element at (0,1) in the first matrix is subtracted from the element at (0,1) in the second matrix, and so on across all rows and columns.

For example, when subtracting two matrices of order 3x3, each corresponding element is processed individually to produce the resulting matrix.

matrix subtraction in Java

Which results in-

When working on a Java Program for Matrix Subtraction, it’s important to remember a few key rules to ensure accurate results.

  1. Both matrices must be of the same size (same number of rows and columns).
  2. The resultant matrix will also have the same order as the input matrices.
  3. Each element in the resultant matrix is obtained by subtracting the corresponding element of the second matrix from the first. For example, the element at (0,0) in the first matrix minus the element at (0,0) in the second matrix becomes the element at (0,0) in the resultant matrix.

Matrix subtraction Java program

 
import java.util.Scanner;

public class MatrixSubtraction {

  public static void main(String[] args) {
    int rowM, colM;
    Scanner in = new Scanner(System.in);
    
    System.out.print("Enter Number of Rows and Columns of Matrix : ");
    rowM = in.nextInt();
    colM = in.nextInt();
        
    int M1[][] = new int[rowM][colM];
    int M2[][] = new int[rowM][colM];
    int resMatrix[][] = new int[rowM][colM];
    
    System.out.print("Enter elements of First Matrix : ");
    
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        M1[i][j] = in.nextInt();
      }
    }
    System.out.println("First Matrix : " );
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +M1[i][j]+"\t");
      }
      System.out.println();
    }
        
    System.out.print("Enter elements of Second Matrix : ");
    
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        M2[i][j] = in.nextInt();
      }
    }
    System.out.println("Second Matrix : " );
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +M2[i][j] + "\t");
      }
      System.out.println();
    }
        
    // Subtraction logic 
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        resMatrix[i][j] = M1[i][j] - M2[i][j];
      }
    }
        
    // Printing the result matrix 
    System.out.println("Result Matrix : " );
    for(int i = 0; i < resMatrix.length; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +resMatrix[i][j]+"\t");
      }
      System.out.println();
    }
  }
}

Output

 
Enter Number of Rows and Columns of Matrix : 3 3

Enter elements of First Matrix : 1 3 4 2 5 6 4 3 2

First Matrix : 
 1  3  4 
 2  5  6 
 4  3  2
 
Enter elements of Second Matrix : 2 7 1 0 4 6 9 8 1

Second Matrix : 
 2  7  1 
 0  4  6 
 9  8  1
 
Result Matrix : 
 -1  -4  3 
  2   1  0 
 -5  -5  1 

That's all for this topic Matrix Subtraction Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Matrix Multiplication Java Program
  2. Matrix Addition Java Program
  3. Remove Duplicate Elements From an Array in Java
  4. Factorial Program in Java
  5. Fibonacci Series Program in Java

You may also like-

  1. How to Display Pyramid Patterns in Java - Part2
  2. Zipping Files And Folders in Java
  3. How to Read File From The Last Line in Java
  4. How to Run a Shell Script From Java Program
  5. Object class in Java
  6. Type Wrapper Classes in Java
  7. Lock Striping in Java Concurrency
  8. How ArrayList Works Internally in Java

Python break Statement With Examples

Have you ever found yourself stuck in a loop that just won't quit? In this tutorial, you’ll master the break statement in Python, your primary tool for stopping a for or while loop dead in its tracks. Whether you've found the data you were looking for or hit a specific error condition, the break keyword gives you ultimate control over your program's flow.

How the break Statement in Python Works

When the Python interpreter encounters a break statement, it immediately terminates the current loop. The program "jumps" out of the loop block and moves straight to the very next line of code.

Key Use Cases and Best Practices

The break statement in Python is most effective when paired with an if statement. This allows you to exit a loop only when a specific criteria is met, saving valuable processing time.

  • Conditional Exit: Use if to check a condition; if True, trigger the break.
  • Search Optimization: Stop searching a list once the target item is found.
  • Nested Loops: Note that when using a break inside nested loops, Python only terminates the innermost loop where the statement resides. The outer loops will continue running as usual.

break statement Python examples

1- Using break statement with for loop in Python. In the example a tuple is iterated using a for loop to search for a specific number as soon as that number is found you need to break out of for loop.

numbers = (89, 102, 0, 234, 67, 10, 333, 32)
flag = False
for num in numbers:
    if num == 10:
        flag = True
        break
if flag:
    print('Number found in tuple')
else:
    print('Number not found in tuple')

Output

Number found in tuple

As you can see here break statement is used inside for loop to break out of loop as soon as the condition is satisfied (Search Optimization use case). Note that searching for an element in a tuple can be done in a more compact way like given below, above example is more of an illustration of break statement.

if searched_num in numbers:
    print('Number found in tuple')
else:
    print('Number not found in tuple')

2- Using break statement in Python with while loop. In the example there is an infinite while loop that is used to prompt user for an input. Condition here is that entered number should be greater than 10 to break out of while loop otherwise prompt user again to enter valid input.

while True:
   num = int(input("Enter a number greater than 10: "))
   # condition for breaking out of loop
   if num > 10:
       break
   print("Please enter a number greater than 10...")

print("Entered number is", num)

Output

Enter a number greater than 10: 7
Please enter a number greater than 10...
Enter a number greater than 10: 11
Entered number is 11

3- In this example we’ll see how to use break statement with nested loops. There are 2 for loops in the example and break statement is used in the scope of inner for loop so it breaks out of that loop when the condition is true.

for i in range(1, 6):
    print(i, "- ", end='')
    for j in range(1, 10):
        print('*', end='')
        # print only 5 times then break
        if j >= 5:
            break
    # move to next line now
    print()

Output

1 - *****
2 - *****
3 - *****
4 - *****
5 - *****

As you can see though the range of inner loop is (1..10) but it breaks out when j’s value is 5 because of the break statement. The end='' used in print statement ensures that the cursor doesn’t move to next line after printing in each iteration.

That's all for this topic Python break Statement With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python continue Statement With Examples
  2. pass Statement in Python
  3. Python assert Statement
  4. Python First Program - Hello World
  5. Python String split() Method

You may also like-

  1. Name Mangling in Python
  2. Inheritance in Python
  3. Class And Object in Python
  4. Python Generator, Generator Expression, Yield Statement
  5. Java Variable Types With Examples
  6. Ternary Operator in Java With Examples
  7. How to Convert Date And Time Between Different Time-Zones in Java
  8. Spring Constructor Based Dependency Injection

Tuesday, March 10, 2026

ArrayList in Java With Examples

The ArrayList in Java is one of the most popular and versatile collection classes, widely used because of its ability to grow dynamically. Unlike traditional arrays, you don’t need to anticipate in advance how many elements you are going to store in the ArrayList. An ArrayList automatically expands as new items are added, making it ideal for scenarios where data size is unpredictable.

Internally, however, the ArrayList isn’t a magical "elastic" structure. It starts with an underlying array of a default capacity (10 elements). When this limit is exceeded, Java creates a new array that is 1.5 times larger than the original array and efficiently copies the existing elements into it. This resizing strategy ensures smooth performance while offering the flexibility developers love about the ArrayList in Java

Refer How does ArrayList work internally in Java to know more about how does ArrayList work internally in Java.


Hierarchy of the ArrayList

To know the hierarchy of java.util.ArrayList you need to know about 2 interfaces and 2 abstract classes.

  • Collection Interface- Collection interface is the core of the Collection Framework. It must be implemented by any class that defines a collection.
  • List interface- List interface extends Collection interface. Apart from extending all the methods of the Collection interface, List interface defines some methods of its own.
  • AbstractCollection- Abstract class which implements most of the methods of the Collection interface.
  • AbstractList- Abstract class which extends AbstractCollection and implements most of the List interface.

ArrayList extends AbstractList and implements List interface too. Apart from List interface, ArrayList also implements RandomAccess, Cloneable, java.io.Serializable interfaces.