CS 111 - 3/10/15
College Of Engineering: Advising Sign-up Week
- Look for information on your advisor's door
- For a list of advisors, stop by 905 SEO
or check email
Office hours for Prof. Troy will end on Tuesday 3/10
and Thursday 3/12 at 12:20pm.
Multiple conditions: Boolean Operators
Join the results from multiple conditions into a
single boolean value
AND, OR, NOT operations
AND: &&
Syntax:
&&
The result of the AND operation will be true if both
and are true; otherwise,
the result will be false.
Example: Is the value of a variable in a range of numbers?
Check if val1 is between 1 and 10 inclusive
if ( ( val1 >= 1 ) && ( val1 <= 10 ) )
{
System.out.println ("val1 is in the range from 1 to 10");
}
else
{
System.out.println ("Val1 is NOT in the range from 1 to 10");
}
OR Operation: ||
Syntax:
||
The result of the OR operation will be true if either
or is true; otherwise,
the result will be false.
Example: Is the value of a variable outside a range of numbers?
Check if val1 is not in the range from 1 and 10 inclusive
if ( ( val1 < 1 ) || ( val1 > 10 ) )
{
System.out.println ("val1 is NOT in the range from 1 to 10");
}
else
{
System.out.println ("Val1 is in the range from 1 to 10");
}
To help people remember and/or use AND and OR operations,
learning their "Truth Tables" is a valuable tool
ex1 ex2 ! ex1 && ex2 ex1 || ex2
=============================================
true true ! true true
true false ! false true
false true ! false true
false false ! false false
x = 3; y = 2; z = 1;
if ( ( x <= 5 ) || ( y >= 4 ))
{
z = z + 1;
}
else
{
z + z + 2;
}
NOT: !
Syntax:
!
The result of the NOT operation will return true if the
is initially false; Otherwise, it will return
false if the is initially true.
// check if the value in val1 is less than or equal to 5
if ( ! (val1 > 5) )
While not could be used in the above case, most programmers
will not use it there.
However, a more common use would be:
Check if val1 is not in the range from 1 to 10 inclusive
if ( !(( val1 >= 1 ) && ( val1 <= 10 )) )
{
System.out.println ("val1 is NOT in the range from 1 to 10");
}
else
{
System.out.println ("Val1 is in the range from 1 to 10");
}
WARNING: THE FOLLOWING DOES NOT WORK!!!!!
if ( 1 <= val1 <= 10 )
The above code attempts to compare a boolean value with
an integer value, which is UNDEFINED in most computer
languages.