Giving multiple conditions in for loop in Java

Java

Java Problem Overview


I was searching for "How to give multiple conditions in a for loop?" But there are no direct answers given.

After some research I found the correct way. Conditions should not be comma(,) or semicolon(;) separated. We can use the && operator to join both the conditions together.

for( initialization ; condition1 && condition2 ; increment)

Example:

for(int j= 0; j < 6 && j < ((int)abc[j] & 0xff) ; j++ ) 
{
//
}

Hope this helps the new Java developers.

Java Solutions


Solution 1 - Java

You can also use "or" operator,

for( int i = 0 ; i < 100 || someOtherCondition() ; i++ ) {
  ...
}

Solution 2 - Java

A basic for statement includes

  • 0..n initialization statements (ForInit)
  • 0..1 expression statements that evaluate to boolean or Boolean (ForStatement) and
  • 0..n update statements (ForUpdate)

If you need multiple conditions to build your ForStatement, then use the standard logic operators (&&, ||, |, ...) but - I suggest to use a private method if it gets to complicated:

for (int i = 0, j = 0; isMatrixElement(i,j,myArray); i++, j++) { 
   // ...
}

and

private boolean isMatrixElement(i,j,myArray) {
  return (i < myArray.length) && (j < myArray[i].length);  //  stupid dummy code!
}

Solution 3 - Java

It is possible to use multiple variables and conditions in a for loop like in the example given below.

 for (int i = 1, j = 100; i <= 100 && j > 0; i = i - 1 , j = j-1) {
     System.out.println("Inside For Loop");
 }

Solution 4 - Java

If you prefer a code with a pretty look, you can do a break:

for(int j = 0; ; j++){
    if(j < 6
    && j < ( (int) abc[j] & 0xff)){
        break;
    }

    // Put your code here
}

Solution 5 - Java

If you want to do that why not go with a while, for ease of mind? :P No, but seriously I didn't know that and seems kinda nice so thanks, nice to know!

Solution 6 - Java

You can also replace complicated condition with single method call to make it less evil in maintain.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJavaBitsView Question on Stackoverflow
Solution 1 - JavaOscarRyzView Answer on Stackoverflow
Solution 2 - JavaAndreas DolkView Answer on Stackoverflow
Solution 3 - JavaKrishnaView Answer on Stackoverflow
Solution 4 - JavaDavid RodriguesView Answer on Stackoverflow
Solution 5 - JavakxkView Answer on Stackoverflow
Solution 6 - JavateodozjanView Answer on Stackoverflow