Finding an ArrayList in Java is Empty or Not

We are going to learn how to check if an ArrayList is empty or not. In order to do that we have several ways.

  • Comparing the size of the ArrayList with zero.
  • Using isEmpty() method

How to Increase and Decrease Current Capacity (Size) of ArrayList in Java

 



Below is the java program to know if an ArrayList is empty or not using if else

import java.util.ArrayList;
public class arraycheck {
    public static void main(String args[]){
        ArrayList<Integer> list=new ArrayList<Integer>();
        
        if(list.size()==0){
            System.out.println("Its Empty");
            
        }
        else
            System.out.println("Not Empty");
        
    }
    
}
run:
Its Empty
BUILD SUCCESSFUL (total time: 0 seconds)

Explanation: 

We have not inserted anything in our ArrayList. So the size of the list is zero. Thus we are getting “Its Empty” in the output console box.

Here we are comparing our ArrayList size with zero. If there exists any value in our ArrayList the size of the list will be greater than zero.

This time below we are going to add some integer values in our ArrayList below

import java.util.ArrayList;
public class arraylistcheck {
    public static void main(String args[]){
        ArrayList<Integer> list=new ArrayList<Integer>();
        list.add(51);
        list.add(53);
        if(list.size()==0){
            System.out.println("Its Empty");
            
        }
        else
            System.out.println("Not Empty");
        
    }
    
}

 

run:
Not Empty
BUILD SUCCESSFUL (total time: 0 seconds)

 

 

Using isEmpty() Method:

In Java, we have a method called isEmpty() to check if an ArrayList is empty or not

Below is the same code but this time we are going to use isEmpty() method instead of comparing the size of the ArrayList with zero.

import java.util.ArrayList;
public class arraylistcheck {
    public static void main(String args[]){
        ArrayList<Integer> list=new ArrayList<Integer>();
        list.add(51);
        list.add(53);
        if(list.isEmpty()){
            System.out.println("Its Empty");
            
        }
        else
            System.out.println("Not Empty");
        
    }
    
}
run:
Not Empty
BUILD SUCCESSFUL (total time: 0 seconds)
import java.util.ArrayList;
public class arraylistcheck {
    public static void main(String args[]){
        ArrayList<Integer> list=new ArrayList<Integer>();
       
        if(list.isEmpty()){
            System.out.println("Its Empty");
            
        }
        else
            System.out.println("Not Empty");
        
    }
    
}
run:
Its Empty
BUILD SUCCESSFUL (total time: 0 seconds)

 

Leave a Reply

Your email address will not be published. Required fields are marked *