Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the loop condition calculated each loop for "for" sentence in Java?

This is my Java code:

List<Object> objects = new ArrayList();

// Assign values to objects
...

for (int i = 0; i < objects.size(); i++) {
    Object object = objects.get(i);
    ...
}

I have two questions:

  1. Is objects.size() calculated only once before stating the loop, or is it calculated each loop?
  2. If objects.size() is calculated each loop, then if other thread change it at the same time without multi-threads protection, the code may be crashed.

Am I correct?

like image 882
flypen Avatar asked Dec 08 '11 05:12

flypen


People also ask

Does for loop run only when the condition is true?

A for loop works as long as the condition is true. The flow of control, at first comes to the declaration, then checks the condition. If the condition is true, then it executes the statements in the scope of the loop. At last, the control comes to the iterative statements and again checks the condition.

What is the condition in a for loop?

Condition is an expression that is tested each time the loop repeats. As long as condition is true, the loop keeps running. Increment is an expression that determines how the loop control variable is incremented each time the loop repeats successfully (that is, each time condition is evaluated to be true).


1 Answers

Yes, it is calculated each time. If you have another thread altering the size of your objects list, the loop condition will keep changing.

like image 178
Todd Avatar answered Nov 15 '22 13:11

Todd