There are three compound Boolean logical assignment operators.
The operand1 must be a boolean variable and op may be &, |, or ^.
Java does not have any operators like &&= and ||=.
Compound Boolean Logical Assignment Operators are used in the form
operand1 op= operand2
The above form is equivalent to writing
operand1 = operand1 op operand2
The following table lists the compound logical assignment operators and their equivalents.
Expression | is equivalent to |
---|---|
operand1 &= operand2 | operand1 = operand1 & operand2 |
operand1 |= operand2 | operand1 = operand1 | operand2 |
operand1 ^= operand2 | operand1 = operand1 ^ operand2 |
For &= operator, if both operands evaluate to true, &= returns true. Otherwise, it returns false.
boolean b = true; b &= true; // Assigns true to b b &= false; // Assigns false to b
public class Main { public static void main(String[] args) { boolean b = true; b &= true; // Assigns true to b System.out.println ("b = " + b); b &= false; // Assigns false to b System.out.println ("b = " + b); }/* w ww . j a v a 2 s . c o m*/ }
For != operator, if either operand evaluates to true, != returns true. Otherwise, it returns false.
boolean b = false; b |= true; // Assigns true to b b |= false; // Assigns false to b
public class Main { public static void main(String[] args) { boolean b = false; b |= true; // Assigns true to b System.out.println("b = " + b); b |= false; // Assigns false to b System.out.println("b = " + b); }/*from w w w . j a v a 2 s.c o m*/ }
For ^= operator, if both operands evaluate to different values, that is, one of the operands is true but not both, ^= returns true. Otherwise, it returns false.
boolean b = true; b ^= true; // Assigns false to b b ^= false; // Assigns true to b
public class Main { public static void main(String[] args) { boolean b = true; b ^= true; // Assigns false to b System.out.println("b = " + b); b ^= false; // Assigns true to b System.out.println("b = " + b); }/*from w ww.j a v a 2 s. c o m*/ }