Logical Operators Flashcards

1
Q

Define all java Logical Operators !

A

JAVA has 5 logical binary operators in total :

  1. Logical OR ( || )
  2. Logical AND ( && )

3.Bitwise AND (&) (also acts as a logical operator for booleans)

4.Bitwise OR (|) (also acts as a logical operator for booleans)

5.Bitwise XOR (^) (also acts as a logical operator for booleans)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Give all data types that can be used with
logical operators !

A
  1. Logical AND (&&)

Operands: Both operands must be of type boolean.

  1. Logical OR (||)

Operands: Both operands must be of type boolean.

  1. Bitwise AND (&)

Operands:

For boolean context: both operands must be of type boolean.

For numeric context: both operands can be of any integral type (byte, short, int, long).

  1. Bitwise OR (|)

Operands:

For boolean context: both operands must be of type boolean.

For numeric context: both operands can be of any integral type.

  1. Bitwise XOR (^)

Operands:

For boolean context: both operands must be of type boolean.

For numeric context: both operands can be of any integral type.

NOTE

Boolean Operators: Require boolean types.

Bitwise Operators: Can work with both boolean and integral types (byte, short, int, long).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Define a short circuit operator !

A

A short circuit operator refers to the operators ‘&&’ and ‘||’ that evaluate expressions in a way that stops as soon as the result is determined

For &&: If the first operand is false, the second operand is not evaluated, as the entire expression cannot be true.

For ||: If the first operand is true, the second operand is not evaluated, as the entire expression is already true.

EXAMPLE

int x=6;
boolean b= x>=6 || ++x<=7;
System.out.println(x); /prints 6 because the right hand side was never reached/

int x=6;
boolean b= x>=6 | ++x<=7;
System.out.println(x);/prints 7 because with the ‘/’ operator both sides are always evaluated/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give a characteristic of the operators
‘|’ and ‘&’ !

A

When it comes to the ‘|’ and ‘&’ operators , both of their operands will be evaluated even if the result would have been determined from the evaluation of the left operand

EXAMPLE

Snake snake=new Snake();
if(snake!=null && snake.method()<5 ) {//Do Something}

In this example, if snake was null, then the short circuit operator will prevent a NullPointerException from ever being thrown, since the evaluation of snake.method() is never reached

Alternatively, if we used a logical &, then both sides would always be evaluated and when x was null this would throw an exception

How well did you know this?
1
Not at all
2
3
4
5
Perfectly