Download lecture3

Document related concepts
no text concepts found
Transcript
Programming Fundamentals I (COSC1336),
Lecture 3 (prepared after Chapter 3 of
Liang’s 2011 textbook)
Stefan Andrei
5/24/2017
COSC-1336, Lecture 3
1
Overview of Previous Lecture









To write Java programs to perform simple calculations
(§2.2).
To obtain input from the console using the Scanner class
(§2.3).
To use identifiers to name variables, constants, methods,
and classes (§2.4).
To use variables to store data (§§2.5-2.6).
To program with assignment statements and assignment
expressions (§2.6).
To use constants to store permanent data (§2.7).
To declare Java primitive data types: byte, short, int,
long, float, double, and char (§§2.8.1).
To use Java operators to write numeric expressions
(§§2.8.2–2.8.3).
To display current time (§2.9).
5/24/2017
COSC-1336, Lecture 3
2
Overview of Previous Lecture (cont)









To use short hand operators (§2.10).
To cast value of one type to another type (§2.11).
To compute loan payment (§2.12).
To represent characters using the char type (§2.13).
To compute monetary changes (§2.14).
To represent a string using the String type (§2.15).
To become familiar with Java documentation,
programming style, and naming conventions
(§2.16).
To distinguish syntax errors, runtime errors, and
logic errors and debug errors (§2.17).
(GUI) To obtain input using the JOptionPane input
dialog boxes (§2.18).
5/24/2017
COSC-1336, Lecture 3
3
Motivation of the current lecture


In the preceding chapter, you learned how to
solve practical problems programmatically,
namely Java primitive data types and related
subjects, such as variables, constants, data
types, operators, expressions, and input and
output.
Considering the Java program that obtains
hours and minutes from seconds (calculating time
and display it), the number of seconds read from
the input has to be positive – hence selected.
5/24/2017
COSC-1336, Lecture 3
4
Overview of This Lecture
declare boolean type and write Boolean expressions using
comparison operators (§3.2).
 To program AdditionQuiz using Boolean expressions (§3.3).
 To implement selection control using one-way if statements
(§3.4)
 To program the GuessBirthday game using one-way if
statements (§3.5).
 To implement selection control using two-way if statements
(§3.6).
 To implement selection control using nested if statements (§3.7).
 To avoid common errors in if statements (§3.8).
 To
 To
program using selection statements for a variety of examples
(BMI, ComputeTax, SubtractionQuiz) (§3.9-3.11).
5/24/2017
COSC-1336, Lecture 3
5
Overview of This Lecture (cont.)
combine conditions using logical operators (&&, ||, and !)
(§3.12).
To program using selection statements with combined
conditions (LeapYear, Lottery) (§§3.13-3.14).
 To implement selection control using switch statements (§3.15).
To write expressions using the conditional operator (§3.16).
To format output using the System.out.printf() method and
to format strings using the String.format() method (§3.17).
To examine the rules governing operator precedence and
associativity (§3.18).
(GUI) To get user confirmation using confirmation dialogs
(§3.19).
To
5/24/2017
COSC-1336, Lecture 3
6
The boolean Type and Operators
Often in a program you need to compare two
values, such as whether i is greater than j.
 Java provides six comparison operators (also
known as relational operators) that can be used
to compare two values.
 The result of the comparison is a Boolean
value: true or false.

boolean b = (1 > 2);
5/24/2017
COSC-1336, Lecture 3
7
Comparison Operators
Operator Name
<
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
==
equal to
!=
not equal to
5/24/2017
COSC-1336, Lecture 3
8
Problem: A Simple Math Learning Tool
 This example creates a program to let a first
grader practice additions.
 The program randomly generates two single-digit
integers number1 and number2 and displays a
question such as “What is 7 + 9?” to the student.
 After the student types the answer, the program
displays a message to indicate whether the answer
is true or false.
5/24/2017
COSC-1336, Lecture 3
9
AdditionQuiz.java
import java.util.Scanner;
public class AdditionQuiz {
public static void main(String[] args) {
int number1 = (int)(System.currentTimeMillis() % 10);
int number2 = (int)(System.currentTimeMillis() / 7 % 10);
Scanner input = new Scanner(System.in);
System.out.print("What is " + number1 + " + " +
number2 + "? ");
int answer = input.nextInt();
System.out.println(number1 + " + " + number2 + " = " +
answer + " is " + (number1 + number2 == answer));
}
}
5/24/2017
COSC-1336, Lecture 3
10
Compiling and running
AdditionQuiz.java
5/24/2017
COSC-1336, Lecture 3
11
One-way if Statements
if (boolean-expression) { if (radius >= 0) {
area = radius * radius * PI;
statement(s);
System.out.println("The area for the "
}
+ " circle of radius " + radius + " is " +
area);
}
Boolean
Expression
false
false
(radius >= 0)
true
true
Statement(s)
area = radius * radius * PI;
System.out.println("The area for the circle of " +
"radius " + radius + " is " + area);
(A)
5/24/2017
(B)
COSC-1336, Lecture 3
12
Note
if i > 0 {
System.out.println("i is positive");
}
if (i > 0) {
System.out.println("i is positive");
}
(a) Wrong
(b) Correct
if (i > 0) {
System.out.println("i is positive");
}
Equivalent
if (i > 0)
System.out.println("i is positive");
(b)
(a)
 It’s like: “buildings with one level don’t need elevators”.
 Similarly, the if statements with just one statement don’t
need to embed that single statement into a block of
statements (surrounded by { and }).
5/24/2017
COSC-1336, Lecture 3
13
Simple if Demo
 Write a program that prompts the user to enter an integer.
 If the number is a multiple of 5, print HiFive.
 If the number is divisible by 2, print HiEven.
5/24/2017
COSC-1336, Lecture 3
14
SimpleIfDemo.java
import java.util.Scanner;
public class SimpleIfDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = input.nextInt();
if (number % 5 == 0) System.out.println("HiFive");
if (number % 2 == 0) System.out.println("HiEven");
}
}
5/24/2017
COSC-1336, Lecture 3
15
Compiling and running
SimpleIfDemo.java
5/24/2017
COSC-1336, Lecture 3
16
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
true
Boolean
Expression
Statement(s) for the false case
Statement(s) for the true case
5/24/2017
false
COSC-1336, Lecture 3
17
if...else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
System.out.println("The area for the "
+ "circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}
5/24/2017
COSC-1336, Lecture 3
18
Multiple Alternative if Statements
if (score >= 90.0)
grade = 'A';
else
if (score >= 80.0)
grade = 'B';
else
if (score >= 70.0)
grade = 'C';
else
if (score >= 60.0)
grade = 'D';
else
grade = 'F';
5/24/2017
Equivalent
COSC-1336, Lecture 3
if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';
19
Trace if-else statement
Suppose score is 70.0
The condition is false
if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';
5/24/2017
COSC-1336, Lecture 3
20
Trace if-else statement
Suppose score is 70.0
The condition is false
if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';
5/24/2017
COSC-1336, Lecture 3
21
Trace if-else statement
Suppose score is 70.0
The condition is true
if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';
5/24/2017
COSC-1336, Lecture 3
22
Trace if-else statement
Suppose score is 70.0
grade is C
if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';
5/24/2017
COSC-1336, Lecture 3
23
Trace if-else statement
Suppose score is 70.0
Exit the if statement
if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';
5/24/2017
COSC-1336, Lecture 3
24
Note
The else clause matches the most recent if
clause in the same block.

int i = 1;
int j = 2;
int k = 3;
int i = 1;
int j = 2;
int k = 3;
Equivalent
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
(a)
5/24/2017
(b)
COSC-1336, Lecture 3
25
Note (cont.)
Nothing is printed from the preceding statement.
 To force the else clause to match the first if
clause, you must add a pair of braces:

int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");

This statement prints B.
5/24/2017
COSC-1336, Lecture 3
26
Common Errors
Adding a semicolon at the end of an if clause is a common
mistake.

if (radius >= 0);
Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation
error or a runtime error, it is a logic error.
 This error often occurs when you use the next-line block
style.

5/24/2017
COSC-1336, Lecture 3
27
TIP
if (number % 2 == 0)
even = true;
else
even = false;
Equivalent
(b)
(a)
5/24/2017
boolean even
= number % 2 == 0;
COSC-1336, Lecture 3
28
CAUTION
if (even == true)
System.out.println(
"It is even.");
Equivalent
(b)
(a)
5/24/2017
if (even)
System.out.println(
"It is even.");
COSC-1336, Lecture 3
29
Problem: Body Mass Index



Body Mass Index (BMI) is a measure of health on
weight.
It can be calculated by taking your weight in kilograms
and dividing by the square of your height in meters.
The interpretation of BMI for people 16 years or older
is as follows:
BMI
below 16
16-18
18-24
24-29
29-35
above 35
5/24/2017
Interpretation
serious underweight
underweight
normal weight
overweight
seriously overweight
gravely overweight
COSC-1336, Lecture 3
30
ComputeBMI.java
import java.util.Scanner;
public class ComputeBMI {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter weight in pounds
System.out.print("Enter weight in pounds: ");
double weight = input.nextDouble();
// Prompt the user to enter height in inches
System.out.print("Enter height in inches: ");
double height = input.nextDouble();
5/24/2017
COSC-1336, Lecture 3
31
ComputeBMI.java
(cont.)
final double KILOGRAMS_PER_POUND = 0.45359237;
// Constant
final double METERS_PER_INCH = 0.0254;
// Constant
// Compute BMI
double weightInKilogram = weight *
KILOGRAMS_PER_POUND;
double heightInMeters = height *
METERS_PER_INCH;
double bmi = weightInKilogram /
(heightInMeters * heightInMeters);
// Display result
System.out.printf("Your BMI is %5.2f\n", bmi);
5/24/2017
COSC-1336, Lecture 3
32
ComputeBMI.java
(cont.)
if (bmi < 16)
System.out.println("You are seriously underweight");
else if (bmi < 18)
System.out.println("You are underweight");
else if (bmi < 24)
System.out.println("You are normal weight");
else if (bmi < 29)
System.out.println("You are overweight");
else if (bmi < 35)
System.out.println("You are seriously overweight");
else System.out.println("You are gravely overweight");
}
}
5/24/2017
COSC-1336, Lecture 3
33
Running ComputeBMI.java
5/24/2017
COSC-1336, Lecture 3
34
Problem: An Improved Math Learning
Tool
This example creates a program to teach a first grade
child how to learn subtractions.
 The program randomly generates two single-digit
integers number1 and number2 with number1 > number2
and displays a question such as “What is 9 – 2?” to
the student.
 After the student types the answer in the input dialog
box, the program indicates if the answer is correct.
 The method Math.random() generates a double
number from interval [0,1).

5/24/2017
COSC-1336, Lecture 3
35
SubtractionQuiz.java
import java.util.Scanner;
public class SubtractionQuiz {
public static void main(String[] args) {
// 1.Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
// 2.If number1 < number2, swap number1 with number2
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
5/24/2017
COSC-1336, Lecture 3
36
SubtractionQuiz.java
(cont.)
// 3.Prompt the answer “what is number1 – number2?”
System.out.print("What is " + number1 + " - " +
number2 + "? ");
Scanner input = new Scanner(System.in);
int answer = input.nextInt();
// 4.Grade the answer and display the result
if (number1 - number2 == answer)
System.out.println("You are correct!");
else
System.out.println("Your answer is wrong.\n" +
number1 + " - " + number2 + " should be " +
(number1 - number2));
}
}
5/24/2017
COSC-1336, Lecture 3
37
Compiling and running
SubtractionQuiz.java
5/24/2017
COSC-1336, Lecture 3
38
Logical Operators
Operator Name
!
not
&&
and
||
or
^
exclusive or
5/24/2017
COSC-1336, Lecture 3
39
Truth Table for Operator !
p
!p
Example (assume age = 24, gender = 'M')
true
false
!(age > 18) is false, because (age > 18) is true.
false
true
!(gender != 'F') is true, because (grade != 'F') is false.
5/24/2017
COSC-1336, Lecture 3
40
Truth Table for Operator &&
p1
p2
p1 && p2
Example (assume age = 24, gender = 'F')
false
false
false
false
true
false
(age > 18) && (gender == 'F') is true, because (age
> 18) and (gender == 'F') are both true.
true
false
false
true
true
true
5/24/2017
(age > 18) && (gender != 'F') is false, because
(gender != 'F') is false.
COSC-1336, Lecture 3
41
Truth Table for Operator ||
p1
p2
p1 || p2
Example (assume age = 24, gender = 'F')
false
false
false
false
true
true
(age > 34) || (gender == 'F') is true, because (gender
== 'F') is true.
true
false
true
true
true
true
5/24/2017
(age > 34) || (gender == 'M') is false, because (age >
34) and (gender == 'M') are both false.
COSC-1336, Lecture 3
42
Truth Table for Operator ^
p1
p2
p1 ^ p2
Example (assume age = 24, gender = 'F')
false
false
false
false
true
true
(age > 34) ^ (gender == 'F') is true, because (age
> 34) is false but (gender == 'F') is true.
true
false
true
true
true
false



(age > 34) || (gender == 'M') is false, because (age
> 34) and (gender == 'M') are both false.
Given A and B two Boolean variables, A ^ B means
“exclusive or”.
That is, very similar with the || operator, except their
values cannot be equal.
Hence A ^ B is true if and only if A and B have different
values.
5/24/2017
COSC-1336, Lecture 3
43
Summary of truth tables for Java
Boolean operators
A
false
true
false
true
5/24/2017
B
false
false
true
true
A || B
false
true
true
true
A && B
false
false
false
true
COSC-1336, Lecture 3
A ^ B
false
true
true
false
!A
true
false
true
false
44
Example
 Here is a program that checks whether a number is
divisible by 2 and 3, whether a number is divisible by
2 or 3, and whether a number is divisible by 2 or 3,
but not both.
5/24/2017
COSC-1336, Lecture 3
45
TestBooleanOperators.java
import java.util.Scanner;
public class TestBooleanOperators {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("Is " + number + " divisible by 2 and 3? "
+ ((number % 2 == 0) && (number % 3 == 0)));
System.out.println("Is " + number + " divisible by 2 or 3? "
+ ((number % 2 == 0) || (number % 3 == 0)));
System.out.println("Is " + number +
" divisible by 2 or 3, but not both? " +
((number % 2 == 0) ^ (number % 3 == 0)));
}
}
5/24/2017
COSC-1336, Lecture 3
46
Compiling and running
TestBooleanOperators.java
5/24/2017
COSC-1336, Lecture 3
47
The bitwise AND "&" operator




Returns 1 if any of the two bits is 1 and it
returns 0 if any of the bits is 0.
5 has the binary representation:

00000101
6
has the binary representation:

00000110
5 & 6


5/24/2017
has the binary representation:
00000100,
which means 4.
COSC-1336, Lecture 3
48
Example of using the ‘&’ operator








int x = 3 & 3;
int y = 4 & 6;
int z = 5 & 6;
How much are x , y, and z?
Hint: use the binary representations of 3, 4, 5, 6.
x = 3,
y = 4,
z = 4.
5/24/2017
COSC-1336, Lecture 3
49
The bitwise OR “|" operator




Returns 0 if both of the two bits are 0 and it
returns 1 if any of the bits is 1.
5 has the binary representation:

00000101
6
has the binary representation:

00000110
5 | 6


5/24/2017
has the binary representation:
00000111,
which means 7.
COSC-1336, Lecture 3
50
Example of using the ‘|’ operator








int x = 3 | 3;
int y = 4 | 6;
int z = 5 | 6;
How much are x , y, and z?
Hint: use the binary representations of 3, 4, 5, 6.
x = 3,
y = 6,
z = 7.
5/24/2017
COSC-1336, Lecture 3
51
switch
Statement Rules
The switch-expression
must yield a value of
char, byte, short, or int
type and must always
be enclosed in
parentheses.
The value1, ..., and valueN must
have the same data type as the
value of the switch-expression.
The resulting statements in the
case statement are executed
when the value in the case
statement matches the value of
the switch-expression. Note that
value1, ..., and valueN are
constant expressions, meaning
that they cannot contain
variables in the expression, such
as 1 + x.
5/24/2017
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-fordefault;
}
COSC-1336, Lecture 3
52
switch
Statement Rules
The keyword break is optional,
but it should be used at the
end of each case in order to
terminate the remainder of the
switch statement. If the break
statement is not present, the
next case statement will be
executed.
The default case, which is
optional, can be used to
perform actions when none of
the specified cases matches
the switch-expression.
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-fordefault;
}
The case statements are executed in sequential order, but the
order of the cases (including the default case) does not matter.
However, it is good programming style to follow the logical
sequence of the cases and place the default case at the end.
5/24/2017
COSC-1336, Lecture 3
53
animation
Trace switch statement
Suppose ch is 'a':
switch
case
case
case
}
5/24/2017
(ch)
'a':
'b':
'c':
{
System.out.println(ch);
System.out.println(ch);
System.out.println(ch);
COSC-1336, Lecture 3
54
animation
Trace switch statement
ch is 'a':
switch
case
case
case
}
5/24/2017
(ch)
'a':
'b':
'c':
{
System.out.println(ch);
System.out.println(ch);
System.out.println(ch);
COSC-1336, Lecture 3
55
animation
Trace switch statement
Execute this line
switch
case
case
case
}
5/24/2017
(ch)
'a':
'b':
'c':
{
System.out.println(ch);
System.out.println(ch);
System.out.println(ch);
COSC-1336, Lecture 3
56
animation
Trace switch statement
Execute this line
switch
case
case
case
}
5/24/2017
(ch)
'a':
'b':
'c':
{
System.out.println(ch);
System.out.println(ch);
System.out.println(ch);
COSC-1336, Lecture 3
57
animation
Trace switch statement
Execute this line
switch
case
case
case
}
5/24/2017
(ch)
'a':
'b':
'c':
{
System.out.println(ch);
System.out.println(ch);
System.out.println(ch);
COSC-1336, Lecture 3
58
animation
Trace switch statement
Execute next statement
switch
case
case
case
}
(ch)
'a':
'b':
'c':
{
System.out.println(ch);
System.out.println(ch);
System.out.println(ch);
Next statement;
5/24/2017
COSC-1336, Lecture 3
59
animation
Trace switch statement
Suppose ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
5/24/2017
COSC-1336, Lecture 3
60
animation
Trace switch statement
ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
5/24/2017
COSC-1336, Lecture 3
61
animation
Trace switch statement
Execute this line
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
5/24/2017
COSC-1336, Lecture 3
62
animation
Trace switch statement
Execute this line
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
5/24/2017
COSC-1336, Lecture 3
63
animation
Trace switch statement
Execute next
statement
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
Next statement;
5/24/2017
COSC-1336, Lecture 3
64
The Conditional (ternary) Operator
if (x > 0)
y = 1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;


Syntax: (boolean-expression) ? expression1 :
expression2
Semantics: if boolean-expression evaluates to
true, then the value of expression1 is returned,
otherwise the value of expression2.
5/24/2017
COSC-1336, Lecture 3
65
The Conditional Operator
if (num % 2 == 0)
System.out.println(num + "is even");
else
System.out.println(num + "is odd");
System.out.println(
(num % 2 == 0)?
num + "is even" :
num + "is odd"
);
5/24/2017
COSC-1336, Lecture 3
66
Formatting Output
 Use the printf() method call:
System.out.printf(format, items);
 where format is a String that may consist of
substrings and format specifiers.
 A format specifier specifies how an item should be
displayed.
 An item may be a numeric value, character, boolean
value, or a String.
 Each specifier begins with a percent sign.
5/24/2017
COSC-1336, Lecture 3
67
Frequently-Used Specifiers
Specifier Output
Example
%b
true or false
a boolean value
%c
a character
'a'
%d
a decimal integer
200
%f
a floating-point number
45.460000
%e
a number in standard scientific notation
%s
a string
4.556000e+01
"Java is cool"
int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
display
5/24/2017
count is 5 and amount is 45.560000
COSC-1336, Lecture 3
68
Operator Precedence












var++, var-+, - (Unary plus and minus), ++var,--var
(type) Casting
! (Not)
*, /, % (Multiplication, division, and remainder)
+, - (Binary addition and subtraction)
<, <=, >, >= (Comparison)
==, !=; (Equality)
^ (Exclusive OR)
&& (Conditional AND) Short-circuit AND
|| (Conditional OR) Short-circuit OR
=, +=, -=, *=, /=, %= (Assignment operator)
5/24/2017
COSC-1336, Lecture 3
69
Operator Precedence and Associativity
The expression in the parentheses is evaluated first
(Parentheses can be nested, in which case the
expression in the inner parentheses is executed first).
 When evaluating an expression without parentheses,
the operators are applied according to the precedence
rule and the associativity rule.
 If operators with the same precedence are next to
each other, their associativity determines the order of
evaluation.
 All binary operators except assignment operators are
left-associative.

5/24/2017
COSC-1336, Lecture 3
70
Operator Associativity






When two operators with the same precedence are
evaluated, the associativity of the operators determines the
order of evaluation.
All binary operators except assignment operators are leftassociative.
a–b+c–d
is equivalent to:
((a – b) + c) – d
Assignment operators are right-associative.
Therefore, the expression:
a = b += c = 5
is equivalent to:
a = (b += (c = 5))
5/24/2017
COSC-1336, Lecture 3
71
Example

Applying the operator precedence and
associativity rule, the expression
3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows:
3 + 4 * 4 > 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 > 5 * 7 – 1
(2) multiplication
3 + 16 > 5 * 7 – 1
(3) multiplication
3 + 16 > 35 – 1
(4) addition
19 > 35 – 1
(5) subtraction
19 > 34
(6) greater than
false
5/24/2017
COSC-1336, Lecture 3
72
Summary
declare boolean type and write Boolean expressions using
comparison operators (§3.2).
 To program AdditionQuiz using Boolean expressions (§3.3).
 To implement selection control using one-way if statements
(§3.4)
 To program the GuessBirthday game using one-way if
statements (§3.5).
 To implement selection control using two-way if statements
(§3.6).
 To implement selection control using nested if statements (§3.7).
 To avoid common errors in if statements (§3.8).
 To
 To
program using selection statements for a variety of examples
(BMI, ComputeTax, SubtractionQuiz) (§3.9-3.11).
5/24/2017
COSC-1336, Lecture 3
73
Summary (cont.)
combine conditions using logical operators (&&, ||, and !)
(§3.12).
To program using selection statements with combined
conditions (LeapYear, Lottery) (§§3.13-3.14).
 To implement selection control using switch statements (§3.15).
To write expressions using the conditional operator (§3.16).
To format output using the System.out.printf() method and
to format strings using the String.format() method (§3.17).
To examine the rules governing operator precedence and
associativity (§3.18).
(GUI) To get user confirmation using confirmation dialogs
(§3.19).
To
5/24/2017
COSC-1336, Lecture 3
74
Reading suggestions

From [Liang: Introduction to Java programming:
Eight Edition, 2011 Pearson Education,
0132130807]
 Chapter 3 (Selections)
5/24/2017
COSC-1336, Lecture 3
75
Coming up next

From [Liang: Introduction to Java
programming: Eight Edition, 2011 Pearson
Education, 0132130807]

5/24/2017
Chapter 4 (Loops)
COSC-1336, Lecture 3
76
Thank you for your attention!
Questions?
5/24/2017
COSC-1336, Lecture 3
77