istrueright
istrueright

Reputation: 63

is there a new variable created each time in loop?

In the following example:

for(int i=0; i<10; i++) {
  int k;
}
  1. Is it true that the loop body (that is, the statement "int k") will repeatedly be executed 10 times?

  2. If this is the case, does that mean each time there will be a new variable k created? (because this "a type followed by a variable name" format is defined as creating a new variable in JAVA although the variable name keeps same)

Upvotes: 3

Views: 181

Answers (4)

user207421
user207421

Reputation: 310957

Is it true that the loop body (that is, the statement "int k") will repeatedly be executed 10 times?

It depends on exactly what you mean. The stack slot concerned will start being used for k, but it was allocated on method entry, not on loop entry.

If this is the case, does that mean each time there will be a new variable k created? (because this "a type followed by a variable name" format is defined as creating a new variable in JAVA although the variable name keeps same).

The variable is created by the compiler. The address space it occupies is created on method entry, see above.

Contrary to certain claims in comments, this is fully specified by the Java Virtual Machine Specification §2.6:

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes, whether that completion is normal or abrupt (it throws an uncaught exception). Frames are allocated from the Java Virtual Machine stack (§2.5.2) of the thread creating the frame. Each frame has its own array of local variables (§2.6.1), its own operand stack (§2.6.2), and a reference to the run-time constant pool (§2.5.5) of the class of the current method.

Upvotes: 1

Roland Illig
Roland Illig

Reputation: 41625

Yes, the variable k is created 10 times.

But this doesn't mean anything for performance, since the Java compiler will know that the use of these 10 variables do not overlap. Therefore, it may reuse the same memory storage (or a register) for it.

So don't be afraid of creating many variables, it's ok. Be more afraid of creating objects with new. But even then will the compiler optimize some of them away.

Upvotes: -1

TofuBeer
TofuBeer

Reputation: 61536

No, the memory for the variable exists in the method, not in the loop. The fact that you can only access k inside the loop is just done by the compiler.

If you were to change the code like this:

public class X
{
    public static void main(final String[] argv)
    {
        for(int i = 0; i < 10; i++)
        {
           int k = i * 2;

           System.out.println(k);
        }
    }
}

Then run javap -c X to view the bytecode you would see:

       0: iconst_0
       1: istore_1          // i = 0
       2: iload_1
       3: bipush        10
       5: if_icmpge     25  // i < 10
       8: iload_1  
       9: iconst_2
      10: imul
      11: istore_2          // k = i * 2 < this is the key (see below)
      12: getstatic     
      15: iload_2           // this gets k (see below)
      16: invokevirtual #3                  
      19: iinc          1, 1   // i++
      22: goto          2
      25: return

istore_2 stores the result of the calculation into the 2nd spot in the stack. iload_2 gets the value that is in the 2nd spot on the stack. (You can see the descriptions of the instructions here)

The stack exists at all times, think of it as an array that a method is able to access a certain part of.

Upvotes: 2

Aditya
Aditya

Reputation: 1135

Since the statement int k only declares a variable (allocates an int block) and does not define it, a new variable is not created every time.

Also, the scope of a local variable should be made as small as possible. Therefore, the only good way to declare the variable is inside the while loop.

If you would want to save clock cycles, when you initialise a variable e.g. int k = 3;, to save extra clock time you can declared outside the while loop thus increasing the scope of the variable. In this case, the variable won't be initialised every time.

Upvotes: 0

Related Questions