I am new, but I can not find the answer to this question, carefully considering other questions.
Why is it sometimes necessary to declare a variable, and sometimes not? I give you two examples:
Example 1: here we do not need to declare i
before the for loop.
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
Example 2: Here we need to declare i
before the loop.
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
I would be grateful if you could also tell me why I should also initialize the variable j = 0
, if in the for loop I already assign the value 0.
source
share