0

What is the best way to check if array is null value or if the array contents are null in combination in 1 statement in Java 6:

if ((myArray[0] != null) || (myArray[1] != null) || (myArray!= null)) {
    ...
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
OneXer
  • 303
  • 9
  • 20
  • 4
    Put the `myArray != null` first, and you probably want to use `&&`. – Andy Turner Jun 07 '18 at 12:57
  • Look at this related question: [How can I check whether an array is null / empty?](https://stackoverflow.com/questions/2369967/how-can-i-check-whether-an-array-is-null-empty). I cannot think of a way to do it in one concise statement in Java 6, but that question has some answers that show how to check (in more than one line). – Malte Hartwig Jun 07 '18 at 13:35
  • the answer at https://stackoverflow.com/questions/2369967/how-can-i-check-whether-an-array-is-null-empty is split into a statement and another method. I need to be able to combine them both into 1 statement – OneXer Jun 07 '18 at 13:45
  • Why are you still using Java 6? It's been unsupported for the last 3+ years when Oracle have stopped issuing security updates. You are opening yourself up to security loopholes. – DodgyCodeException Jun 07 '18 at 13:49
  • Is the length of the array fixed? Or can it vary in length? If so, is there an upper limit on the length? – Malte Hartwig Jun 07 '18 at 13:54
  • the length of the array is fixed – OneXer Jun 07 '18 at 14:21
  • 1
    Then wouldn't @AndyTurner 's comment have done it already? `if (array == null || array[0] == null && array[1] == null) { // array is null or contains only nulls }` – Malte Hartwig Jun 07 '18 at 14:27

6 Answers6

2

Firstly, check if the array is not null itself. If the array is null, it makes no reason to iterate its elements since Java will throw the NullPointerException upon access to it:

if (myArray != null) {
    // ...
}

Then inside the body of the condition iterate through all its elements and check if one of them is null.

boolean hasNull = false;
for (int i=0; i<myArray.length; i++) {
    if (myArray[i] == null) {
        hasNull = true;
        break; // to terminate the iteration since there is no need to iterate more
    } 
}

This one-line solution (thanks for the warning from @Napstablook). The condition is evaluated as true if the array itself is null or one of its element is null:

if !(myArray != null && myArray[0] != null && myArray[1] != null) { ... }

Be aware that the && operator works that if the left side is evaluated as false, it stops evaluating the rest of the condition because it will not affect the result. The same does || but with true. However, I suggest you avoid this solution since the index might overflow. Better use the for-loop mentioned above.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • OP wants to check if the array is null or all the elements in the array are null. See post- **or if the array contents are null** – Napstablook Jun 07 '18 at 13:27
2

To have it check for any value, I'd use allMatch. It's also important to check for array != null first, otherwise you'll get an Exception if it is.

if (array == null || Arrays.stream(array).allMatch(Objects::isNull)) 

Note that this won't work with java prior to version 8, OP edited his requirements after I posted the answer

baao
  • 71,625
  • 17
  • 143
  • 203
0

Check if Array is null:

String array[] = null;
if (array == null) {
  System.out.println("array is null");
}

Check if array is Empty:

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

Check for null at the same time:

int[] array = ...;
if (array.length == 0) { } // no elements in the array

if (array == null || iarray.length == 0) { }
Allan Braga
  • 460
  • 5
  • 19
0

Try this

 if (myArray == null || Arrays.stream(myArray).allMatch(element-> element==null)) {}

Edit- For java 6, I really don't see this happening in one line. You can try this if one line is not necessary

  boolean isNull = true;
    if(myArray==null){
        System.out.println("array is null");
    }else{
        for(Integer element: myArray){
            if(element!=null){
                System.out.println("array is not null");
                isNull=false;
                break;
            }
        }
        if(isNull)
            System.out.println("Array is null");
    }
Napstablook
  • 594
  • 1
  • 6
  • 24
0

for example this

boolean isNullOrContainsNull = array == null || Arrays.asList(array).contains(null);

checks in a line whether the array is null or contains null elements

If you want to check whether the array is null or empty or all elements are null take

boolean containsNothingUseful = array == null
        || array.length == 0
        || !new HashSet<String>(Arrays.asList(array))
            .retainAll(Arrays.asList((String)null));

(assuming a String[] array)

Uses the Collection#retainAll() method which returns true when there were other values present, i.e. the inverse of "containsOnly"

Using this one liner is actually fairly inefficient and one better uses a method like below which doesn't create lots of temporary objects and mutates collections etc.

public static boolean containsNothingUseful(String[] array) {
    if (array == null || array.length == 0)
        return true;
    for (String element : array) {
        if (element != null)
            return false;
    }
    return true;
}

// ...
if (containsNothingUseful(myArray)) { .. }
zapl
  • 63,179
  • 10
  • 123
  • 154
0

Instead Itreating Manullay the array, re use the existing collection for this case.

  1. Convert Array Into List
  2. Check Null is present in list or not using contains() method;

Please find the sample code:

public static void main(String[] args) {
        Integer[] array = new Integer[3];

        array[0] = 1;
        array[1] = null;
        array[2] = 2;

        System.out.println(Arrays.asList(array).contains(null));
    }
  • This has been proposed in [another answer](https://stackoverflow.com/a/50742211/7653073) already, and it does not fulfill the Op's request. They want to know whether **all** entries are `null`, not **any** entries. – Malte Hartwig Jun 07 '18 at 14:07