print
Advertisment
Advertisment

logical operators in java

Whenever we want true or false value (Boolean value) in two or more condition then we use logical operator which gives us boolean value. It can used with any variable. The logical operators used with conditional operators.

java has three Short circuit operators in java
  1. Logical OR Operator(||).
  2. Logical AND Operator(&&).
  3. Logical NOT Operator(!).

Logical OR Operator in java

This operator returns the true condition whenever one of the two conditions is true. but both condition are false , then it returns the wrong condition according to condition Which is called a logical OR operator.

Example

        
    import java.util.Scanner;
    class Relation{
        public static void main(String agrs[]){
            Scanner scr = new Scanner(System.in);
            boolean x = scr.nextInt(); // true by user
            boolean y = scr.nextInt(); // false by user
            if(x||y){
                System.out.println("x is true"); 
            else{
                System.out.println("y is false"); 
            }
        }
    }
        
    

Output :

   
    
        true // user input
        false // user input
        true // Returns true whenever one of the two conditions is true.
    

Advertisment

Logical AND Operator in java

In this operator, both the conditions must be true, only then this operator returns the true condition.

Example

        
    import java.util.Scanner;
    class Rohit{
        public static void main(String agrs[]){
            Scanner scr = new Scanner(System.in);
            int age = scr.nextInt(); 
            if((age==45)&&(age>18)){
                System.out.println("eligible to vote"); 
            }
            else{
                System.out.println("not eligible to vote"); 
            }
        }
    }
        
    

Output :

   
    
        45
        eligible to vote
    

Advertisment

Logical NOT Operator in java

When we want to make any true condition false then we use the logical NOT operator there.

Example

        
    import java.util.Scanner;
    public class Rohit{
        public static void main(String agrs[]){
            Scanner scr = new Scanner(System.in);
            int a = scr.nextInt(); 
            int b = scr.nextInt();
            if(!(a>b||a>b)){
                System.out.println("true"); 
            }
            else{
                System.out.println("false"); 
            }
        }
    }
        
   

Output :

   
    
        50 // value of a by user
        30 // value of b by user
        false
    
Advertisment
Advertisment
arrow_upward