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);
        }
    }
}
Roger Wang
  • 565
  • 2
  • 12
  • 30

0 Answers0