java logical operator understanding

1.1  Logical Operators

Logical operators, which are used to operate on Boolean values, and the final result of the operation is the Boolean value true or false .

operator

algorithm

example

result

&

and

false&true

False

|

or

false|true

True

^

XOR

true^flase

True

!

No

!true

talk

&&

short circuit with

false&&true

False

||

short circuit or

false||true

True

After looking at the picture, let's take a look at the general use of logical operators:

l Logical operators usually concatenate the result of a Boolean value computed by two other expressions

l When using short-circuit and or short-circuit or, the latter part will not be judged as long as the result can be judged.

int x = 1,y = 1;

if(x++==2 & ++y==2)
{
x =7;
}
System.out.println("x="+x+",y="+y);

& and, go through all the conditions, regardless of whether the result is right or wrong. The body of the loop is entered only when the conditions are met.

int x = 1,y = 1;

if(x++==2 && ++y==2)
{
x =7;
}
System.out.println("x="+x+",y="+y);

&& short-circuit and, once short-circuit, it will not go. If the first result is false, then the latter will not go, and end directly (jump out of the loop), if not, then go down.

int x = 1,y = 1;

if(x++==1 | ++y==1)
{
x =7;
}
System.out.println("x="+x+",y="+y);

|Or, as long as one condition is satisfied, enter the loop body, and go through the whole condition

int x = 1,y = 1;

if(x++==1 || ++y==1)
{
x =7;
}
System.out.println("x="+x+",y="+y);

|| Short-circuit or, as long as there is one that meets the conditions, it will not go to the back. If the first one meets the conditions, it will not go to the back and directly enter the loop body.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326017577&siteId=291194637