Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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?
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.
Add a comment
If you want the loop to terminate when i reaches the smaller of the two expressions, use AND:
i
for(int i=0; i < string.length() && i < 5 ;i++)
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.