Logical operators

1. Combine the results of two Boolean expressions into a single boolean value
2. Provide for complex logic. The following table shows the operators and how they can be
 used to combine the results of two Boolean expressions X and Y:
Operator
Operation
Resulting value true if…
X and Y always evaluated?
& AND X and Y are both true Yes
| OR either X or Y is true Yes
^ XOR (exclusive OR) X and Y have different values Yes
&& Conditional AND X and Y are both true No
|| Conditional OR either X or Y is true No\
The conditional AND ( && ) and OR ( || ) are sometimes called “short-circuit” operators because the second operand is not always evaluated depending on the value of the first operand. If the first operand is false, the result of an AND will always be false regardless of the value of the second operand. If the first operand is true, the result of an OR will always be true regardless of the value of the second operand.
Example:
The following program uses two values entered by the user to determine if a customer is entitled to free shipping. A customer receives free shipping if their order amount is greater than or equal to 100 and they are a preferred customer.
import java.util.*;
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

// Variables for holding order amount and valued customer data to be
// entered by the user

// Variables for holding information about free shipping

boolean isFree;

// Prompt for and read order amount and valued customer data

System.out.print(“Order amount (floating-point): “);
Scanner Keyboard= new Scanner(System.in);
double amount;
amount =Keyboard.nextDouble();
System.out.print(“Valued customer? (Y)es or (N)o: “);
Char valuedCust;

valuedCust = Keyboard.nextChar();

// Determine and display information about free shipping.
// Shipping is free if the order amount is greater than or equal $100
// AND the customer is a valued customer.

isFree = (amount >= 100 && (valuedCust == ‘Y’ || valuedCust == ‘y’));
System.out.println(” Free shipping? ” + isFree);
}
}

Output
Certain logical operators can be combined with assignment
1. The operators are &= (AND equals), |= (OR equals), and ^= (XOR equals)
2. The left operand must be boolean
Example:
The following program reads a boolean value from the user and displays its opposite value.
public class AppCer
{
public static void main(String[] args)
{

// Variable for holding a boolean value entered by the user

boolean value;

// Prompt for and read the boolean value

System.out.print(“Enter a boolean value (true or false): “);
value = Keyboard.readBoolean();

// Determine the opposite value. If the value is false, XOR with
// true results in true. If the value is true, XOR with true results
// in false.

value ^= true;

// Display the new value of the value.

System.out.println(” The opposite value is ” + value);
}
}
***try this yourself

Scroll to Top