Is a variable declared inside a loop limited in one iteration?

I know this sounds trivial, but I just want to clear my head of it.

consider

for (int i = 0; i < 100; i++) {
    int x=i;
    System.println(i);
}

represents a new created and allocated memory for each iteration, or the compiler with confidence displays the script and creates it only once and changes its value (since it knows that it is a loop),

and as for the declaration iinside the method signature, is it obviously instantiated immediately once?

will also be

int x = 0;

for (int i = 0; i < 100; i++) {
    x = i;
    System.println(i);
}

really more effective the higher?

in java in cases where I do not need to access xoutside the loop, is it better to declare it inside, which is good practice?

+4
1

-, .

:

public static void main(String[] args) {
    int x;
    for (int i = 0; i < 100; i++) {
        x = i;
    }
}

:

public static void main(java.lang.String[]);
Code:
   0: iconst_0
   1: istore_2
   2: iload_2
   3: bipush        100
   5: if_icmpge     16
   8: iload_2
   9: istore_1
  10: iinc          2, 1
  13: goto          2
  16: return

:

public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
        int x = i;
    }
}

:

public static void main(java.lang.String[]);
Code:
   0: iconst_0
   1: istore_1
   2: iload_1
   3: bipush        100
   5: if_icmpge     16
   8: iload_1
   9: istore_2
  10: iinc          1, 1
  13: goto          2
  16: return

, - . , x 1 i 2, x 2 i 1. , .

, , , . , x , , .

+1

All Articles