Chapter X
Boolean Logic
Chapter X Topics
10.1
Introduction
10.2
What is a Boolean Statement?
10.3
Boolean Operators
10.4
Venn Diagrams & Boolean Algebra
10.5
The Boolean Data Type
10.6
Compound Conditions
10.7
Ranges
10.8
Protecting Against User Data Entry Errors
10.9
Summary
Chapter X
Boolean Logic
Page 365
10.1 Introduction
This chapter will be a departure from the usual format. There are only a few
programs in this chapter, and they are at the very end. There is more . . . this
chapter hardly mentions Java and again, only at the end of the chapter. You are
probably surprised because at this stage, in all likelihood, you thought you were
learning programming in Java. Perhaps this is a good time to set the record
straight. In an AP Computer Science course or an introductory Computer Science
course you learn computer science. A major component of introductory computer
science is to learn the logic and problem solving skills that are part of
programming. Programming is a very major and large focus of introductory
computer science. However, it is a subset. There are concepts to be learned that
are not necessarily programming. Java is one more step down. You need to learn
programming and the current language used in AP Computer Science and
Computer Science is Java.
In other words, you are not taking a class in Java. You are taking a class in
computer science. This course has a major component, which is programming.
The language used to teach the programming components is Java.
In this chapter we will investigate Boolean Logic concepts. The information in
this chapter will be very beneficial in understanding control structures. In an
earlier chapter you were introduced to control structures. In this chapter you will
look at control structures again, and discover that there are many complex
situations that can easily cause confusion. A good understanding of Boolean
Logic will help tremendously in writing program code that is logically correct.
On the other hand, a weak (or no understanding) about Boolean principles can
cause program problems without a clue why the program executed incorrectly.
More than 150 years ago, there was a mathematician, George Boole, who took
statements and wrote them in a precise format, such that a statement is always
true or false. He founded a branch of mathematics called Boolean Algebra.
Statements that are either true or false are called Boolean statements. The
conditions you used with selection and repetition back in Chapter 5 were all
Boolean statements. This chapter could very well be called Boolean Algebra.
The biggest reason is that many concepts that students have learned in Algebra do
not apply to Boolean Algebra. It is too easy for students to think that Boolean
Algebra is a branch of Algebra, which is not true. It is a branch of mathematics.
At any rate, the title matters very little. Let us get down to business and learn
some serious Boolean Logic. If you like mathematics, you will be happy to
increase your mathematical horizon. If you do not like mathematics, you should
be happy that you are learning something that will be very beneficial in
understanding computer science.
366 Exposure Java 2013, PreAPCS Edition
03-01-13
10.2 What is a Boolean Statement?
A good starting point is to look at a variety of English sentences and determine if
these sentences are Boolean statements or not. So, what are the criteria for a
Boolean statement? The sentence, statement, condition, whatever, must be true
or false. Questions, ambiguities, opinions and arguments are not Boolean
statements. You can see why this branch of mathematics has a major impact on
computer science. The basis of processing data is the binary system of on and
off, which certainly sounds a bunch like true or false. Each one of the following
five statements is a Boolean statement.
A mile is longer than a kilometer.
July and August both have the same number of days.
A pound of feathers is lighter than a pound of lead.
The Moon is larger than the Sun.
New York City has more people than Baltimore.
The five sentences may not have seemed very Boolean to you. Let us look at the
sentences again, translate them into brief logic statements, and indicate whether
the statements are true of false. Some Java relational operators are used for the
Boolean statements to help clarify the meaning.
English Sentence
Boolean Statement
Mile > Kilometer
A mile is longer than a kilometer.
July and August have the same days. JulDays == AugDays
A pound of feathers is lighter than a PoundF < PoundL
pound of lead.
MoonSize > SunSize
The Moon is larger than the Sun.
New York City has more people than NYPop > BaltPop
Baltimore.
T/F
True
True
False
False
True
Sentences are not always so short and straightforward. Frequently there are
multiple conditions in one statement. Special rules need to be followed to
determine if the entire statement is true or false. Consider the following sentences
with compound conditions.
Chapter X
Boolean Logic
Page 367
She is a computer science teacher and she is a math teacher.
The number is odd or the number is even.
Enter again if gender is not male or gender is not female.
Employment requires a CPA and five years experience.
The same sentences converted into Boolean statements are:
(She == CSTeacher) and (She == MathTeacher)
(Number % 2 == 1) or (Number % 2 == 0)
(Gender != Male) or (Gender != Female)
(CPA == ‘Y’) and (YrExp >= 5)
These statements are certainly more complex than the earlier examples. Keep in
mind that Boolean statements can be made considerably more complicated. It is
the intention of this chapter to get a firm grip on Boolean logic.
10.3 Boolean Operators
In this section we will look at four different Boolean operators. You know how to
handle arithmetic operators ( + - * / % ). Addition, subtraction, multiplication,
division and remainder operations are performed according to the rules for each
operator. There are also a set of Boolean operators with their own set of rules.
The rules of Boolean operators can be conveniently displayed in a truth table.
This is a table, which shows the possible combinations of a Boolean statement
and indicates the value (true or false) of each statement.
In the truth tables that follow, a single letter indicates a single, simple Boolean
condition. Such a condition is either true or false. Boolean statement A is true or
false. Likewise Boolean statement B is true or false. The truth tables will show
the results of Boolean statements that use both A and B with a variety of Boolean
operators. Employment requirements will be used to explain the logic of each
truth table. In each case imagine that an accountant needs to be hired. Condition
A determines if the applicant has a Degree and condition B determines if the
applicant has at least five years experience.
368 Exposure Java 2013, PreAPCS Edition
03-01-13
Boolean Or
The or Operator
A
T
T
F
F
B
T
F
T
F
A or B
T
T
T
F
Notice that two conditions have four possible combinations. It is important that
you know the results for each type of combination.
In this case the employment analogy requires a Degree OR Experience. This
requirement is quite relaxed. You have a Degree, fine. You have Experience,
that’s also fine. You have both, definitely fine. You have neither, that’s a
problem.
Boolean And
The and Operator
A
T
T
F
F
B
T
F
T
F
A and B
T
F
F
F
Now employment requires a Degree AND Experience. This requirement is
much more demanding than the or operator. You have a Degree, fine, provided
you also have Experience. If you have only one qualification, or the other
qualification, that is not good enough. If you have neither qualification, forget
showing up.
Chapter X
Boolean Logic
Page 369
Boolean Xor
The xor Operator
A
T
T
F
F
B
T
F
T
F
A xor B
F
T
T
F
Everyday human language, like English, uses both the or operator, as well as the
and operator. How about the “exclusive or” xor? A peek at the truth table shows
something pretty weird. If conditions A and B are both true, the compound result
is false. We will try to explain this by using the “cheap boss” analogy. A manager
wants to hire somebody and not pay much money. The advertisement states that a
degree or experience is required.
Candidate X walks in and the boss says: “I’ll hire you, but your pay will be low.
You see, you have a degree but you have no experience at all.”
Candidate Y walks in and the boss says: “I’ll hire you, but your pay will be low.
You see, you have experience but you have no degree.”
Candidate Z walks in and the boss says: “I’m sorry I cannot hire you. You are
over qualified since you have a degree and also experience.”
Let us try another example with a “Student Council” election analogy. The
student council sponsor requires that a candidate shows school spirit by belonging
to a musical organization (band, orchestra, choir) or an athletic team. You can
only run for student council if you belong to one or the other group. However, if
you are active in both a musical organization and an athletic team, the sponsor
does not want you in Student Council. You are too active and won’t have the
time to do a proper job.
Boolean Not
The not Operator
A
T
F
370 Exposure Java 2013, PreAPCS Edition
not A
F
T
03-01-13
This section will finish with the simplest Boolean operator, not. This operator
takes the condition that follows and changes true to false or false to true. There
are special rules that need to be followed when a complex Boolean statement is
used with not. Such rules will be explained later in the chapter. Right now we
want to understand the simple truth table shown earlier. In English we need to
use “double negative” sentences to create an appropriate analogy. I can say “It is
not true that Tom Smith is valedictorian.” This statement results in Tom not
being Valedictorian. On the other hand, if I say “It is not true that Tom Smith is
not the Valedictorian.” Now Tom is the Valedictorian.
10.4 Boolean Algebra & Venn Diagrams
Venn diagrams are useful tools for teaching Set Theory. With a rectangle to
represent the universal set and a group of circles, representing individual sets
inside the rectangle, it is possible to visually demonstrate many Set Theory
concepts. You probably learned about Venn diagrams in one or more
mathematics classes. Boolean Algebra would not have been mentioned in any of
these classes and you learned terms like union and intersection. The relationship
between Boolean Algebra and Set Theory is very close, and the same visual
benefits of Venn diagrams can apply to Boolean Algebra, as well as Set Theory.
Intersection and Logical and
The Boolean Algebra logical and ( * ) can be demonstrated
with Venn Diagrams, using intersection.
Venn Diagram 1 shows the intersection sets A and B. Consider one of the
Boolean examples of the past. You have an employment requirement that
applicants must have a college degree and they must also have five years of work
experience. Now imagine that Set A represents people with a college degree, and
Set B represents people with at least five years of work experience. In this case
the shaded section is the result of saying A and B in Boolean Algebra or the
intersection of Set A and Set B in Set Theory.
Chapter X
Boolean Logic
Page 371
Venn Diagram 1
A and B
A*B
This time our business will hire people that have either a college degree or at least
five years of experience. With the logical or there are now many more people
qualified to apply for the job. We now can interview everybody in Set A, which
are the college degree people as well as everybody in Set B, which are the
experience people. In Boolean Algebra this is stated with the expression A or B.
In set theory this is called the union of Set A and Set B, which is illustrated with
Venn Diagram 2.
Venn Diagram 2
A or B
A+B
372 Exposure Java 2013, PreAPCS Edition
03-01-13
Here is one more hiring situation. We have someone who wants to hire people
who are competent… but not too competent. A person with both a college degree
and 5 years work experience would qualify for a higher salary; however, the boss
of this company is cheap and does not want to pay that much. He will hire people
from Set A, he will hire people from Set B, but anyone in both sets will be
considered over-qualified. This is something like or but it is more exclusive so it
is called “exclusive or” or xor. Venn Diagram 3 shows A xor B which has
people from Set A or Set B, but not both.
Venn Diagram 3
A xor B
A⊕B
The reason for using Venn diagrams is to help illustrate Boolean Algebra
concepts. With small expressions like A and B and A or B you may not see
much need for using Venn diagrams. However, more complex expressions can be
assisted with the help of set theory. Venn diagrams are particularly helpful to
demonstrate that two different expressions are equivalent.
Venn diagrams 4 and 5 illustrate the not operator, which is identical in Boolean
Algebra, as well as in Set Theory. Expressions not(A) and not(B) are shown in
the next two diagrams.
Chapter X
Boolean Logic
Page 373
Venn Diagram 4
not(A)
~A
Venn Diagram 5
not(B)
~B
The remaining Venn diagrams will show a variety of compound Boolean
expressions. Venn diagram 5 illustrates the negation of the intersection of A and
B, which is not(A and B) in Boolean Algebra.
374 Exposure Java 2013, PreAPCS Edition
03-01-13
Venn Diagram 6
not(A and B)
~(A * B)
Venn diagram 7 is very similar to the previous example, but this illustrates the
negation of the union of Set A and Set B. You can compare diagrams 6 and 7
with the earlier diagrams 1 and 2 to notice the pattern of negation.
Venn Diagram 7
not(A or B)
~(A + B)
One of the Boolean Algebra Laws is DeMorgan’s Law, which states that the
expression not(A or B) is equivalent to the expression not(A) and not(B).
Proving this law can be done with Venn diagrams. Note that Venn diagram 7
shows not(A or B) and Venn diagram 8 shows not(A) and not(B). More
importantly, note that both Venn diagrams 7 and 8 illustrate the exact same result.
Chapter X
Boolean Logic
Page 375
Venn Diagram 8
not(A) and not(B)
~A * ~B
The second part of DeMorgan’s Law states that not(A and B) is equivalent to
not(A) or not(B). This law is proven by Venn diagrams 6 and 9. If any
Boolean Algebra laws confuse you, create Venn Diagrams.
Venn Diagram 9
not(A) or not(B)
~A + ~B
376 Exposure Java 2013, PreAPCS Edition
03-01-13
DeMorgan’s Law
not(A and B) = not A or not B
not(A or B) = not A and not B
One more Venn Diagram will be shown. This is the negation of A xor B. Now
if A xor B means one or the other but not both, then its opposite, not(A xor B),
would mean both or neither. Essentially it means that A equals B. Either they
are both true, or they are both false.
Venn Diagram 10
not(A xor B)
~(A ⊕ B)
A == B
Chapter X
Boolean Logic
Page 377
Tricky Venn Diagrams
Sometimes you come across a Boolean expression that is more complicated. For
example, how would you make the Venn Diagram for A and not B? What
about A or not B? What about A xor not B? It is certainly possible to make
Venn Diagrams of these of any Boolean expression; however, it will take a few
steps.
We will start with the expression A and not B. This is not as simple and straight
forward as some of the other Venn Diagrams shown earlier. In order to do this
we need to remember one of the key skills in programming, if a task is too big and
complicated, break it up into smaller easier mini-tasks.
A and not B has two parts. There is A and there is not B. For the first step, I
am simply going to shade in A.
Tricky Venn Diagram
Step 1
A and not B
A * ~B
For the second step, I am going to shade in not B. Notice that I am shading not
B differently from how I shaded A.
378 Exposure Java 2013, PreAPCS Edition
03-01-13
Tricky Venn Diagram
Step 2
A and not B
A * ~B
Once this is done, you now have the ability to figure out the final result. For
A and not B, you need to find the part that was shaded twice. This gives you
something that looks somewhat like a crescent moon.
Tricky Venn Diagram
Step 3
A and not B
A * ~B
Chapter X
Boolean Logic
Page 379
OK, we have figured out A and not B. What about A or not B? What about
A xor not B? Both of these will start the same way as A and not B, meaning
we would shade A one way and not B a different way. Now here is the
difference, for A or not B, the final result is everything that was shaded, once or
twice, it does not matter. For A xor not B, the final result is everything that was
shaded exactly once.
Tricky Venn Diagram
Step 3
A or not B
A + ~B
Tricky Venn Diagram
Step 3
A xor not B
A ⊕ ~B
380 Exposure Java 2013, PreAPCS Edition
03-01-13
10.6 The Boolean Data Type
In chapter 5 you saw how selection control structures assisted in controlling
program flow. The reserved word if, combined with a variety of conditions,
impacts the outcome of a program. You were told that these conditions were true
or false. Everything that you have learned about computers drums the recurring
theme that data processing involves two states. There is on and off, 1 and 0, and
there is true and false. Consider program Java1001.java, in figure 10.1.
Figure 10.1
// Java1001.java
// This program demonstrates a boolean expression being used in an if statement.
public class Java1001
{
public static void main(String args[])
{
System.out.println("\nJAVA1001.JAVA\n");
int x = 10;
if (x == 10)
System.out.println("true");
else
System.out.println("false");
if (x == 5)
System.out.println("true");
else
System.out.println("false");
System.out.println();
}
}
Program Java1001.java does not show any new information. It does show
something that is a bit redundant. The program will display true if it is “true”
that x == 10. The program will display false if it is “false” that x == 10. Program
Chapter X
Boolean Logic
Page 381
Java1002.java in figure 10.2 does the exact same thing, but is much shorter. The
program simply displays the value of the boolean expression x == 10.
Figure 10.2
// Java1002.java
// This program demonstrates that conditional statements have
// true or false Boolean values and these values can be displayed.
public class Java1002
{
public static void main(String args[])
{
System.out.println("\nJAVA1002.JAVA\n");
int x =10;
System.out.println(x == 10);
System.out.println(x == 5);
System.out.println();
}
}
It is helpful in programming logic to test if something is true. You test for correct
password entries, objects that are found, values that are equivalent and so on.
Whenever a true condition exists, a value of 1 can be assigned in the program to
some integer variable. However, programmers prefer greater readability and want
to assign true and false. Modern program languages handle this requirement with
a special boolean data type that only has two possible values: true or false.
If you are like most students, you will find a data type with two possible values
less than handy. That is OK, a boolean data type will grow on you and there are
many applications where both program logic and program readability are served
well with such a simple data type.
382 Exposure Java 2013, PreAPCS Edition
03-01-13
The next 3 programs all do the same thing. We will look at the output first in
figure 10.3 and then look at the code for each program:
Figure 10.3
The program asks a question, and keeps repeating the question until the user
enters the correct answer. In this case, the correct answer in 12.
In program Java1003.java, in figure 10.4, this is accomplished with a repetition
control structure: while (gcf != 12). The part in the parentheses (gcf != 12) is a
boolean statement which evaluates to true or false.
Figure 10.4
// Java1003.java
// This program shows a boolean expression being used in a while statement.
public class Java1003
{
public static void main (String args[])
{
System.out.println("\nJAVA1003.JAVA\n");
int gcf = 0;
int attempt = 0;
while (gcf != 12)
{
attempt++;
System.out.print("\nWhat is the GCF of 120 and 108? --> ");
gcf = Expo.enterInt();
}
System.out.println("\nAnswered correctly after " + attempt + " Attempt(s).\n");
}
}
Chapter X
Boolean Logic
Page 383
Program Java1004.java, in figure 10.5, is made a little more readable by adding a
boolean variable. The boolean variable correct is used to assign true or false
based on the entry of the answer. Yes the same result can be achieved without the
boolean variable, but the program has gained readability and the intention of the
source is clearer.
Figure 10.5
// Java1004.java
// This program introduces the <boolean> data type, which only has two
// values, true or false. Boolean variables add readability to programs.
public class Java1004
{
public static void main (String args[])
{
System.out.println("\nJAVA1004.JAVA\n");
int gcf;
boolean correct = false;
int attempt = 0;
while (!correct) // same as saying while (correct == false)
{
attempt++;
System.out.print("\nWhat is the GCF of 120 and 108? --> ");
gcf = Expo.enterInt();
if (gcf == 12)
correct = true;
else
correct = false;
}
System.out.println("\nAnswered correctly after " + attempt + " Attempt(s).\n");
}
}
Program Java1005.java, in figure 10.6 accomplishes the exact same task as the
previous program with some simplified code. Note that the if ... else statement is
gone. In its place is the rather “bizarre” looking
correct = (gcf == 12);
This statement is both proper Java syntax and the preferred way to handle two
possible outcomes. Yes, the if...else works just fine, but the shorter approach can
make excellent sense. For starters, correct is a boolean type. This means it can
only take on the value of true or false. You found out earlier that conditional
statements have a value, which is true or false. This value can be assigned to a
boolean variable. The program output is exactly identical to the output of the
previous program.
384 Exposure Java 2013, PreAPCS Edition
03-01-13
Figure 10.6
// Java1005.java
// This program executes in the same manner as Java1004.java.
// The abbreviated Boolean assignment statement is used in place of the
// longer if ... else syntax.
public class Java1005
{
public static void main (String args[])
{
System.out.println("\nJAVA1005.JAVA\n");
int gcf;
boolean correct = false;
int attempt = 0;
while (!correct)
{
attempt++;
System.out.print("\nWhat is the GCF of 120 and 108? --> ");
gcf = Expo.enterInt();
correct = (gcf == 12);
}
System.out.println("\nAnswered correctly after " + attempt + " Attempt(s).\n");
}
}
If you still find program Java1005.java confusing, check out the following chart,
in figure 10.7, showing 4 different variable and expressions:
Figure 10.7
Variable
Expression
Assignment
int x;
23 + 45
x = 23 + 45;
double y;
66.23 - 8.11
y = 66.23 - 8.11;
String name;
“John” + “Smith”
name = “John”+”Smith”;
boolean pass;
grade >= 70
pass = grade >= 70;
The first column shows the type of variable; the second shows an expression; and
the third shows the assignment statement. By now you should recognize 23 + 45
as an integer expression. Since x is an int there is no problem with the statement:
x = 23 + 45; In other words, there is no problem assigning an integer expression
to an integer variable. The same thing is shown again with the similar statement
y = 66.23 - 8.11; The value of the real number expression is being assigned to a
Chapter X
Boolean Logic
Page 385
real number variable. While the third example demonstrates concatenation - the
combining or two or more strings - we still see the same thing is happening. The
value of the String expression is being assigned to a String variable.
Now look at the bottom row. pass is a boolean variable, meaning it can store a
value of true or false. grade >= 70 is a boolean expression which, depending on
the value of grade, will evaluate to true or false. Just as in the first three
examples, there is no problem storing the value of a boolean expression in a
boolean variable.
10.6 Compound Conditions
You are about to use Boolean Logic in actual computer programs. Many
situations in life present compound conditions and we will start by looking at four
programs that decide if a person should be hired. The hiring-criteria are based on
years of education as well as years of work experience.
The “Nice Boss” <OR> Example
Program Java1006.java, in figure 10.8, uses a logical OR to decide if somebody
should be hired. In this case somebody is qualified if they have the required
education OR they have the required work experience. We call this boss the Nice
Boss because he is flexible. The user enters the number of years of education and
work experience. Then there is an if statement with a Compound Condition. It
says
if (education >= 16 || experience >= 5)
You might have expected to actually see the word “or” being used somewhere in
the program. Such an expectation is completely logical. Truth be told in most
programming languages the command for OR is OR. Please realize something.
Java copied its Control Structures from C++, which inherited them from the
original C. Apparently the designers of C thought that using OR for OR made
way to much sense. Instead they decided to use two vertical lines || to indicate
the logical OR. The vertical line character is called the “pipe” and is found above
the <Enter> key.
386 Exposure Java 2013, PreAPCS Edition
03-01-13
Figure 10.8
// Java1006.java
// This program demonstrates compound decisions with the logical or ( || ) operator.
public class Java1006
{
public static void main (String args[])
{
System.out.println("Java1006\n");
int education; // years of education
int experience; // years of work experience
System.out.print("Enter years of education ===>> ");
education = Expo.enterInt();
System.out.print("Enter years of experience ===>> ");
experience = Expo.enterInt();
if (education >= 16 || experience >= 5)
System.out.println("You are hired");
else
System.out.println("You are not qualified");
}
}
Chapter X
Boolean Logic
Page 387
Figure 10.8 Continued
The “Picky Boss” <AND> Example
Some bosses are not as flexible as the Nice Boss. Some are very picky. Program
Java1007.java, in figure 10.9, demonstrates the Picky Boss. The Picky Boss only
wants the best people working for him. He only will hire people with BOTH
education AND experience. As with the previous program, the user enters the
number of years of education and work experience. There is another if statement
with a Compound Condition that is only slightly different from the previous
program:
if (education >= 16 && experience >= 5)
As you may have guessed, Java uses a double ampersand && for AND. It should
make sense that getting a job from the Picky Boss is much harder than getting a
job from the Nice Boss.
Figure 10.9
// Java1007.java
// This program demonstrates compound decisions with the logical and ( && ) operator.
public class Java1007
{
public static void main (String args[])
{
System.out.println("Java1007\n");
int education; // years of education
int experience; // years of work experience
System.out.print("Enter years of education ===>> ");
education = Expo.enterInt();
System.out.print("Enter years of experience ===>> ");
experience = Expo.enterInt();
388 Exposure Java 2013, PreAPCS Edition
03-01-13
if (education >= 16 && experience >= 5)
System.out.println("You are hired");
else
System.out.println("You are not qualified");
}
}
Chapter X
Boolean Logic
Page 389
The “Cheap Boss” XOR Example
The Cheap Boss is called Cheap because he wants to pay as little as possible. He
does want people to be qualified so he will hire people with education, or
experience but not both. If they have both they qualify for a higher salary and
that is not good for the Cheap Boss. This is a perfect example of XOR (eXclusive
OR). There is one slight problem. Java does not have an XOR operator… at least
not officially.
Think about what XOR is not. With XOR we do not want people with both
conditions True. We also do not want people with both conditions False. We
could simplify that and say we do not want people that have both conditions
equal. Well, if we do not want people whose conditions are equal, then does it
make sence that we do want the people whose conditions are not equal? If I just
lost you with this little logical explanation do not worry about it. The main thing
is this. We can use the not equals relation operator != for XOR. Program
Java1008.java, in figure 10.10, will demonstrate this. Note the Compound
Condition statement:
if (education >= 16 != experience >= 5)
Figure 10.10
// Java1008.java
// This program demonstrates compound decisions with not equals ( != ) operator.
// != can be used to implement XOR (eXclusive OR).
public class Java1008
{
public static void main (String args[])
{
System.out.println("Java1008\n");
int education; // years of education
int experience; // years of work experience
System.out.print("Enter years of education ===>> ");
education = Expo.enterInt();
System.out.print("Enter years of experience ===>> ");
experience = Expo.enterInt();
System.out.println();
if (education >= 16 != experience >= 5)
System.out.println("You are hired!");
else
System.out.println("You are not qualified.");
System.out.println();
}
}
390 Exposure Java 2013, PreAPCS Edition
03-01-13
Figure 10.10 Continued
Chapter X
Boolean Logic
Page 391
The “Crazy Boss” NOT Example
We now come to the Crazy Boss. The Crazy Boss is completely certifiable
because he will only hire people who have no qualifications what so ever. He
will only hire people with neither education nor experience. This is the exact
opposite of the Nice Boss. If you do not understand why the Crazy Boss is the
opposite of the Nice Boss then compare the outputs of their 2 programs. You will
see that everyone who the Nice Boss will hire is considered “unqualified” by the
Crazy Boss. The Crazy Boss only hires people whom the Nice Boss considers
unqualified.
The Compound Condition for this program will involve using OR (or rather the
double “pipe” ||). We also need a NOT to change the value of the Compound
Condition to its opposite. We have actually already seen this operator. The
exclmation point ( ! ) means NOT. This is why != means NOT Equals. Program
Java1009.java, in figure 10.11, will demonstrate this. Note the use of extra
parentheses in the Compound Condition statement. They are necessary because
we want the NOT to apply to the entire Compound Condition, not just the first
part.
if ( !(education >= 16 || experience >= 5) )
Figure 10.11
// Java1009.java
// This program demonstrates the logical not ( ! ) operator.
public class Java1009
{
public static void main (String args[])
{
System.out.println("Java1009\n");
int education; // years of education
int experience; // years of work experience
System.out.print("Enter years of education ===>> ");
education = Expo.enterInt();
System.out.print("Enter years of experience ===>> ");
experience = Expo.enterInt();
System.out.println();
if ( !(education >= 16 || experience >= 5) )
System.out.println("You are hired!");
else
System.out.println("You are not qualified.");
System.out.println();
}
}
392 Exposure Java 2013, PreAPCS Edition
03-01-13
Figure 10.11 Continued
Chapter X
Boolean Logic
Page 393
Logical Operators in Java
Java uses || to indicate a logical OR.
Java uses && to indicate a logical AND.
Java uses ! to indicate a logical NOT.
Java uses != to indicate a relational NOT EQUALS
which can also be used to indicate a logical XOR.
10.7 Ranges
There are times when you need to see if a number falls within a certain range of
numbers. The teenage years, for example, are between thirteen and nineteen. In
some languages we could simply specify something like 13..19 and the computer
would know you mean all numbers between and including 13 and 19. Java is not
one of those languages; however, if we combine the AND (&&) Compound
Condition with a couple relational operators we can specify the same range of
numbers in this way:
if (age >= 13 && age <= 19)
Program Java1010.java, in figure 10.12, will determine if someone is the proper
age to drive. Assume the proper age range is from 16 through 89.
Figure 10.12
// Java1010.java
// This program determines if an age is between 16 and 89.
public class Java1010
{
394 Exposure Java 2013, PreAPCS Edition
03-01-13
public static void main (String args[])
{
System.out.println("Java1010\n");
int age;
System.out.print("How old are you? ===>> ");
age = Expo.enterInt();
System.out.println();
if (age >= 16 && age <= 89)
System.out.println("You are the proper age to drive.");
else
System.out.println("You are not the proper age to drive.");
System.out.println();
}
}
Figure 10.12 Continued
Chapter X
Boolean Logic
Page 395
Figure 10.12 Continued
Program Java1011.java, in figure 10.13, shows a completely different way to do
ranges by nesting two-way selection. At the same time, this program essentially
achieves multi-way selection with the non-ordinal double data type.
Figure 10.13
// Java1011.java
// This program shows ranges, nested two-way selection,
// and multi-way selection all at the same time.
// This is how you have to do multi-way selection with real numbers.
public class Java1011
{
public static void main (String args[])
{
System.out.println("Java1011\n");
double gpa;
System.out.print("What is your gpa ===>> ");
gpa = Expo.enterDouble();
System.out.println();
if (gpa >= 3.9)
System.out.println("Summa Cum Laude");
else if (gpa >= 3.75)
System.out.println("Magna Cum Laude");
else if (gpa >= 3.5)
System.out.println("Cum Laude");
else if (gpa >= 2.0)
System.out.println("Graduate without honors");
else
System.out.println("Will not graduate");
System.out.println();
}
}
396 Exposure Java 2013, PreAPCS Edition
03-01-13
Figure 10.13 Continued
Chapter X
Boolean Logic
Page 397
10.8 Protecting Against User Data Entry Errors
One unfortunate reality of life is that people make mistakes. Some people make
more than others. When someone uses a computer and it does not work properly,
people get very frustrated. In many cases they are the cause of their own
frustration. The computer is not working because the user entered the wrong
information in the program. Now, if a program is written very well, it can
actually prevent certain errors from occurring.
Program Java1012.java, in figure 10.14, is very similar to some Chapter 5
programs which ask about your SAT score. A valid SAT score is between 400
and 1600. With the earlier programs, nothing would have prevented you from
entering scores of 100, 2000, or even totally ridiculous scores like -365 or
1000000.
Program Java1012.java is simply showing a selection structure nested inside a
repetition structure. Any control structure can be nested inside any other control
structure. The part of the program that enters the SAT score is inside a loop. A
boolean variable stores true if the score is in the valid range of 400..1600, false
otherwise. An if structure displays an error message if the SAT score is not in the
proper range, and the loop repeats as long as the SAT score is not in the proper
range. The user is not able to enter an invalid score. Any attempt to do so result
in an error message and having to reenter the score.
Figure 10.14
// Java1012.java
// This program uses an <if> structure inside a <while> loop to protect
// againt faulty data entry. Valid SAT scores are between 400 and 1600.
// If the user enters a score outside thay range, they will be forced to reenter.
public class Java1012
{
public static void main (String args[])
{
System.out.println("\nJAVA1012.JAVA\n");
boolean scoreOK = false;
int sat;
while (!scoreOK)
{
System.out.print("Enter SAT ===>> ");
sat = Expo.enterInt();
System.out.println();
scoreOK = (sat >= 400 && sat <= 1600);
if (!scoreOK)
{
System.out.println("Error... Please enter a valid SAT score between 400 and 1600.");
System.out.println();
}
}
398 Exposure Java 2013, PreAPCS Edition
03-01-13
if (sat >= 1100)
{
System.out.println("You are admitted");
System.out.println("Orientation will start in June");
}
else
{
System.out.println("You are not admitted");
System.out.println("Please try again when your SAT improves.");
}
System.out.println();
}
}
Figure 10.14 Continued
Chapter X
Boolean Logic
Page 399
10.9 Summary
Computers simulate real life processes that are made simpler, faster and more
accurate. In real life many actions are the result of a single condition and many
other situations require compound conditions. When compound conditions are
evaluated Boolean logic is used.
Boolean logic is based on an Algebra that makes all statements true or false.
Examples of Boolean statements are. John is taller than Tom. Five pounds is
more than ten pounds. Keep in mind that a Boolean statement can be false.
Many students will argue that five pounds is less than ten pounds. Truth is not the
issue. The only concern is that every Boolean statement is unquestionably true or
false.
Some Boolean statements can be tricky. Is the following statement Boolean? Mr.
Schram says that Mrs. Schram is the sweetest wife in the world. Perhaps you
argue that the sweetness of Mrs. Schram is an opinion and therefore cannot be
stated as true or false. However, the statement is absolutely Boolean. Opinion is
not at issue here. Is it true that Mr. Schram made that statement or is it not true?
The question is was the statement made or not made?
There are four Boolean operators, and, or, xor and not. Operator and is very
restrictive and only true when all conditions are true. Operator or is quite
relaxed and true when only a single condition is true. Operator xor, called
exclusive or, is true if one condition is true, but if both conditions are true.
Operator not negates a condition, such that true becomes false and false becomes
true. Truth tables can be useful in evaluating Boolean expressions.
The Venn diagrams of mathematical sets help to clarify Boolean expressions.
The intersection of sets is the same as the and operation. The union of sets is the
same as the or operation. There is also an exclusive or operation (xor) which
means one or the other, but not both. Venn diagrams provide a nice visual aid in
understanding Boolean expressions.
The Java programming language has a Boolean data type called boolean. It is the
simplest of the simple data types with only two values, true and false. This data
type is used for readability. You can use statement like while (!correct) in a
program to enter a password. You gain readability to help debug a program. You
can also use this to make your program more user-friendly and protect against
user data entry errors.
Using Java boolean operators programs can be written with compound
conditions. This can be used in various situations including specifying a range of
numbers.
400 Exposure Java 2013, PreAPCS Edition
03-01-13
© Copyright 2026 Paperzz