Search code examples
javatype-safety

Checking condition safety and evaluating in same if statement


Is it considered to be good practice or even safe to check if a condition can be evaluated and then evaluating the expression in the same if statement?

For example:

int[] values = new int[] { 1, 2, 3, 4 }
int index = 4;
if (index < values.length && values[index] == 4) {
    System.out.println("value is 4")
}

In this example the condition is values[index] == 4 and I am using index < values.length to check if it is safe to call it. However, I am doing this in the same if statement. Is it ok to do this?


Solution

  • Yes, this is correct approach, because in Java there is mechanism called short-circuit evaluation (called also lazy evaluation). That means JVM checks for first condition and if this is false JVM knows that no matter what result is in second condition it won't change anything, so second condition is skipped. In your example if index is greater than values.length, the whole if statement is false, so second condition is omitted.


    Edit:

    As Coffee Ninja mentioned, there is significant difference between bitwise operators (&,|) and logical operators (&&,||). Technically result should be the same, but bitwise operators are evaluated eager, so both sides are proceeded. This may result in OutOfBoundException in your example.
    What's more, bitwise operators have lower precedence, so if you accidentally mix logical and bitwise operators, you can receive different results.