Why is the condition of j never satisfied with "||", and why is i satisfied with "&&"?

Asked

Viewed 58 times

2

package aulas;
   public class Aula{
     public static void main(String[] args){
       for(int i = 0, j = 0; i < 100 || j < 50; ++i);
          //Quando troco o operador lógico para && é impresso até 99, porém
          //quando uso || é impresso até o infinito(ou estouro da variável)
  }
}
  • Are you modifying j somewhere? and what is your starting value

  • The value of j = 0. Sorry, I already made the correction!

2 answers

6


The question is the following, you are only increasing the value of the variable i. This way it will vary from 0 until 99.

These are the truth tables for the logical connectives:

And (&&)

A | B | A && B
--+---+-------
V | V | V
V | F | F
F | V | F
F | F | F

OR (||)

A | B | A || B
--+---+-------
V | V | V
V | F | V
F | V | V
F | F | F

Thus, as can be seen in the operator OU (||) the two conditions need to be false for the loop to stop. As the variable value j is never incremented. The loop is infinite thus causing the overflow.

Already on the operator E (&&) only one of the evaluations needs to be false to make the boolean expression false, and thus interrupt the loop, a fact that will occur only when the value of i for 100.

1

Because the value of j is static.

You have just the i++ thus j will always meet the proposed condition

Browser other questions tagged

You are not signed in. Login or sign up in order to post.