Home Need of declaration of a variable in a for loop
 This question already has an answer here: Scope of variable declared in for loop 6 answers I am newbie but cannot find the answer to this question after looking thoroughly in other questions. Why is there a need sometimes to declare a variable and sometimes not? I give you two examples: Example 1: here, we don't have 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 will appreciate if you could also tell me why do I have also to initialize the variable j = 0 if within the for loop I am already assigning the value 0.