Clarification Needed on Short Java Code Snippet



  • // I was looking at a program to find the specific value //
    
    // Declares the index
    
    int x [] = {23,45,25,26};
    
    // Assuming the value at the 0th index is 0
    
    int indexOF = 0; // Can someone please explain this line
    
    // Iterating the whole array and then when it is matched store the value in the index basically replacing the assume value.
    
    
    
    for(int i = 0; i<x.length;i++){
    
    if (x[i]) == '45'){ // How this works?
    // replace the assume value
    indexOF = i; // Can Someone Please explain this line
    }
    
    }
    
    s.o.p(indexOF);
    

    Can somebody explain what the purpose of indexOF is or how it is being used?



  • @Syed_AlamM
    It looks like indexOF saves the index of the last occurrence of whatever number you are looking for in an array. In this case it is '45'. So indexOF will always be set to the index of the last occurrence of '45'. So if the array is [3,45,67,74,45] indexOF will be 4 since the last 45 element is at index 4.

    Hope this makes sense.



  • @Syed_AlamM
    It looks like indexOF saves the index of the last occurrence of whatever number you are looking for in an array. In this case it is '45'. So indexOF will always be set to the index of the last occurrence of '45'. So if the array is [3,45,67,74,45] indexOF will be 4 since the last 45 element is at index 4.

    Hope this makes sense.


Log in to reply