Open In App

Java Logical Operators with Examples

Last Updated : 10 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Logical operators are used to perform logical “AND”, “OR” and “NOT” operations, i.e. the function similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consideration. One thing to keep in mind is, while using AND operator, the second condition is not evaluated if the first one is false. Whereas while using OR operator, the second condition is not evaluated if the first one is true, i.e. the AND and OR operators have a short-circuiting effect. Used extensively to test for several conditions for making a decision.

  • AND Operator ( && ) – if( a && b ) [if true execute else don’t]
  • OR Operator ( || ) – if( a || b) [if one of them is true to execute else don’t]
  • NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]

Example For Logical Operator in Java

Here is an example depicting all the operators where the values of variables a, b, and c are kept the same for all the situations.

a = 10, b = 20, c = 30

For AND operator:

Condition 1: c > a

Condition 2: c > b

Output:

True [Both Conditions are true]


For OR Operator:

Condition 1: c > a

Condition 2: c > b

Output:

True [One of the Condition if true]


For NOT Operator:

Condition 1: c > a

Condition 2: c > b

Output:

False [Because the result was true and NOT operator did it’s opposite]

Logical ‘AND’ Operator (&&) 

This operator returns true when both the conditions under consideration are satisfied or are true. If even one of the two yields false, the operator results false. In Simple terms, cond1 && cond2 returns true when both cond1 and cond2 are true (i.e. non-zero). 

Syntax:

condition1 && condition2

Illustration:

a = 10, b = 20, c = 20

condition1: a < b
condition2: b == c

if(condition1 && condition2)
d = a + b + c

// Since both the conditions are true
d = 50.

Example:

Java
// Java code to illustrate
// logical AND operator

import java.io.*;

class Logical {
    public static void main(String[] args)
    {
        // initializing variables
        int a = 10, b = 20, c = 20, d = 0;

        // Displaying a, b, c
        System.out.println("Var1 = " + a);
        System.out.println("Var2 = " + b);
        System.out.println("Var3 = " + c);

        // using logical AND to verify
        // two constraints
        if ((a < b) && (b == c)) {
            d = a + b + c;
            System.out.println("The sum is: " + d);
        }
        else
            System.out.println("False conditions");
    }
}

Output
Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50


Now in the below example, we can see the short-circuiting effect. Here when the execution reaches to if statement, the first condition inside the if statement is false and so the second condition is never checked. Thus the ++b(pre-increment of b) never happens, and b remains unchanged.

Example:

Java
import java.io.*;

class shortCircuiting {
    public static void main(String[] args)
    {

        // initializing variables
        int a = 10, b = 20, c = 15;

        // displaying b
        System.out.println("Value of b : " + b);

        // Using logical AND
        // Short-Circuiting effect as the first condition is
        // false so the second condition is never reached
        // and so ++b(pre increment) doesn't take place and
        // value of b remains unchanged
        if ((a > c) && (++b > c)) {
            System.out.println("Inside if block");
        }

        // displaying b
        System.out.println("Value of b : " + b);
    }
}

Output:

AND Operator Output

Logical ‘OR’ Operator (||) 

This operator returns true when one of the two conditions under consideration is satisfied or is true. If even one of the two yields true, the operator results true. To make the result false, both the constraints need to return false. 

Syntax:

condition1 || condition2

Example:

a = 10, b = 20, c = 20

condition1: a < b

condition2: b > c

if(condition1 || condition2)

d = a + b + c

// Since one of the condition is true

d = 50.

Illustration:

Java
// Java code to illustrate
// logical OR operator

import java.io.*;

class Logical {
    public static void main(String[] args)
    {
        // initializing variables
        int a = 10, b = 1, c = 10, d = 30;

        // Displaying a, b, c
        System.out.println("Var1 = " + a);
        System.out.println("Var2 = " + b);
        System.out.println("Var3 = " + c);
        System.out.println("Var4 = " + d);

        // using logical OR to verify
        // two constraints
        if (a > b || c == d)
            System.out.println(
                "One or both + the conditions are true");
        else
            System.out.println(
                "Both the + conditions are false");
    }
}

Output
Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both + the conditions are true


Now in the below example, we can see the short-circuiting effect for OR operator. Here when the execution reaches to if statement, the first condition inside the if statement is true and so the second condition is never checked. Thus the ++b (pre-increment of b) never happens, and b remains unchanged.

Example:

Java
import java.io.*;

class ShortCircuitingInOR {
    public static void main (String[] args) {
        
      // initializing variables
        int a = 10, b = 20, c = 15;
        
        // displaying b
        System.out.println("Value of b: " +b);
        
        // Using logical OR
        // Short-circuiting effect as the first condition is true
        // so the second condition is never reached
        // and so ++b (pre-increment) doesn't take place and 
        // value of b remains unchanged
        if((a < c) || (++b < c))
            System.out.println("Inside if");
        
        // displaying b
        System.out.println("Value of b: " +b);
      
    }
}

Output
Value of b: 20
Inside if
Value of b: 20


Logical ‘NOT’ Operator (!)

Unlike the previous two, this is a unary operator and returns true when the condition under consideration is not satisfied or is a false condition. Basically, if the condition is false, the operation returns true and when the condition is true, the operation returns false. 

Syntax:

!(condition)

Example:

a = 10, b = 20

!(a<b) // returns false

!(a>b) // returns true

Illustartion:

Java
// Java code to illustrate
// logical NOT operator
import java.io.*;

class Logical {
    public static void main(String[] args)
    {
        // initializing variables
        int a = 10, b = 1;

        // Displaying a, b, c
        System.out.println("Var1 = " + a);
        System.out.println("Var2 = " + b);

        // Using logical NOT operator
        System.out.println("!(a < b) = " + !(a < b));
        System.out.println("!(a > b) = " + !(a > b));
    }
}

Output
Var1 = 10
Var2 = 1
!(a < b) = true
!(a > b) = false


Implementing all logical operators on Boolean values (By default values – TRUE or FALSE)

Syntax:

 boolean a = true;
boolean b = false;

Example:

Java
public class LogicalOperators {
    public static void main(String[] args) {
        boolean a = true;
        boolean b = false;

        System.out.println("a: " + a);
        System.out.println("b: " + b);
        System.out.println("a && b: " + (a && b));
        System.out.println("a || b: " + (a || b));
        System.out.println("!a: " + !a);
        System.out.println("!b: " + !b);
    }
}

Output
a: true
b: false
a && b: false
a || b: true
!a: false
!b: true


Explanation:

  • The code above is a Java program that implements all logical operators with default values. The program defines a class LogicalOperators with a main method.
  • In the main method, two boolean variables a and b are defined and assigned default values true and false, respectively.
  • The program then prints the values of a and b to the console using the System.out.println method. This allows us to verify the values assigned to a and b.
  • Next, the program calculates the result of the logical operators && (and), || (or), and ! (not) applied to a and b. The results of these operations are also printed to the console using the System.out.println method.
  • The && operator returns true if both operands are true; otherwise, it returns false. In this case, the result of a && b is false.
  • The || operator returns true if either operand is true; otherwise, it returns false. In this case, the result of a || b is true.
  • The ! operator negates the value of its operand. If the operand is true, the result is false, and if the operand is false, the result is true. In this case, the results of !a and !b are false and true, respectively.
  • The output of the program shows the truth table for all logical operators. This table provides a visual representation of how these operators behave for all possible combinations of true and false inputs.

Advantages of logical operators:

  • Short-circuit evaluation: One of the main advantages of logical operators is that they support short-circuit evaluation. This means that if the value of an expression can be determined based on the left operand alone, the right operand is not evaluated at all. While this can be useful for optimizing code and preventing unnecessary computations, it can also lead to subtle bugs if the right operand has side effects that are expected to be executed.
  • Readability: Logical operators make code more readable by providing a clear and concise way to express complex conditions. They are easily recognizable and make it easier for others to understand the code.
  • Flexibility: Logical operators can be combined in various ways to form complex conditions, making the code more flexible. This allows developers to write code that can handle different scenarios and respond dynamically to changes in the program’s inputs.
  • Reusability: By using logical operators, developers can write code that can be reused in different parts of the program. This reduces the amount of code that needs to be written and maintained, making the development process more efficient.
  • Debugging: Logical operators can help to simplify the debugging process. If a condition does not behave as expected, it is easier to trace the problem by examining the results of each logical operator rather than having to navigate through a complex code structure.

Disadvantages of logical operators:

  • Limited expressiveness: Logical operators have a limited expressive power compared to more complex logical constructs like if-else statements and switch-case statements. This can make it difficult to write complex conditionals that require more advanced logic, such as evaluating multiple conditions in a specific order.
  • Potential for confusion: In some cases, the use of logical operators can lead to confusion or ambiguity in the code. For example, consider the expression a or b and c. Depending on the intended order of operations, this expression can have different interpretations. To avoid this kind of confusion, it is often recommended to use parentheses to explicitly specify the order of evaluation.
  • Boolean coercion: Logical operators can sometimes lead to unexpected behavior when used with non-Boolean values. For example, when using the or operator, the expression a or b will evaluate to a if a is truthy, and b otherwise. This can lead to unexpected results if a or b are not actually Boolean values, but instead have a truthy or false interpretation that does not align with the programmer’s intentions.

Overall, logical operators are an important tool for developers and play a crucial role in the implementation of complex conditions in a program. They help to improve the readability, flexibility, reusability, and debuggability of the code.



Previous Article
Next Article

Similar Reads

Short Circuit Logical Operators in Java with Examples
In Java logical operators, if the evaluation of a logical expression exits in between before complete evaluation, then it is known as Short-circuit. A short circuit happens because the result is clear even before the complete evaluation of the expression, and the result is returned. Short circuit evaluation avoids unnecessary work and leads to effi
3 min read
Java Arithmetic Operators with Examples
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic Operator
6 min read
Java Relational Operators with Examples
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Types of Operators: Arithmetic OperatorsU
10 min read
Java Assignment Operators with Examples
Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Types of Operators: Arithmetic OperatorsU
7 min read
Java.util.Bitset class | Logical operations
Bitset class also allows some of the logical operations on two Bitsets. The logical operations supported are : and, andNot, or, Xor. These are discussed in this article. 1. and(Bitset set) : This method performs a logical AND of this target bit set with the argument bit set and returns the values of 1st bitset also present in second bitset. Declara
5 min read
Java | Operators | Question 1
Predict the output of following Java Program class Test { public static void main(String args[]) { int x = -4; System.out.println(x&gt;&gt;1); int y = 4; System.out.println(y&gt;&gt;1); } } (A) Compiler Error: Operator &gt;&gt; cannot be applied to negative numbers (B) -2 2 (C) 2 2 (D) 0 2 Answer: (B) Explanation: See https://www.geeksforgeeks.org/
1 min read
Java | Operators | Question 2
Predict the output of following Java program. Assume that int is stored using 32 bits. class Test { public static void main(String args[]) { int x = -1; System.out.println(x&gt;&gt;&gt;29); System.out.println(x&gt;&gt;&gt;30); System.out.println(x&gt;&gt;&gt;31); } } (A) 7 3 1 (B) 15 7 3 (C) 0 0 0 (D) 1 1 1 Answer: (A) Explanation: Please see https
1 min read
Java | Operators | Question 3
class Test { public static void main(String args[]) { System.out.println(10 + 20 + &quot;GeeksQuiz&quot;); System.out.println(&quot;GeeksQuiz&quot; + 10 + 20); } } (A) 30GeeksQuiz GeeksQuiz30 (B) 1020GeeksQuiz GeeksQuiz1020 (C) 30GeeksQuiz GeeksQuiz1020 (D) 1020GeeksQuiz GeeksQuiz30 Answer: (C) Explanation: In the given expressions 10 + 20 + "Geeks
1 min read
Java | Operators | Question 4
class Test { public static void main(String args[]) { System.out.println(10*20 + &quot;GeeksQuiz&quot;); System.out.println(&quot;GeeksQuiz&quot; + 10*20); } } (A) 10*20GeeksQuiz GeeksQuiz10*20 (B) 200GeeksQuiz GeeksQuiz200 (C) 200GeeksQuiz GeeksQuiz10*20 (D) 1020GeeksQuiz GeeksQuiz220 Answer: (B) Explanation: Precedence of * is more than +.Quiz of
1 min read
Java | Operators | Question 5
Which of the following is not an operator in Java? (A) instanceof (B) sizeof (C) new (D) &gt;&gt;&gt;= Answer: (B) Explanation: There is no sizeof operator in Java. We generally don't need size of objects.Quiz of this Question
1 min read
Java | Operators | Question 6
class Base {} class Derived extends Base { public static void main(String args[]){ Base a = new Derived(); System.out.println(a instanceof Derived); } } (A) true (B) false Answer: (A) Explanation: The instanceof operator works even when the reference is of base class type.Quiz of this Question
1 min read
Java | Operators | Question 7
class Test { public static void main(String args[]) { String s1 = &quot;geeksquiz&quot;; String s2 = &quot;geeksquiz&quot;; System.out.println(&quot;s1 == s2 is:&quot; + s1 == s2); } } (A) true (B) false (C) compiler error (D) throws an exception Answer: (B) Explanation: The output is “false” because in java + operator precedence is more than == op
1 min read
Java | Operators | Question 8
class demo { int a, b, c; demo(int a, int b, int c) { this.a = a; this.b = b; } demo() { a = b = c = 0; } demo operator+(const demo &amp;obj) { demo object; object.a = this.a + obj.a; object.b = this.b + obj.b; object.c = this.c + obj.c; return object; } } class Test { public static void main(String[] args) { demo obj1 = new demo(1, 2, 3); demo obj
1 min read
Java | Operators | Question 9
Predict the output of the following program. Java Code class Test { boolean[] array = new boolean[3]; int count = 0; void set(boolean[] arr, int x) { arr[x] = true; count++; } void func() { if(array[0] && array[++count - 2] | array [count - 1]) count++; System.out.println("count = " + count); } public static void main(String[] args) { Test object =
1 min read
Bitwise Right Shift Operators in Java
In C/C++ there is only one right shift operator '&gt;&gt;' which should be used only for positive integers or unsigned integers. Use of the right shift operator for negative numbers is not recommended in C/C++, and when used for negative numbers, the output is compiler dependent. Unlike C++, Java supports following two right shift operators. Here w
2 min read
Basic Operators in Java
Java provides a rich operator environment. We can classify the basic operators in java in the following groups: Arithmetic OperatorsRelational OperatorsBitwise OperatorsAssignment OperatorsLogical Operators Let us now learn about each of these operators in detail. 1. Arithmetic Operators: Arithmetic operators are used to perform arithmetic/mathemat
10 min read
Interesting facts about Increment and Decrement operators in Java
Increment operator is used to increment a value by 1. There are two varieties of increment operator: Post-Increment: Value is first used for computing the result and then incremented.Pre-Increment: Value is incremented first and then the result is computed. Example Java Code //INCREMENTAL OPERATOR //Let's see what exactly happens when we use these
5 min read
Compound assignment operators in Java
Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction a
7 min read
Operators in Java
Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. In this article, we will learn about Java Operators and learn all their types. What are the Java Operators?Operators in Java are the symbols used for performing specific operations in Java. Operators make tasks
15 min read
Bitwise Operators in Java
Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic Operator
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
Java Clock tickMinutes() method in Java with Examples
java.time.Clock.tickMinutes(ZoneId zone) method is a static method of Clock class that returns the current instant ticking in whole minutes using the best available system clock and the time-zone of that instant is same as the time-zone passed as a parameter. Nanosecond and second fields of the clock are set to zero to round the instant in the whol
3 min read
Java Clock withZone() method in Java with Examples
The java.time.Clock.withZone(ZoneId zone) method is a method of Clock class which returns a clock copy of clock object on which this method is applied, with a different time-zone. If there is a clock and it is required to change the zone of clock but not other properties, then withZone() method is used. This method takes zone as parameter which is
3 min read
Article Tags :
Practice Tags :