J
J
Jake Taylor2021-04-30 14:23:00
Java
Jake Taylor, 2021-04-30 14:23:00

Condition 'customArray == null' is always 'false' when reached in Java?

If the object check customArrayin the method looks like this, when first it checks for size and then for null , then the compiler issues a warning likecustomArray.length() == 0customArray == null

Condition 'customArray == null' is always 'false' when reached
. But if we swap the check in such a way that first there is a check for null , and then for size , then the warning disappears. Why is that?customArray == nullcustomArray.length() == 0

@Override
    public int findMinValueMethodStream(CustomArray customArray) throws ArrayException {
        if(customArray.length() == 0 || customArray == null) {
            LOGGER.log(Level.ERROR, "CustomArray object is empty or null!");
            throw new ArrayException("CustomArray object is empty or null!");
        }
// some code
}


The **CustomArray** class is just a wrapper class over int[] array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BorLaze, 2021-04-30
@n199a

Because conditions are checked from left to right.
Therefore, it makes no sense to check customArray for null second - if the array is not null, then it will not come to it; if it is null, then execution will fail with NPE.
But it just makes sense to swap them - first we check if customArray is null, and only if not, then we turn to the object, asking for its size.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question