Home Need of declaration of a variable in a for loop
Reply: 2

Need of declaration of a variable in a for loop

ercolegui
1#
ercolegui Published in 2017-11-13 09:11:25Z

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.

Eran
2#
Eran Reply to 2017-11-13 09:16:13Z

If you declare the loop variable within the loop, it is only accessible inside the loop.

Since, in your last snippet, you are accessing both i and j after the loop ends (in System.out.println("Found " + searchfor + " at " + i + ", " + j);), you must declare them before the loop.

That's also the reason why you have to initialize j prior to the loop. The loop may never be executed (if arrayOfInts.length is 0), but you would still access j in the mentioned println statement, so it must be initialized at this point.

SaiBot
3#
SaiBot Reply to 2017-11-13 09:16:18Z

In Example 1, i is only used within the for-loop. That's why you do not need to declare it beforehand. In Example 2, i is used in the loop, but also afterwards in the "if (foundIt)"-Block. Therefore, it must be declared outside the loop.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.306265 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO