Would this be an example of short circuiting?

88 views Asked by At

If I ask a user to input an int, and need to check if it is within the range of indices of an array before checking the array at that index to see if it's not null, would that be an example of "short circuiting"? Because if the array size is only 5 and the user inputs 15, then I would get an ArrayIndexOutOfBoundsException. But if I first check if the number input is 0-4 inclusive and then check the array index last, it will be guaranteed to be between 0-4 inclusive. So my question is: is this an example of "Short Circuiting"? I'll rephrase what I'm saying in code...

import java.util.Scanner;

public Class Reservation{

    Customer[] customers = new Customer[5];
    Scanner input = new Scanner(System.in);
    //some code

    private void createReservation(){

        System.out.print("Enter Customer ID: ");
        int customerIndex;
        if(input.hasNextInt()){
            customerIndex = input.nextInt();
            //is the if-statement below a short-circuit
            if(customerIndex < 0 || customerIndex >= 5 || customers[customerIndex] == null){
                System.out.print("\nInvalid Customer ID, Aborting Reservation");
                return;
            }   
        }
        else{
            System.out.print("\nInvalid Customer ID, Aborting Reservation");
        }
    //the rest of the method
    }
}
2

There are 2 answers

1
Sergey Kalinichenko On BEST ANSWER

Yes, this is a valid example of using short-circuiting correctly:

if(customerIndex < 0 || customerIndex >= 5 || customers[customerIndex] == null)

This code works only under the assumption that || stops evaluating as soon as it gets a true - otherwise, customers[customerIndex] could be reached with an invalid index, triggering an exception.

1
Steve P. On

Yes, because if any of your comparisons, going from left to right, are true, then the remaining comparisons to the right do not need to be evaluated.

Another example would be:

if(node != null && node.value.equals("something"))

In this case, if node == null, short-circuiting occurs, since the && requires two true values and the first is false, it does not evaluate the second comparison.