Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

The Java Lesson 6: Boolean expressions and operations

JavaFAQ Home » Java Lessons by Jon Huhtala Go to all tips in Java Lessons by Jon Huhtala


Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

The Java Lesson 6

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): ");
x = Keyboard.readInt();
System.out.print("Second number (floating-point): ");
y = Keyboard.readDouble();

// Display information comparing the two values

System.out.println(" " + x + " < " + y + " is " + (x "<" y));
System.out.println(" " + x + " <= " + y + " is " + (x <= y));
System.out.println(" " + x + " > " + y + " is " + (x > y));
System.out.println(" " + x + " >= " + y + " is " + (x >= y));
System.out.println(" " + x + " == " + y + " is " + (x == y));
System.out.println(" " + 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): ");
amount = Keyboard.readDouble();
System.out.print("Valued customer? (Y)es or (N)o: ");
valuedCust = Keyboard.readChar();

// 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);
}
}

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.

A warning about comparing strings

  • 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.): ");
weekDay = Keyboard.readString();

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

isMonday = (weekDay == "Monday");
System.out.println(" Is 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): ");
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);
}
}

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(" The 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


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy