How to check whether an array is null / empty in java?

How to check whether an array is null / empty in java?

In Java, you can check whether an array is null or empty using conditional statements. Here's how you can do it:

  1. Check for Null:

    To check if an array is null, you can simply use the equality operator (==) to compare the array reference to null. If it's equal to null, it means the array is null.

    int[] array = null; if (array == null) { System.out.println("Array is null"); } else { System.out.println("Array is not null"); } 
  2. Check for Empty:

    To check if an array is empty, you need to examine its length. An array is considered empty if its length is 0.

    int[] array = new int[0]; if (array.length == 0) { System.out.println("Array is empty"); } else { System.out.println("Array is not empty"); } 

    You can also check for an empty array on an existing array by using the length property:

    int[] array = {1, 2, 3}; if (array.length == 0) { System.out.println("Array is empty"); } else { System.out.println("Array is not empty"); } 

In summary, you can check whether an array is null by comparing it to null and whether it's empty by examining its length property.


More Tags

qpython tablename postman-collection-runner iequalitycomparer jwe android-volley fencepost android-logcat event-driven oracle11g

More Java Questions

More Financial Calculators

More Livestock Calculators

More Retirement Calculators

More Chemical thermodynamics Calculators