Logical Operators Flashcards
Define all java Logical Operators !
JAVA has 5 logical binary operators in total :
- Logical OR ( || )
- 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)
Give all data types that can be used with
logical operators !
- Logical AND (&&)
Operands: Both operands must be of type boolean.
- Logical OR (||)
Operands: Both operands must be of type boolean.
- 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).
- Bitwise OR (|)
Operands:
For boolean context: both operands must be of type boolean.
For numeric context: both operands can be of any integral type.
- 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).
Define a short circuit operator !
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/
Give a characteristic of the operators
‘|’ and ‘&’ !
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