Star.Kid
Star.Kid

Reputation: 200

Evaluate middle part of the 'for loop' in java before checking

for (int i=0; i < string.length() || i < 5 ; i++) {
    // some code
}

Is it possible to evaluate the middle part based on whichever expression is smaller?

Upvotes: 1

Views: 162

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521409

You can phrase your loop as this:

for (int i=0; i < Math.min(string.length(), 5); i++) {
    // some code
}

Here we are taking the smaller of 5 or the string length as the upper bound of the loop, and the code is clear to someone else who might have to read it.

Upvotes: 3

Eran
Eran

Reputation: 393851

If you want the loop to terminate when i reaches the smaller of the two expressions, use AND:

for(int i=0; i < string.length() && i < 5 ;i++)

Upvotes: 2

Related Questions