boolean a = true, b = false;
System.out.println(a && b); // Output: false
boolean a = true, b = false;
System.out.println(a || b); // Output: true
boolean a = true;
System.out.println(!a); // Output: false
public class LogicalOperators
{
public static void main(String[] args)
{
// Initialize boolean variables
boolean a = true, b = false, c = true;
// Logical AND (&&)
System.out.println("Logical AND (a && b): " + (a && b)); // Output: false
System.out.println("Logical AND (a && c): " + (a && c)); // Output: true
// Logical OR (||)
System.out.println("Logical OR (a || b): " + (a || b)); // Output: true
System.out.println("Logical OR (b || c): " + (b || c)); // Output: true
// Logical NOT (!)
System.out.println("Logical NOT (!a): " + !a); // Output: false
System.out.println("Logical NOT (!b): " + !b); // Output: true
// Using logical operators in a complex condition
if ((a && b) || (c && !b))
{
System.out.println("Condition is true");
}
else
{
System.out.println("Condition is false"); // Output: Condition is true
}
// Another example with short-circuit behavior
if (a && b && (c || !b))
{
System.out.println("All conditions met");
}
else
{
System.out.println("Not all conditions met"); // Output: Not all conditions met
}
}
}
Logical AND (a && b): false Logical AND (a && c): true Logical OR (a || b): true Logical OR (b || c): true Logical NOT (!a): false Logical NOT (!b): true Condition is true Not all conditions met
&&, ||, !) are primarily used with boolean values (true or false).
boolean a = true, b = false; boolean result = a && b; // false.
&&): If the first operand is false, the second operand is not evaluated because the result is already determined.
||): If the first operand is true, the second operand is not evaluated because the result is already determined.
boolean result = a && (b = false); β here, b will not be assigned false if a is false.
if ((a && b) || (!a && c)) { // complex condition }.
() should be used for clarity when combining logical operators with other operators.
boolean result = a && (b || c);.
if (x > 10 && y < 20) { // execute code }.
boolean result = a || b; // result is boolean.
a && b && c, if a is false, b and c are not evaluated.
int a = 5, b = 10; // a && b is invalid and will cause a compile-time error.
true, 0 for false) can lead to logical errors.
true or false) when using logical operators.
! (logical NOT) operator is only applicable to boolean values. Using ! on non-boolean types will result in a compile-time error.
int a = 5; // !a will cause a compilation error.
if (a > 10 && b < 20) { // condition met }.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.