Godsave Godsave -4 years ago 147
Java Question

Why is this condition satisfied? (j == nElems)

I wrote this code to find an element in an array which is working pretty well but I do not understand how it works 100%. My question is, how come (j == nElems) when it only runs from 0 to 9? I've also noticed that the condition is satisfied outside the for loop when the search key is not found.

public class ArrayApp {
public static void main(String args[]) {
int nElems = 10;
int[] arr = new int[nElems];
int j;
int searchKey;
arr[0] = 77;
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
for (j = 0; j < nElems; j++) {
System.out.print(arr[j] + " ");
}
System.out.println();
//Find 66 in array
searchKey = 66;
for (j = 0; j < nElems; j++) {
if (arr[j] == searchKey) {
break;
}
}
if (j == nElems) {
System.out.println("Cant find " + searchKey);
} else {
System.out.println("Found " + searchKey + " in position " + j);
}
//Remove 55 from array
searchKey = 55; // delete item with key 55
for (j = 0; j < nElems; j++) { // look for it
if (arr[j] == searchKey) {
break;
}
}
for (int k = j; k < nElems - 1; k++) { // move higher ones down
arr[k] = arr[k + 1];
}
nElems--;
for (j = 0; j < nElems; j++) {
System.out.print(arr[j] + " ");
}
}
}

Answer Source
for (j = 0; j < nElems; j++) {
    if (arr[j] == searchKey) {
        break;
    }
}

nElems is 10. So j < nElems will be satisfied until j reaches 10. At that point, it will exit the loop. It'll only reach that point, however, if

arr[j] == searchKey

is never satisfied (ie. the search key is not found). So what you're seeing is that the search key is never found, j is incremented up until 10, at which point the loop is exited. At this point, j == nElems.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download