0

I have a for loop with multiple conditions like that:

for(int i = 4; i < 100 && (i-1)%6 == 0 || (i+1)%6 == 0; i++) {
    //do something
}

Now, how does Java handle the conditions? Is it if both and conditions are correct or the other one or is my for loop doing something when the first and one of the last conditions are true? And should i use parenthesis to clarify what i want it to do?

I wanted to avoid to many if statements in my for loop, or am i obliged to use if statements?

noahkln
  • 21
  • 2
  • 1
    Your code, as it is, means `(i < 100 && (i-1)%6 == 0) || (i+1)%6 == 0`. Should you add parentheses? Yes. – Sweeper Mar 20 '20 at 17:12
  • Read [this](https://introcs.cs.princeton.edu/java/11precedence/), you may get a full landscape of java operator precedence. – Lebecca Mar 20 '20 at 17:13
  • Thank you very much – noahkln Mar 20 '20 at 17:13
  • FYI: The condition can be simplified by much. Actually it is redundant as a whole. – akuzminykh Mar 20 '20 at 17:18
  • I'd like to but it's too much to explain it in a *nice* and *readable* way as a comment and sadly the post got already closed, so I can't post it as an answer. ¯\\_(ツ)_/¯ Anyways, @noahkln_ please feel free to post another question with the same statement. And make sure it's about the *simplification* so it's not closed instantly. – akuzminykh Mar 20 '20 at 17:36

0 Answers0