Boolean Operators

   

Most control flow expressions in Java direct program execution based on a computed true or false value. For instance, as you'll see later in this chapter, an if ( expression ) statement causes the next statement to be executed only if expression evaluates to true. You can actually write something like if (true), but this is not very useful in general (except for concepts such as conditional compilation, which you'll learn about later). Instead, control mechanisms such as the if statement are usually driven by a Boolean expression.

Note

The use of the term Boolean in this chapter refers to Boolean logic in general and not the Boolean class found in Java. The expressions used in flow control typically evaluate to the true and false literals associated with the boolean primitive type and not to an object reference. Boolean and boolean are used somewhat interchangeably throughout this chapter depending on the context, but from a Java implementation standpoint, they are referring to the same type of data or expression.


Operators in Java have particular meanings when used in Boolean expressions. Many of these operators are used with the other primitive types as arithmetic and bitwise operators. In most cases, the Boolean meanings are a natural extension from the operations performed on integer types. Table 6.1 shows the operations that can be performed on Booleans.

Table 6.1. Operations on Boolean Expressions
Operation Name Description
= Assignment As in lightOn = true;.
== Equality This produces a true if the two boolean operands have the same value ( true or false ). It produces false otherwise . This is equivalent to NOT EXCLUSIVE OR ( NXOR ).
!= Inequality This produces a true if the two boolean operands have different values (one true, the other false ). It produces false otherwise. This is equivalent to EXCLUSIVE OR ( XOR ).
! Logical NOT A unary operator. If the operand is false, the result is true, and vice versa.
& AND Produces a true if and only if both operands are true. For non- boolean operands, it is interpreted as a bitwise operator.
OR Produces a false if and only if both operands are false. For non- boolean operands, it is interpreted as a bitwise operator.
^ XOR Produces true only if exactly one ( EXCLUSIVE OR ) operand is true. For non- boolean operands, it is interpreted as a bitwise operator.
&& Logical AND Same result for boolean operands as described for &.
Logical OR Same result for boolean as described for .
?: if-then-else Uses a boolean expression before the question mark to determine which of two expressions to evaluate.

The Relational Operators

The most intuitive comparative operators are those that fall into a category known as relational operators. Relational operators include the standard greater-than and less-than symbols you learned about back in third grade. Conveniently enough, they work the same in Java as they did back in third grade, too. For instance, you know that if you write (3>4), you have written something wrong (a false statement). On the other hand, (3<4) is correct (a true statement). These examples use literal values, which makes them easy to evaluate, but not very useful in a program because their result is known in advance, and it is always the same. Fortunately, in Java and other languages, you are not limited to comparing constants when you use relational operators; you are free to use variables , so the statement (accountBalance > minimumBalance) is also a valid relational expression that provides much more potential for use in a flow control statement. These expressions are built using the operators shown here:

Operator Boolean Result
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to

The precedence of the relational operators is below that of the arithmetic operators, but above that of the assignment operator. Thus, the following two assignment statements produce identical results:

 result1 = a+b < c*d; result2 = ((a+b) < (c*d)); 

The associativity of relational operators is left-to-right , but this aspect really is not an issue because they can be used only with non- boolean operands. It might not be immediately obvious what this implies, so consider the following (illegal) expression:

 a < b < c 

Using left-to-right associativity, the expression a < b is evaluated first to produce a boolean value of either true or false. This value would then have to be compared to c. What does it mean to ask if true (or false ) is less than some other operand? Unlike some languages, a boolean in Java is not the same as a 0 or 1 or any other number, so a relational comparison with a boolean has no meaning. An expression like this results in the compiler generating a syntax error.

In C and C++, the relational operators produce an integer value of 0 or 1, which can be used in any expression expecting an integer. Expressions such as the following are legal in C or C++ if the variables are declared accordingly , but they generate compiler errors in Java:

 dailyRate = rateArray [ dayOfWeek < 4 ]; newValue = oldValue + ( newRate > oldRate ) * interest; 

Try a basic program to test some of what you have just learned. Listing 6.1 includes some simple print statements that demonstrate the use of the relational operators with literals.Another convenient fact of Java is used here: You can concatenate boolean values with a string using the + or += operator and the string true or false will be displayed in the output.

Listing 6.1 QuickTest.java ”A Simple Lesson from the Third Grade
 public class QuickTest {      public static void main(String args[]){           System.out.println("5 is greater than 6:"+(5>6));           System.out.println("6 is greater than or equal to 3:"+(6>=3));           System.out.println("8 is less than 10:"+(8<10));      } } 

To run this program, first copy Listing 6.1 to a file called QuickTest.java. As discussed in previous chapters, it's important the file be called QuickTest.java with all capitalization the same. Next, compile the program using javac:

 javac QuickTest.java 

After the file is compiled, you're ready to run it:

 java QuickTest 

As you might have already guessed, the output you get should look like this:

 001 5 is greater than 6:false 002 6 is greater than or equal to 3:true 003 8 is less than 10:true 004 

The Equality Operators

The equality operators are the next set of Boolean operators in Java. Equality operators enable you to compare one value to another to determine if they are the same. In third grade, you might have written an equality statement such as (3=3). Unfortunately, in Java, this statement would cause the compiler to attempt to use the assignment operator rather than evaluate it as a Boolean expression.

The problem is that this is not the result you are looking for. It is also a compiler error when using literal values because you cannot assign a new value to the number 3, even if it is the value 3. To solve this problem, a separate two-character operator ( == ) is used to distinguish equality comparisons from assignments. In Java then, you would write the expression as (3==3). This would be read as "three equals three" and would produce a true result when evaluated. Similarly, the expression (3==4) would evaluate to false.

The two equality operators are very similar to the relational operators, with slightly lower precedence:

Operator Boolean Result
== Is equal to
!= Is not equal to

The equality operators take operands of virtually any type and always produce a boolean result. If the operands are primitive data types, the values of the operands are compared to evaluate the expression. However, if the operands are object references, the purpose of these operators is to determine if both operands refer to exactly the same object. Consider the following example:

 string1 == string2 

In this expression, string1 and string2 must refer to the same string ”not to two different strings that happen to contain the same sequence of characters ”for the expression to evaluate to true. Consider the lines shown in Listing 6.2.

Listing 6.2 ObjectEquals.java ”Comparing Objects in Java
 public class ObjectEquals {      public static void main(String args[]){           String string1 = new String("Hi Mom");           String string2 = new String("Hi Mom");           //At this point string1 is not equal to string2           System.out.println("string1 == string2  :"+(string1==string2));           String string3=string1;           //Now string1 is equal to string2           System.out.println("string1 == string3 :"+(string1==string3));      } } 

Given this sequence, string1==string2 returns false after the first two lines despite the fact that the two objects being referenced are initialized using equivalent string literals. What matters here is that they are not the same object. On the other hand, string1==string3 returns true because these two variables refer to exactly the same object. So as you might have already guessed, the output of this program is as follows :

 string1 == string2 :false string1 == string3 :true 

Note

If you want to compare string1 to string2 based on the text they contain rather than what objects they refer to, you can use the equals method of String. This would be written string1.equals(string2), which would evaluate to true in this case. The equals() method compares the strings character by character. This method is an overridden version of the one defined in the Object class that is introduced later in Chapter 7, "Classes."


The associativity of the equality operators is again left-to-right. You have seen that the associativity of the relational operators is really not meaningful to you as a programmer. The associativity of the equality operators is only slightly more useful. Take a look at the following example:

 startTemp == endTemp == lastRace 

Here, the variables startTemp and endTemp are compared first to produce a boolean result. This result becomes the left operand for a comparison with lastRace. A boolean can only be compared with another boolean for equality, so a compiler error results here if lastRace is any other data type.

Caution

Although this expression is valid if the far right operand is a boolean, you should avoid writing code that requires such a careful examination by the reader to determine its correctness. Even if you understand it completely when you write it, chances are you'll be as mystified as everyone else when you try to read it a few weeks or months later. Try to use constructs in your code that are easily read. If there is some reason that you must use an expression like the one just given, be sure to use comments to explain how the expression operates and, if possible, why you have chosen to implement your algorithm that way.


   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net