Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving multiple conditions in for loop in Java [closed]

Tags:

java

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.

like image 875
JavaBits Avatar asked May 24 '11 06:05

JavaBits


People also ask

Can you have multiple conditions in a for loop Java?

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

Can we put 2 conditions in for loop?

It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.

How do you handle multiple conditions in Java?

When using multiple conditions, we use the logical AND && and logical OR || operators. Note: Logical AND && returns true if both statements are true. Logical OR || returns true if any one of the statements is true.


2 Answers

You can also use "or" operator,

for( int i = 0 ; i < 100 || someOtherCondition() ; i++ ) {   ... } 
like image 150
OscarRyz Avatar answered Oct 06 '22 10:10

OscarRyz


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! } 
like image 41
Andreas Dolk Avatar answered Oct 06 '22 11:10

Andreas Dolk