Thursday 29 November 2007

For loop fun

So I was just doing a bit of reading about Java for loops, and something occurred to me that I hadn't really thought about before, I knew it implicitly but didn't really think it out loud, so to speak.

Two methods, same function (very trivial):

public void hello()
{
String outsideLoop = "0";
for(int i=0;i<5;i++)
{
outsideLoop = ""+i;
System.out.println("The value of outsideLoop is: "+i);
}
}


public void hello2()
{
for(int i=0;i<5;i++)
{
String outsideLoop = "" + i;
System.out.println("The value of outsideLoop is: "+i);
}
}


The main difference here is that in the first method, the variable outsideLoop is available to the rest of the method, if we were to add more functionality. In the second method, this value will not be available. The compiler should optimise the second example to ensure that outsideLoop is not created at every call in the loop.

So I guess it depends on whether you are interested in retaining (and using) the state of the internal for loop variable or not.