• Post Reply Bookmark Topic Watch Topic
  • New Topic

How does a loop work in this case ?  RSS feed

 
Mark Putin
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say I have a loop as shown below:

while(intX < intArray.length){

for(int i = intX; i < intArray.length;i++){//do something}
intX++;

}

In the for loop, does the JVM get the value of length for each iteration of while loop or does it just do it once and use it all the time. I am guessing the former since it would want to consider the possibility of us changing the length of the array inside the while loop.

 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

You cannot change the length of an array. But you can replace it with an array of a different length, as long as the reference is not final.

As for your question:-
Not sure. Let's try something.Inspect the bytecodeYou can see that arraylength is called in no 28 and then the loop continues (line 29) by going to no 45 or not. If the line does not continue control passes to no 45. The line before that (no 42) passes control back to no 26. If the loop does continue no 29 has not effect. Notice arraylength is called in no 28, so it is called once per iteration.

Changed code:Running that method gives the output 1 0 0; if it had retained 5 as the array length it would have thrown an Exception.
 
Paul Clapham
Sheriff
Posts: 22832
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As for your question:

Here's a link to the Oracle tutorial about the for-statement: The for Statement.

You'll notice that it says

When the termination expression evaluates to false, the loop terminates.


And that means the termination expression (the one in the middle) is evaluated before every iteration. (Notice also that the tutorial specifically says the initialization expression is evaluated only once.)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!