Logical Operators in Java

Profile picture for user arilio666

To determine the logic between the variable and the value these operators AND, OR, NOT are used up as logical operators in the java programming language.

These logical operators are used to test out the logic and constraints between the variable and value and determine the result based on the logical condition.

Let's have a look at logical operators in a more expanded manner.

1. Logical AND Operator (&&)

This operator returns true if both of the conditions given satisfy true else return false.

Syntax

Cond1 && Cond2

Example

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 10 , val2 = 20, val3, val4 = 30;
        val3 = val1 + val2;

        if ((val3 == val4) && (val2 > val1)) 
        {
            System.out.println("AND Satisfied");
        }
        else
        {
            System.out.println("Not Satisfied");
        }
    }
}

Output

AND Satisfied

2. Logical OR Operator (||)

The OR operator is satisfied when either one of the conditions provided returns true and it doesn't care about the other one even if it returns false.

Syntax

Cond1 || Cond2

Example

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 10 , val2 = 20, val3, val4 = 30;
        val3 = val1 + val2;

        if ((val3 == val4) || (val2 < val1))
        {
            System.out.println("OR Satisfied");
        }
        else
        {
            System.out.println("Not Satisfied");
        }
    }
}

Output

OR Satisfied
  • As you can see here the second condition is false as val2 is greater than val1.
  • But since the first one is true it got passed.

3. Logical NOT Operator(!)

  • This operator is opposite to both of the other ones and this is satisfied by returning the condition false.
  • That's right if it is false then it returns true.
  • If it is true then it returns false.

Syntax

!(Cond)

Example

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 10 , val2 = 20, val3, val4 = 40;
        val3 = val1 + val2;

        if ((val3 != val4) && !(val2 < val1))
        {
            System.out.println("NOT Satisfied");
        }
        else
       {
            System.out.println("Not Satisfied");
       }
       System.out.println("(val3 != val4): " +(val3 != val4));
       System.out.println("!(val2 < val1): " +!(val2 > val1));
    }
}

Output

NOT Satisfied
(val3 != val4): true
!(val2 < val1): false
Tags