Boolean expressions and operations

Boolean expressions

• Always result in a boolean value (either true or false)

• Are used to resolve logic questions, such as determining if two variables have the same value

• May contain several different operators

Comparison operators

• Used to compare the values of two variables or constants

• Require that the two operands be either both numeric (including char) or both boolean. A numeric value cannot be compared to a boolean value.

• Frequently appear in if, for, while, and do-while statements (to be covered later)
 Operator Operation < Less than <= Less than or equal > Greater than >= Greater than or equal == Equal != Not equal

Note: Java makes a clear distinction between assignment ( = ) and a test for equality ( == ). Failure to understand this leads to many programming errors!

Example: This program reads two numeric values from the user and displays the result of several comparisons involving the two numbers.

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

// Variables for holding two numeric values entered by the user

int x;
double y;

// Prompt for and read the two numeric values

System.out.print("First number (integer): ");
System.out.print("Second number (floating-point): ");

// Display information comparing the two values

System.out.println("\n\t" + x + " < " + y + " is " + (x < y));
System.out.println("\t" + x + " <= " + y + " is " + (x <= y));
System.out.println("\t" + x + " > " + y + " is " + (x > y));
System.out.println("\t" + x + " >= " + y + " is " + (x >= y));
System.out.println("\t" + x + " == " + y + " is " + (x == y));
System.out.println("\t" + x + " != " + y + " is " + (x != y));
}
}

Note: When you test this code, use several different values - including the same value for both numbers.

Logical operators

• Combine the results of two Boolean expressions into a single boolean value

• 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.

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

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

double amount;
char valuedCust;

// 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): ");
System.out.print("Valued customer? (Y)es or (N)o: ");

// 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("\n\tFree shipping? " + isFree);
}
}

Note: When you test this code, use several different values - including upper and lower case 'Y' or 'N' in response to the "Valued Customer?" prompt.

• Strings are objects. If you attempt to compare them using the comparison operators, you are comparing where they are stored in memory (their addresses) and NOT their contents.

• To properly compare the contents of two String objects you should use the equals() method. This will be covered in a later lesson.

Example: This program reads a string from the user and erroneously tests it to determine if they entered "Monday". Because the user's String object and the literal's String object are in different memory locations, the result of the comparison will always be false, even if the user enters "Monday".

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

// String variable for the day of the week

String weekDay;

// Variable for indicating if the day is Monday

boolean isMonday;

// Prompt for and read the day of the week

System.out.print("Day of the week (Monday, Tuesday, etc.): ");

// Determine and display information about the day of the week.

isMonday = (weekDay == "Monday");
System.out.println("\n\tIs the day Monday? " + isMonday);
}
}

Certain logical operators can be combined with assignment

• The operators are &= (AND equals), |= (OR equals), and ^= (XOR equals)

• The left operand must be boolean

Example: The following program reads a boolean value from the user and displays its opposite value.

public class App {
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): ");

// 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("\n\tThe opposite value is " + value);
}
}

Note: An alternate way to set the opposite value is to code.

value = !value;

Review questions

1. If x is a long variable with a value of 654321 and y is a float variable with a value of 654321.0, what will result from the following expression?

x = y

1. true

2. false

3. 0

4. 1

5. a compile error

1. What will be displayed by the following code fragment?

boolean x = true;
boolean y = false;
boolean z = !x;
System.out.println("Test 1: " + (x | y));
System.out.println("Test 2: " + (y & z));
System.out.println("Test 3: " + (z ^ x));

1. Test 1: true
Test 2: true
Test 3: true

2. Test 1: true
Test 2: false
Test 3: true

3. Test 1: true
Test 2: false
Test 3:
false

4. Test 1: false
Test 2: false
Test 3: true

5. Test 1: false
Test 2: true
Test 3:
false

1. What will happen if an attempt is made to compile and execute the following code? You may assume the statements are within a valid main method of a valid application class and that the line numbers are for reference purposes only.

 1 2 3 4 double big = 45.67; byte little = 45; boolean result = big > little && little != 100; System.out.println("\n\tThe result is " + result);
1. the program will compile and run to display "The result is true"

2. the program will compile and run to display "The result is false"

3. the program will compile but an error will occur at run time

4. a compile error will occur at line 3

5. a compile error will occur at line 4

1. Which of the expressions below are equivalent to the following?  (choose two)

x <= 0

1. !(x >= 0)

2. 0 > x

3. !(x > 0)

4. 0 >= x

5. 0 => x