Java Operators - Logical Operators


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

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post