Java Reference
In-Depth Information
Be careful when forming logical expressions. Some beginners make the following common
mistake: Suppose that num is an int variable. Further suppose that you want to write a
logical expression that evaluates to true if the value of num is between 0 and 10 ,including
0 and 10 , and that evaluates to false otherwise. The following expression appears to
represent a comparison of 0 , num ,and 10 that will yield the desired result:
0 <= num <= 10
This statement is not legal in Java and you will get a syntax error. This is because the
associativity of the operator <= is from left to right. Therefore, the preceding expression is
equivalent to:
4
(0 <= num) <= 10
The value of the expression (0 <= num) is either true or false . Because you cannot
compare the boolean values true and false with other data types, the expression
would result in a syntax error. A correct way to write this expression in Java is:
0 <= num && num <= 10
When creating a complex logical expression, take care to use the proper logical operators.
boolean Data Type and Logical (Boolean) Expressions
Recall that Java contains the built-in data type boolean , which has the logical (boolean) values
true and false . Therefore, you can manipulate logical (boolean) expressions using the
boolean data type. Also, recall that in Java, boolean , true ,and false are reserved words.
Suppose that you have the following statements:
boolean legalAge;
int age;
The statement:
legalAge = true ;
sets the value of the variable legalAge to true . The statement:
legalAge = (age >= 21);
assigns the value true to legalAge if the value of age is greater than or equal to 21 . This
statement assigns the value false to legalAge if the value of age is less than 21 . For
example, if the value of age is 25 , the value assigned to legalAge is true . Similarly, if
the value of age is 16 , the value assigned to legalAge is false .
 
 
Search WWH ::




Custom Search