0

Why can I declare a local variable in this for loop multiple times by including the int prefix in the loop?

class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++){
            int num = 5;
            System.out.println(num);
        }
    }
}

Contrast with this (variable can be used throughout class):

class Main {
    public static void main(String[] args) {
        int num;
        for (int i = 0; i < 3; i++){
            num = 5;
            System.out.println(num);
        }
    }
}
3
  • int obj;: is this supposed to be int num;? Commented Feb 10, 2019 at 4:20
  • Oops, yes, that is supposed to be int num;. Edited. Commented Feb 10, 2019 at 4:20
  • I want to know why I'm allowed to write int num = 5; in the for loop in the first example as it goes through the loop multiple times. Does it reinitialize the variable? Commented Feb 10, 2019 at 4:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.