Bluej and Pi
Bluej and Pi
Ron McFadyen
Copyright
c 2015 by Ron McFadyen
Ron McFadyen
Department of Applied Computer Science
University of Winnipeg
515 Portage Avenue
Winnipeg, Manitoba, Canada
R3B 2E9
[email protected]
[email protected]
iii
iv
Contents
1 Introduction 1
1.1 Java, the beginning . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Running Java Programs . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 A First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 BlueJ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Basics 7
2.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.1.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.3 boolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.4 byte, short, int, long . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.5 float, double . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.6 Calculations in Java . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.6.1 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.6.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.6.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.6.4 Mixed Mode Expressions . . . . . . . . . . . . . . . . . . 17
2.6.5 Unary Operators . . . . . . . . . . . . . . . . . . . . . . . 18
2.6.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.7 The String Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.7.1 Catenation operator + . . . . . . . . . . . . . . . . . . . . 23
2.7.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.8 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.8.1 System.out . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.8.2 JOptionPane . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.9 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.9.1 The Scanner Class . . . . . . . . . . . . . . . . . . . . . . 27
2.9.2 The JOptionPane Class . . . . . . . . . . . . . . . . . . . 28
v
vi CONTENTS
3 Control Structures 31
3.1 Compound statements . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2 The while Statement . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.2.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.2.2 Nesting statements . . . . . . . . . . . . . . . . . . . . . . 38
3.2.3 Autoincrement . . . . . . . . . . . . . . . . . . . . . . . . 39
3.2.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.3 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.3.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.3.2 Nesting statements . . . . . . . . . . . . . . . . . . . . . . 42
3.3.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.4 The for Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.5 The do while Statement . . . . . . . . . . . . . . . . . . . . . . . 46
3.6 The switch Statement . . . . . . . . . . . . . . . . . . . . . . . . 46
3.7 Logical Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.7.1 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Chapter 1
Introduction
• 2015 - awarded the IEEE John von Neumann Medal for ”the Java pro-
gramming language, Java Virtual Machine, and other contributions to
programming languages and environments”.[3]
1
2 CHAPTER 1. INTRODUCTION
In 2010 Oracle acquired Sun Microsystems and took over the development
of the language. The language has gone through a number of updates, and at
the time of writing the current release is referred to as Java 8. All programs in
this text have been tested on Java 8.
This text is about programming Java applications. The student may be
interested Java applets (these run in a web browser) which are discussed in an
appendix.
When you inspect this program one thing that is immediately obvious is that
there is a lot of overhead to do just one thing. Each line of the program is
explained below:
1. The first line gives a name to the program: HelloWorld.
2. The program is actually a Java class and the lines making up the class are
delimited by the { in line 2 and the } in the very last line.
3. A class like this has a method, and the third line gives the name main
to this method. In general, a method can take arguments and the text
(String[] args) is the way those are indicated for a main method - much
more on this in a later chapter.
4. The lines that comprise the main method begin with the { in the fourth
line and end with the } in the seventh line.
5. Line 5 is an assignment statement that says the value to be assigned to
the variable message is the text Hello World. When this line executes the
string Hello World is stored in a memory location reserved for the variable
message.
6. Line 6 is an example of how output is obtained. When this line executes
the contents of message are transferred to a display unit.
1.3.1 Exercises
1. Run the Hello World program.
2. Modify the Hello World program so it displays a different message.
4 CHAPTER 1. INTRODUCTION
1.4 BlueJ
BlueJ is an integrated development environment that provides the programmer
with a framework that includes an editor, compiler, and a runtime environ-
ment. It is our experience that BlueJ is very suitable for the beginning Java
programmer.
BlueJ is available as a free download from http://www.bluej.org. There is
no point repeating a description and installation instructions that can be found
at the BlueJ site. Below is a picture showing HelloWorld in a BlueJ project.
Note the button available to compile the source code.
1.5. RASPBERRY PI 5
1.5 Raspberry Pi
The Raspberry Pi is a small computer developed by the Raspberry Pi foundation
in order to promote the teaching of computer science. One remarkable point
about the Raspberry Pi is its price: US$35 (at the time of writing). The current
model comes with 1 GB of memory, 4 USB ports, an ethernet port, a camera
interface, HDMI and composite outputs, a micro SD slot, and a set of general
purpose input/output pins. The computer weighs 45 grams and it all fits inside
a case with dimensions 9.5 ×6.2 × 2.7cm.
At the Raspberry Pi and BlueJ sites you will see that the Pi runs BlueJ
(and all the programs included in this text have been run on the Pi). Of course
one does need some additional components to make it useful: keyboard, mouse,
monitor, internet. Below is a picture of one installed inside a clear case with a
wireless keyboard/mouse adapter, wifi adapter, and HDMI cable attached.
6 CHAPTER 1. INTRODUCTION
Chapter 2
Basics
The focus of this chapter is literals, variables, primitive data types, and related
expressions. It is common for programs to include constants; in Java these are
referred to as literals. Examples include: 123, 123.45, ’a’, ”Gosling”, true. You
will see literals used in many examples to follow.
Variables are indispensable to programming. A variable is simply a name
given to a piece of computer memory - a piece of memory that holds a value that
a program can use and change as it executes. The Java programming language
requires us to declare the type of data to be associated with a variable. There are
eight primitive data types: byte, short, int, long, float, double, char and boolean.
When you develop a program you choose a specific data type depending on the
nature of the data your program processes:
• byte, short, int, and long are used for cases where the data is to be treated
as whole numbers. For example, 33, 498, -100 are whole numbers (numbers
without a fractional component). These data types differ with regards to
the magnitude of number they can represent.
• float and double are used for cases where the data is numeric and where
one expects values to have a fractional component such as: 101.5, 26.334,
-55.5. When written we show them with a decimal point. Again, these
two types differ with regards to size in terms of the number of significant
digits and in the magnitude of the number they can represent.
• boolean is used when the situation requires one to work with logical values
of true and false. In a Java program these values are written just as we
do in English: true, false.
7
8 CHAPTER 2. BASICS
2.1 Variables
The concept of a variable is very important to programming. A variable is
a named location in a computer’s memory. A Java programmer will declare
variables in declaration statements and then use those variable names later
in the program to refer to the value currently associated with the variable.
Consider the program below which does the following:
As you study Java you will find that certain names are keywords and as
such they cannot be used for variable names - keywords are reserved for special
purposes only. The word int in a Java program is reserved for situations where
one declares a variable to be of type int. For instance, you cannot declare a
variable to have the name int. In sample programs we have seen a few of these
reserved words: public, class, void, static.
Naming Variables
A convention used by many Java programmers is to choose names that are
short yet meaningful. A name you choose should indicate the intent of its
2.2. CHAR 9
use. In situations where the intent of use involves more than one word a Java
programmer will often name the variable in camel case. For instance, suppose
you need a variable to keep track of net pay. In order to have a proper name
a programmer could choose the name netPay for the variable. Two words are
involved: net and pay. the first word is in lower case and other word is catenated
to it, and only the first letter of the second word is capitalized. Camel case is
a style where words are catenated together forming a variable name - the first
word is all lower case, the second and subsequent words have only the first letter
capitalized.
Some examples of variables named according to camel case:
netPay grossPay
dayOfWeek shippingAddress
monthOfYear billingAddress
studentNumber lastName
Camel case is a good convention to follow when declaring variables. How-
ever, Java will accept any variable name (that is not a keyword) as long as the
name starts with a letter and contains any mixture of letters, digits, and the
underscore character (’ ’). Some valid variable names include: a123, net pay,
gross pay.
Java variable names are case-sensitive. This means that variable names such
as NetPay and netPay are two distinct variables.
2.1.1 Exercises
1. Choose one of the programs from above and modify it to use a keyword
for a variable name. What is the response you get from the Java compiler.
2. Modify the println in the Hello World so that the variable message is
misnamed as Message with a capital M. What is the response you get
from the Java compiler.
2.2 char
char is used when you need to handle characters individually. When you
see a char value in a program you see them enclosed in single quotes, as in:
’a’,’A’.’q’,’%’.
Java organizes memory for char values so that each one is stored in 2 bytes
of memory. 2 bytes of memory means that there can be as many as 65536(216 )
individual characters.
2.3 boolean
The boolean type has two values: true and false. We will see that the boolean
type is particularly important when we discuss logical expressions and control
structures.
10 CHAPTER 2. BASICS
program needs to represent monetary values. More about this much later on in
the text. These types differ with respect to the number of significant digits they
store (approximately 7 for float and 16 for double) and the overall magnitude
of a value:
Try running the above program and verify the output is as indicated.
If a data type for a value with decimal places is not given, the default is
double; therefore, the calculations in the above example were carried out using
double arithmetic.
• the order of operations can be critical: in this case the formula for con-
verting Celsius to Fahrenheit requires the division to be performed before
the multiplication and the subtraction must be done last;
2.6.1 Expressions
An expression is Java code which, when evaluated, yields a value. We will firstly
consider expressions that involve literals, variables and operators.
i = 1;
i = 1
followed by a semi-colon. In the above, the equals (=) sign is an operator, and
the expression
i = 1
2.6.2 Exercises
1. Modify the following program so the two print statements produce exactly
the same results. For this to work, Java statements that interchange the
values of x and y are required.
10
2. Modify question 1 so that the two values for x and y are obtained as input
from the user.
Other Operators
Other operators we consider in this section are +, -, *, /, and %. Note that any
example that uses % will be using int operands.
As with the equals operator these are used in an infix fashion: one operand to
the left of the operator and one operand to the right of the operator. Some
examples:
Operator Examples
netPay + overtimePay
grossPay - netPay
hours * 20.50
13 / 5
13 % 5
Complex expressions
Expressions can be more complicated; we can write more complex expressions
involving these operators so long as each variable, literal, or sub-expresson is
separated from the next variable or literal by an operator. At least one space
14 CHAPTER 2. BASICS
Java Expressions
9.0 / 5.0 * c - 32.0
f = 9.0 / 5.0 * c - 32.0
number / 10 * 10
grossPay - deductions * taxRate
Operator Priorities
When you examine the above expressions, in what order do you think the oper-
ations are performed? Are calculations performed in a left-to-right manner, or,
are some operations performed before others?
Consider the last example
forcing the subtraction to be performed first and for that result to be multiplied
by the tax rate. Sub-expressions are evaluated first, before the expression of
which it a part.
The order in which expressions are evaluated is determined as indicated in the
following table:
Order of Evaluation
Highest to Lowest
sub-expressions
* /%
+-
=
Example 1
Consider the expression
13 % 5
We will only consider in this text the use of the modulo operator, %, where both
operands are integers. When the operands are integers, the modulo operator
returns the remainder when the first operand is divided by the second operand.
So this example evaluates to 3, the remainder when 13 is divided by 5.
Exercise: What expression would yield the rightmost digit of an integer stored
in the variable number ?
Example 2
Now consider the expression
netPay = grossPay - deductions * taxRate
Of the operators in the expression, the multiplication operator has the highest
priority and so it is performed first, the minus operation is performed next, and
since assignment has the lowest priority it is performed last. We can show this
order of evaluation using parenthesis where sub-expressions match what we have
just stated:
netPay = (grossPay - (deductions * taxRate) )
Suppose the intention of the programmer was to implement a business rule
where the taxes to be paid were to be calculated as the product of the tax
rate and the difference between gross pay and deductions. According to the
business rule, the default evaluation according to operator priorities is not what
the programmer requires; to get the expression evaluated as per the business
rule, we need to have:
netPay = (grossPay - deductions) * taxRate
Example 3
For the operators +, -, /, *, and %, when there is more than one operator of
the same priority then they are carried out from left to right. Consider the
expression
9.0 / 5.0 * c - 32.0
where the programmer intends that a value in degrees Celsius is converted to
Fahrenheit using the well-known formula:
9
F = C − 32
5
This expression has two operators of the same priority (/ and * ). Since mul-
tiplication and division have the same priority, 9.0 is divided by 5.0 and that
result is multiplied by c - the expression is evaluated as required to convert
Celsius to Fahrenheit.
16 CHAPTER 2. BASICS
Example 4
If an expression has more than one assignment operator then those are carried
out from right to left. Consider the expression
and consider the priorities of the operators. Let us suppose grossPay is 100.00,
deductions is 10.00, and that taxRate is 0.10.
The values of netPay and taxesPaid will be the same, 99.00. The expression is
evaluated according to the sequence:
Example 5
Recall from Example 4, if an expression has more than one assignment operator
then those are carried out from right to left. Now consider a similar expression
but where we have a sub-expression:
Consider the priorities of the operators and the use of the subexpression to
override operator priorities. Again, let us suppose grossPay is 100.00, deductions
is 10.00, and that taxRate is 0.10.
The values of netPay and taxesPaid will be different. The expression is evaluated
according to the sequence:
If the intention of the programmer was to implement two business rules where
(1) net pay is determined as gross pay minus deductions, and (2) the taxes to
be paid were to be calculated as the product of the tax rate and net pay, then
the above expression implements both rules.
2.6. CALCULATIONS IN JAVA 17
2.6.3 Exercises
The last two exercises refer to programs available at the website for this text.
These two programs could be modified to assist in answering questions 1, 2, and
3.
4. Run the TaxesPaid program and verify the output from Example 4. Note
in the program that the expression is followed by a semi-colon to be a
proper Java statement.
(9/5) * 1 - 32.0
The sub-expression, 9/5, involves integers and the result is an integer yielding
a value of 1. Next in the evaluation will be the multiplication involving 1 and
1, which yields the int value of 1. Now we have 1 minus 32.0. For this to be
performed the 1 is converted to 1.0 and the final result is -31.0. Note that this
would be considered inacurrate (wrong) for the conversion of 1 degree Celsius to
Fahrenheit. To get a more accurate result the expression should have involved
9.0/5.0.
Narrowing conversions are cases where there could be a loss of precision going
from one type to another. For example converting an double to a char is not
allowed unless the programmer directly indicates that casting from one type to
another is be performed. We will leave the cast language construct until a later
chapter.
-(1000 / 10)
is -100.
2.7. THE STRING CLASS 19
2.6.6 Exercises
1. The expressions
(9/5) * 30 - 32.0
and
(9.0/5.0) * 30 - 32.0
2. Write a program that will print the integer values for the characters ’a’,
’b’, ’c’, ’A’, ’B, ’C’, ’1’, ’2’, ’3’. Note that you can use a statement such as
Because text strings are used so often Java provides a ”short-cut” for assigning
values to String variables without the need for using the new keyword:
Recall that String was not mentioned in the section on primitive data types.
The assignment statement above causes an object to be created and a reference
to that object is stored in the variable fullName. There is a subtle difference
that is hard to appreciate at this time: the varible holds a reference to the value
instead of holding the actual value. The diagram below attempts to show the
difference.
20 CHAPTER 2. BASICS
Because strings are objects defined as String another way to declare fullName
and assign it a value is:
The String class provides many methods for working with text strings such as:
2.7. THE STRING CLASS 21
24 // trim both and then compare the two strings for equality
ignoring case
25 fullName = fullName.trim();
22 CHAPTER 2. BASICS
26 fullNameLc = fullNameLc.trim();
27 namesAreEqual = fullName.equalsIgnoreCase(fullNameLc);
28 System.out.println("\nTriming and then testing for equality
ignoring case yields: "+namesAreEqual);
29
34 }
35 }
2.7.2 Exercises
1. Evaluate the following Java expressions:
"x = "+100
"x = "+100+200
2.8 Output
2.8.1 System.out
A simple way to generate output for the user is to use the println() and print()
methods that belong to the pre-defined Java class named System and an object
within System named out. The output generated is said to go to the standard
output device. When you use this type of output with BlueJ you will see a
window pop up named ”Terminal Window” that contains the output produced
by the program.
The following program listing illustrates ways of producing output. The println()
and print() methods take one argument which is a text string. Often that text
string is composed of multiple catenations. Notice the last println() introduces
some special characters for new line and tabbing. The special characters are
not displayed, they are used to control the appearance of the output.
31 }
println() advances to a new line and then displays output. print() differs from
println() in that it does not automatically advance to a new line when it dis-
plays output; instead, output begins at the point where the previous print() or
println() left off. If we change all the println() to print() expressions for the
previous example the output we get is:
2.8.2 JOptionPane
In some situations a programmer may find JOptionPane message dialogs useful.
The following program shows how to display some information. When the pop-
up window appears, the program is suspended until the user clicks the OK
button. Note that line 1 is an import statement that directs the compiler to the
location where it find details of the Scanner class.
8 deductions = 10.00;
9 // Calculate net pay
10 netPay = grossPay - deductions;
11 JOptionPane.showMessageDialog(null, "net pay is "+netPay);
12 }
13 }
The pop-up window the user showing the information and an OK button:
2.9. INPUT 27
2.9 Input
We examine two ways a programmer can arrange to get input from the user by
using pre-defined Java classes: the Scanner class and the JOptionPane class.
The program below shows one how to use next(), nextDouble(), and nextInt()
to obtain a user’s name, hours worked and rate of pay. Note that line 1 is an
import statement that directs the compiler to the location where it find details
of the Scanner class.
The above program was run, and the contents of the Terminal Window are
shown below. This window shows the output/prompts from the program and
the input provided by the user via the keyboard.
Line 5 is required since we need to tell the Java compiler where it can find the
JOptionPane class. When line 9 executes it causes a dialog box to be displayed
to the user (see below). The user is able to enter a value in the box and press
OK. Then control goes back to the program and the value entered is assigned
to firstName. A similar dialog box is displayed when line 10 executes.
30 CHAPTER 2. BASICS
Chapter 3
Control Structures
31
32 CHAPTER 3. CONTROL STRUCTURES
The order of execution of Java statements can be visualized using a flow diagram:
How the JVM executes a while
Example 1
Consider the following program that prints numbers from 0 to 9:
The JVM starts sequential execution with the statement in line 8 - the variable
count is initialized to 0. The JVM then moves on to Line 9 which results in the
printing of a heading for the output. Next, the JVM encounters the while loop
in Line 10. Observe that lines 11 and 12 form a compound statement (enclosed
in curly braces). This compound statement is executed for count equal to 0, 1,
2, and so on, up to count equal to 9; when count has the value 9 the compound
statement is executed and count is assigned the value 10 in line 12. That’s
the last time the compound statement is executed since the value of the logical
expression evaluates to false - the JVM will move on to the statement following
the while statement (line 14) where normal sequential execution resumes. The
output follows:
3.2. THE WHILE STATEMENT 35
Example 2
Consider another program which displays the digits of a positive number that
the user provides as input. This program uses a scanner object in order to get
input from the user via the keyboard.
20 }
21 }
36 CHAPTER 3. CONTROL STRUCTURES
This program has a while loop where the number obtained from the user is
altered each time the loop executes. Line 16 contains the expression
number / 10
3.2.1 Exercises
1. Write a program that will sum the digits from -100 to 100.
2. What happens when a user enters the value 0 when DisplayDigits is exe-
cuted?
4. What happens when a user enters something that is not an integer when
DisplayDigits is executed?
5. Write a program that converts from Celsius to Fahrenheit for Celsius val-
ues starting at -40 and going up +40 in increments of 1.
6. Write a program that converts from Celsius to Celsius for Fahrenheit val-
ues starting at -40 and going up +40 in increments of 1.
3.2. THE WHILE STATEMENT 37
Use a while to calculate n!. Prompt the user for the value of n.
38 CHAPTER 3. CONTROL STRUCTURES
Example 3
consider the program:
26 }
27 }
The above program has two variables i and j. The outer while (lines 15-23) is
executed twice, once with i equal to 0 and then with i equal to 1. The inner
while (lines 18-21) is executed once for each value of i; for each value of i, the
variable j takes on the values 0, 1, and 2. Study the program to verify the output
shown next. How many times is the print statement (line 19) executed? Notice
the indentation of lines 18-21; this is done simply to help a human read the
code - one quickly sees that those lines are a control structure that is embedded
inside another control structure.
3.2. THE WHILE STATEMENT 39
3.2.3 Autoincrement
Because statements that increment a variable’s value, such as
i = i + 1;
are so common Java has a special unary operator ++ for this. The statement
i++;
has the same effect as the above assignment statement. ++ is a unary operator
(takes one operand). The operand can be before or after the ++. The difference
relates to when the increment occurs which is only relevant in more complex
expressions. See the section on Unary Operators for more information.
Java has a similar operator, - -, which has the effect of decrementing the value
of a variable, and so the following two statements are equivalent:
count = count - 1;
count--;
3.2.4 Exercises
1. Modify the programs in this section to use the ++ operator where it can
be applied.
2. Use nested whiles to print a 4 × 4 times-table. The times-table should
appear as follows
1 2 3 4
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16
40 CHAPTER 3. CONTROL STRUCTURES
When the JVM executes an if statement, the JVM will first evaluate the log-
ical expression. If the expression is true then statement-1 is executed; if the
expression is false then statement-2, if present, is executed. The if statement
conditionally executes either statement-1 or statement-2. The JVM process can
be visualized as:
Example 1
Consider the following program that displays a different message depending
on the value of the expression number > 0. Note that compound statements
are used even though it was not necessary - some programmers always code
compound statements. Exactly one of the two compound statements will be
executed.
3.3.1 Exercises
1. Modify PositiveOrNot so that it obtains a number from the user. Use a
Scanner object so that you can get the number as an integer.
2. Write a program that obtains a number from the user and displays whether
the number is an even number or an odd number. Consider using the %
operator.
3. Write a program that obtains two numbers from the user and displays the
larger of the two numbers.
42 CHAPTER 3. CONTROL STRUCTURES
Example 2
Consider where a customer is paying for some goods with either cash or a debit
card. Suppose there are no pennies in circulation and if someone is paying with
cash the cost is rounded to the nearest nickel. For instance if the cost is $10.22
then the cost is rounded down to $10.20, and if the cost is $10.23 the cost is
rounded up to $10.25. Suppose also that a debit card payment has a surcharge
of 25 cents. Consider the following program where the program prompts for the
type and cost of a purchase, and handles a cash or debit purchase appropriately.
To avoid rounding errors the program uses integers for the cost and so the cost
is processed in cents (not as a double where a decimal point separates dollars
and cents).
28 }
29 }
44 CHAPTER 3. CONTROL STRUCTURES
Example 3
Consider how a letter grade could be translated into a numeric grade, as defined
in this table:
If you were given a letter grade, its a simple matter to find the grade in the
letter grade column and look across to find out the grade point value. We can
do a similar thing in Java using nested if statements. In the program below
each if represents a line in the table. Assuming the grade obtained from the
user appears in the table, the grade will be determined.
30 }
Observe the indentation in the listing above. When each logical expression is
basically the same with one simple change (the value A, B, ...) a Java program-
mer will change the indentation to that shown below, and may then refer to an
if else-if structure.
1 import java.util.Scanner;
2 /**
3 * Determine a numeric equivalent to a letter grade.
4 * Note how "else if" appears on one line
5 * and how they are aligned.
6 */
7 public class IfElseIfIndentation
8 {
9 public static void main(String[] args)
10 {
11 String letterGrade;
12 double numericGrade;
13 System.out.println("Please enter letter grade:");
14 Scanner kb = new Scanner(System.in);
15 letterGrade = kb.next();
16 if (letterGrade.equals("A"))
17 numericGrade = 4.0;
18 else if (letterGrade.equals("B"))
19 numericGrade = 3.0;
20 else if (letterGrade.equals("C"))
21 numericGrade = 2.0;
22 else if (letterGrade.equals("D"))
23 numericGrade = 1.0;
24 else
25 numericGrade = 0.0;
26 System.out.println(letterGrade+" is equivalent to
"+numericGrade);
27 }
28 }
3.3.3 Exercises
range grade
80-100 A
70-79 B
60-69 C
50-59 D
0-49 F
Given a mark, its a simple matter to determine which range it falls into
and determining the corresponding grade. Write a program which obtains
a numeric value and translates that into a letter grade. Consider using
statements of the form:
Relational operators
operator meaning example
< less than count < 100
> greater than netPay > 100
<= less than or equal to netPay <= grossPay
>= greater than or equal to number >= 0
Equality operators
operator meaning example
== equal to netPay == grossPay
!= not equal to netPay != grossPay
Logical expressions can be combined using boolean operators which are &&, ||,
and !:
Boolean operators
operator meaning example
&& AND count > 0 && count < 100
|| OR netPay > 100 || grossPay > 150
! NOT ! (number >= 0)
Truth tables
The values produced by the boolean operators can be illustrated using truth
tables. A truth table shows all possible combinations of operand(s) and the
result of an operation for each combination.
&& is true only when both operands are true:
AND
operand-1 operand-2 result
true true true
true false false
false true false
false false false
OR
operand-1 operand-2 result
true true true
true false true
false true true
false false false
NOT
operand result
true false
false true
Operator priority
The table below shows the priorities from highest to lowest for the arithmetic,
logical, and boolean operators.
Order of Evaluation
Highest to Lowest
sub-expressions ( ...)
autoincrement/decrement ++, − −
unary -, !
arithmetic * /
arithmetic + - (including string catenation)
assignment =
relational < > <= <=
equality == !=
boolean &&
boolean ||
3.7.1 Examples
In the following consider that x and y are ints and are both equal to 100 for
each example.
Example 1
Consider
Example 2
Consider
x++ > 100 && y++ <= 101
Example 3
Consider
x + y > 150 && y = 100
The arithmetic operations are performed first followed by the relational opera-
tions and so the above is equivalent to
false && true
which evaluates to false. However, in a case like this where two expressions are
ANDed, the JVM would evaluate the first operand of && and since that is false
the JVM would not evaluate a second operand since a false ANDed to anything
yields false. Similarly the JVM does not evaluate the second operand for ||
when the first operand is true.
Example 4
Consider that
boolean found = true
and we have the expression
which evaluates to false. Again, the JVM would not evaluate the second operand
of && since the first operand is false.
50 CHAPTER 3. CONTROL STRUCTURES
Bibliography
[1] http://publications.gc.ca/gazette/archives/p1/2007/2007-03-24/pdf/g1-
14112.pdf.
[2] http://www.acm.org/press-room/news-releases/2013/fellows-2013.
[3] http://www.ieee.org/documents/vonn eumannr l.pdf.
51