Need to declare a variable in a for loop

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

+4
source share
2 answers

If you declare a loop variable in a loop, it is only available inside the loop.

i j ( System.out.println("Found " + searchfor + " at " + i + ", " + j);), .

, j . ( arrayOfInts.length 0), j println, .

+2

1 for. . 2 , "if (foundIt)". .

+2

Source: https://habr.com/ru/post/1689182/


All Articles