Saturday, June 11, 2016

Logical Operator

Logical operator is used to perform the operation on two operands with boolean type . The result of this operation also will be boolean type. Here is a table showing logical operator:

  Operator   Description
  &&   AND
  ||   OR
  ^   XOR (exclusive OR)
  !   NOT (negation)

If there are two boolean operands (for example: A and B) and both are used in AND, OR, XOR, and NOT operation, then the resulting values are as follows:

  A   B   A && B   A || B   A ^ B   !A
  true   true   true   true   false   false
  true   false   false   true   true   false
  false   true   false   true   true   true
  false   false   false   false   false   true

As shown in table above, the AND operation will only return true if both operands (A and B) are true; OR operation will only return false if the second operand is false; XOR operation will only return true if either of its operands (not both) are true; while the NOT operation will return the negation or reversal of a previous value.

Here is an example of code that will show the values ​​resulting from table above

class LogicalOperatorDemo {

   public static void main(String[] args) {

      System.out.println("AND operation");
      System.out.println("true && true = " + (true && true));
      System.out.println("true && false = " + (true && false));
      System.out.println("false && true = " + (false && true));
      System.out.println("false && false = " + (false && false));
      System.out.println();

      System.out.println("OR operation");
      System.out.println("true || true = " + (true || true));
      System.out.println("true || false = " + (true || false));
      System.out.println("false || true = " + (false || true));
      System.out.println("false || false = " + (false || false));
      System.out.println();

      System.out.println("XOR operation");
      System.out.println("true ^ true = " + (true ^ true));
      System.out.println("true ^ false = " + (true ^ false));
      System.out.println("false ^ true = " + (false ^ true));
      System.out.println("false ^ false = " + (false ^ false));
      System.out.println();

      System.out.println("NOT operation");
      System.out.println("!true = " + (!true));
      System.out.println("!false = " + (!false));
   }
}



The results will be given by the above program as follows:

AND operation
true && true = true
true && false = false
false && true = false
false && false = false

OR operation
true || true = true
true || false = false
false || true = false
false || false = false

XOR operation
true ^ true = true
true ^ false = false
false ^ true = false
false ^ false = false

NOT operation
!true = false
!false = true

1 comment: