Java Operators

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java Interfaces

Java Data Structures

Java Collections Algorithms

Advanced Java

Java Miscellaneous

Java APIs & Frameworks

Java Class References

Java Useful Resources

Java - Logical Operators



Java logical operators are used to perform logical operations on boolean values. These operators are commonly used in decision-making statements such as if conditions and loops to control program flow.

List of Java Logical Operators

The following table lists the logical operators in Java:

OperatorDescriptionExample
&& (Logical AND)Returns true if both operands are true, otherwise returns false.(A && B) returns true if both A and B are true.
|| (Logical OR)Returns true if at least one of the operands is true.(A || B) returns true if either A or B is true.
! (Logical NOT)Reverses the logical state of the operand.!A returns true if A is false, and false if A is true.

The following programs are simple examples which demonstrate the logical operators. Copy and paste the following Java programs as Test.java file, and compile and run the programs −

Example 1

In this example, we're creating two variables a and b and using logical operators. We've performed a logical AND operation and printed the result.

 public class Test { public static void main(String args[]) { boolean a = true; boolean b = false; System.out.println("a && b = " + (a&&b)); } } 

Output

 a && b = false 

Example 2

In this example, we're creating two variables a and b and using logical operators. We've performed a logical OR operation and printed the result.

 public class Test { public static void main(String args[]) { boolean a = true; boolean b = false; System.out.println("a || b = " + (a||b) ); } } 

Output

 a || b = true 

Example 3

In this example, we're creating two variables a and b and using logical operators. We've performed a logical Negate operation and printed the result.

 public class Test { public static void main(String args[]) { boolean a = true; boolean b = false; System.out.println("!(a && b) = " + !(a && b)); } } 

Output

 !(a && b) = true 
Advertisements
close