Java Operators - Logical Operators

April 18, 2018 Oclemy Java Operators 1 minute, 11 seconds

The logical operators are normally used to create a compound boolean expression.

In java they inlcude:

  1. ! - 'logical not operator'
  2. && - 'logical and operator'
  3. || - 'logical or operator'
  4. ^ - 'exclusive logical or operator'

Logical operators are important when you want to execute a statement based on one or several coditions.

Logical operators can combine multiple conditions to for a compound boolean expression.

Logical operators are also known as boolean operators. They operate on boolean values yet still create a boolean value as a result.

Operator Name Description
|| or logical disjunction
&& and logical conjunction
! not logical negation
^ exclusive or logical exclusion

Example

import java.util.Scanner;
/**
 * MrLogical
 */
public class MrLogical {

    public static void main(String[] args) {
        // Create a Scanner
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Your Age: ");
        int age = input.nextInt();
        System.out.print("Enter Your Gender: ");
        String gender=input.next();

        if (age < 5 && gender.equalsIgnoreCase("male"))
        {
            System.out.println("You are baby boy");
        }
        if (age < 5 || gender.equalsIgnoreCase("male"))
        {
            System.out.println("You are a baby or a boy");
        }
        if (age < 5 ^ gender.equalsIgnoreCase("male"))
        {
            System.out.println("You are either a baby or a boy but not both.");
        }
        if (!gender.equalsIgnoreCase("male"))
        {
            System.out.println("You a female");
        }
    }

}

Result

Enter Your Age: 4
Enter Your Gender: female
You are a baby or a boy
You are either a baby or a boy but not both.
You a female

Comments