4 || ++at>10 && it>0) { System.out.print("stuff"); } System.out.print(at); prints material9,...">

Why "or" go to "and"?

int it=9, at=9;

if(it>4 || ++at>10 && it>0)  
{
    System.out.print("stuff");    
}

System.out.print(at);

prints material9, and I want to know why, because I thought I would ++at>10 && it>0be rated first and thus would do at = 10.

+4
source share
3 answers

Operator priority only controls the grouping of arguments; it does not affect the execution order. In almost all cases, Java rules say that instructions are executed from left to right. Priority ||and &&leads to the fact that the control expression ifis evaluated as

it>4 || (++at>10 && it>0)

but a higher priority &&does not mean that an evaluation is first performed &&. Instead

it>4

, || , .

+14

if(it>4 || (++at>10 && it>0))  

- Java-. || , it>4, true, ( &&) ( at ).

+9

, , .

Brief explanation: the operator is a || short circuit of the entire expression, so the right side is not even evaluated.

But in order not to lock up and get the expected result, instead of the operator, ||just use |, for example:

int a = 9, b = 9;

if(a>4 | ++b>10 && a>0)  
{
    System.out.print("stuff");    
}
System.out.print(b);

Conclusion to this stuff10

Thus, regardless of which side is true or not, both of them are still evaluated.

The same goes for &&and&

0
source

Source: https://habr.com/ru/post/1540306/


All Articles