The logical NOT operator ! is used in the form
!operand
The operator returns true if the operand is false, and false if the operand is true.
The following code shows how to use Logical NOT Operator.
boolean b; b = !true; // Assigns false to b b = !false; // Assigns true to b int i = 10; int j = 15; boolean b1 = true; b = !b1; // Assigns false to b b = !(i > j); // Assigns true to b, because i > j returns false
public class Main { public static void main(String[] args) { boolean b; /*from w ww . ja v a 2 s .co m*/ b = !true; // Assigns false to b System.out.println(b); b = !false; // Assigns true to b System.out.println(b); int i = 10; int j = 15; boolean b1 = true; b = !b1; // Assigns false to b System.out.println(b); b = !(i > j); // Assigns true to b, because i > j returns false System.out.println(b); } }
To negate the value of a boolean variable:
b = !b; // Assigns true to b if it was false and false if it was true