Java check if array is null: In the previous article, we have seen Java Program to Join Elements of String Array with Delimiter
In this article we are going to see how to check if array is empty using Java programming language.
Java Program to Check if Array is Empty
How to check if a spot in an array is empty java: Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.
In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.
Declaration of an array:
dataType[] arrayName; (or) //Declaring an array dataType []arrayName; (or) dataType arr[];
Instantiation of an Array:
arrayName = new datatype[size]; //Allocating memory to array
Combining both Statements in One:
dataType[] arrayName = new dataType[size] //Declaring and Instantiating array
Initialization of an Array:
arrayName[index-0]= arrayElement1 //Initializing the array ... arrayName[index-s]= arrayElementS
Combining all Statements in One:
dataType arrayName[ ]={e1,e2,e3}; //declaration, instantiation and initialization
Let’s see different ways to check if array is empty.
Method-1: Java Program to Check if Array is Empty By Checking if the Array is Null
Approach:
- Initialize the array.
- Check if an array is null, using if(array == null).
- Check if array.length is 0.
Program:
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr1 = null; int[] arr2 = {}; int[] arr3 = {1, 2, 3}; isArrayEmpty(arr1); isArrayEmpty(arr2); isArrayEmpty(arr3); } public static void isArrayEmpty(int arr[]) { if (arr == null || arr.length == 0) { System.out.println("Array " + Arrays.toString(arr)+ " is empty"); } else { System.out.println("Array " + Arrays.toString(arr)+ " is not empty"); } } }
Output: Array null is empty Array [] is empty Array [1, 2, 3] is not empty
Method-2: Java Program to Check if Array is Empty By Checking Array Length
Approach:
- Initialize the array.
- Check if the array length is equal to 0, then the array is empty.
Program:
public class Main { public static void main(String[] args) { //Declaring an empty array int arr[] = {}; //checking the length of array, if it is equal to 0 //then the array is empty if(arr.length == 0) { System.out.println("Empty Array"); } else { System.out.println("Not an Empty Array"); } } }
Output: Empty Array
Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.
Related Java Programs: