Java Program on Logical AND Operator

In the previous article, we have discussed about Java Program on Less Than or Equal To Operator

In this article we will see the use of Logical AND operator in Java programming language.

Java Program on Logical AND Operator

Logical AND operator is represented by the symbol &&. This operator returns True if both the left and right side expression is true else it returns False.

Syntax: Expression1 && Expression2

Where the expression holds a condition and that Expression1, Expression2 are both operands for logical AND operator.

For Example:

Suppose you have 3 integer variables a, b, c.

a=5, b=8, c=3

Case-1

if(a>b && a>c) then print 'a' is greater    // Here left side condition i.e. a>b does not satisfy. So here AND operator will return False. Case-2 if(b>a && b>c) then print 'b' is greater    // Here left side condition i.e. a>b and right side condition i.e. b>c both satisfies. So here AND operator will return True.

Actually in case of AND operator when left hand side condition fails means first condition is False, then it does not check the next condition that is in right side. It checks the second condition when first condition is true.

Program:

class Main
{
    public static void main(String[] args)
    {
        //initializing three integer variables a, b, c
        int a = 5, b = 8, c = 3;
  
        //Printing values of a, b, c
        System.out.println("Value of a = " + a);
        System.out.println("Value of b = " + b);
        System.out.println("Value of c = " + c);
  
        //using logical AND 
        //here first condition is false so AND operator will return false
        //so it will not go into if block
        if ((a>b) && (a>c)) 
        {
            System.out.println("'a' is greater than 'b' and 'c'");
        }
        //here both conditions are true so AND operator will return true
        //so it will go into else else if block
        else if ((b>a) && (b>c)) 
            System.out.println("'b' is greater than 'a' and 'c'");
    }
}
Output:

Value of a = 5
Value of b = 8
Value of c = 3
'b' is greater than 'a' and 'c'

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs: