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)) {
    ...
}
7
  • 4
    Put the myArray != null first, and you probably want to use &&. Commented Jun 7, 2018 at 12:57
  • Look at this related question: 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). Commented Jun 7, 2018 at 13:35
  • the answer at stackoverflow.com/questions/2369967/… is split into a statement and another method. I need to be able to combine them both into 1 statement Commented Jun 7, 2018 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. Commented Jun 7, 2018 at 13:49
  • 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 } Commented Jun 7, 2018 at 14:27

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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
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) { }

Comments

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");
    }

Comments

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));
    }

1 Comment

This has been proposed in another answer already, and it does not fulfill the Op's request. They want to know whether all entries are null, not any entries.
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)) { .. }

2 Comments

This will return true if there is atleast one element in the array that is null. OP wants to check if all elements are null.
@Napstablook true, I've added a version for that too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.