javaarraysindexoutofboundsexceptionshort-circuitingprogram-flow

Would this be an example of short circuiting?


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

Solution

  • 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.