Java Logical Operators
In this chapter you will learn:
- What are Java Boolean Logical Operators
- Logical Operator List
- True table
- Example - boolean logical operators
- How to use the Bitwise Logical Operators
Description
The Boolean logical operators operate on boolean operands.
Logical Operator List
The following table lists all Java boolean logical operators.
Operator | Result |
---|---|
& | Logical AND |
| | Logical OR |
^ | Logical XOR (exclusive OR) |
|| | Short-circuit OR |
&& | Short-circuit AND |
! | Logical unary NOT |
&= | AND assignment |
|= | OR assignment |
^= | XOR assignment |
== | Equal to |
!= | Not equal to |
? : | Ternary if-then-else |
True table
The following table shows the effect of each logical operation:
A | B | A | B | A & B | A ^ B | !A |
---|---|---|---|---|---|
False | False | False | False | False | True |
True | False | True | False | True | False |
False | True | True | False | True | True |
True | True | True | True | False | False |
Example
The following program demonstrates the boolean logical operators.
public class Main {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
/* w w w.j a va 2 s.com*/
}
}
]]>
The output:
Example 2
The following program demonstrates the bitwise logical operators:
public class Main {
public static void main(String args[]) {
int a = 1;/*from w w w . j a v a2s .c o m*/
int b = 2;
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("~a&b|a&~b = " + f);
System.out.println(" ~a = " + g);
}
}
Here is the output from this program:
Next chapter...
What you will learn in the next chapter:
- What is Java Logical Operators Shortcut
- Example - Short-Circuit Logical Operators in Java
- Example - Not Shortcut Logical Operators