0% found this document useful (0 votes)
30 views

Chapter 3 - Selections

This document discusses selection statements and conditional logic in Java. It introduces if, if-else, and nested if statements. It describes the boolean data type and relational operators that can be used to create conditions. Logical operators like &&, ||, and ! are also covered, along with their truth tables. Random number generation and example subtraction quiz code is provided to demonstrate if/else statements.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Chapter 3 - Selections

This document discusses selection statements and conditional logic in Java. It introduces if, if-else, and nested if statements. It describes the boolean data type and relational operators that can be used to create conditions. Logical operators like &&, ||, and ! are also covered, along with their truth tables. Random number generation and example subtraction quiz code is provided to demonstrate if/else statements.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Selections

3.1 Introduction
The program can decide which statements to execute based on a
condition.

if (radius < 0) {
System.out.println("Incorrect input");
}
else {
area = radius * radius * 3.14159;
System.out.println("Area is " + area);
}
• Selection statements use conditions that are
Boolean expressions. A Boolean expression is an
expression that evaluates to a Boolean value: true or
false. We now introduce Boolean types and
relational operators.
3.2 boolean Data Type

The boolean data type declares a variable with the value either
true or false.

• How do you compare two values, such as whether a radius is


greater than 0, equal to 0, or less than 0? Java provides six
relational operators (also known as comparison operators), shown
in Table 3.1, which can be used to compare two values (assume
radius is 5 in the table).
TABLE 3.1 Relational Operators
Java Operator Mathematics Name Example(radiu Result
Symbol s is 5)
< < Less than radius < 0 false

<= ≤ Less than or equal radius <= 0 false


to

> > Greater than radius > 0 true

>= ≥ Greater than or radius >= 0 true


equal to

== = Equal to radius == 0 false

!= ≠ Not equal to radius != 0 true


Caution
• The equality testing operator is two equal signs (==), not
a single equal sign (=). The latter symbol is for
assignment.
• The result of the comparison is a Boolean value: true or false.
For example, the following statement displays true:
double radius = 1;
System.out.println(radius > 0);
• A variable that holds a Boolean value is known as a Boolean
variable. The boolean data type is used to declare Boolean
variables. A boolean variable can hold one of the two values:
true or false.
Assuming that x is 1, show the result of the
following Boolean expressions:
(x > 0)
(x < 0)
(x != 0)
(x >= 0)
(x != 1)
if Statements
• An if statement is a construct that enables a program to specify alternative paths of
execution.

• Java has several types of selection statements: one-way if statements, two-way if-
else statements, nested if statements, multi-way if-else statements, switch
statements, and conditional expressions.

• A one-way if statement executes an action if and only if the condition is true. The
syntax for a one-way if statement is:
if (boolean-expression) {
statement(s);
• An if statement executes statements if the boolean-expression evaluates to true.

• If the boolean-expression evaluates to true, the statements in the block are


executed.

As an example, see the following code:

if (radius >= 0) {

area = radius * radius * PI;

System.out.println("The area for the circle of radius " +

radius + " is " + area);

}
• This program that prompts the user to enter an integer. If the
number is a multiple of 5, the program displays HiFive. If the
number is divisible by 2, it displays HiEven.
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");
}
Two-Way if-else Statements
• An if-else statement decides the execution path based on whether the
condition is true or false.

• A one-way if statement performs an action if the specified condition is


true. If the condition is false, nothing is done. But what if you want to
take alternative actions when the condition is false? You can use a two-
way if-else statement. The actions that a two-way if-else statement
specifies differ based on whether the condition is true or false.
Here is the syntax for a two-way if-else statement:
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
For example, consider the following code:

if (radius >= 0) {

area = radius * radius * PI;

System.out.println("The area for the circle of radius " + radius + " is " + area);

else {

System.out.println("Negative input");

}
• Here is another example of using the if-else statement. The
example checks whether a number is even or odd, as follows:

if (number % 2 == 0)

System.out.println(number + " is even.");

else

System.out.println(number + " is odd.");


Nested if and Multi-Way if-else Statements
• An if statement can be inside another if statement to form a nested if
statement.

• The statement in an if or if-else statement can be any legal Java


statement, including another if or if-else statement. The inner if
statement is said to be nested inside the outer if statement. The inner
if statement can contain another if statement; in fact, there is no limit
to the depth of the nesting.
• For example, the following is a nested if statement:

if (i > k) {

if (j > k)

System.out.println("i and j are greater than k");

else

System.out.println("i is less than or equal to k");


• prints a letter grade according to the score, with multiple alternatives.
• Suppose x = 3 and y = 2; show the output, if any, of the
following code. What is the output if x = 3 and y = 4? What is
the output if x = 2 and y = 2? Draw a flowchart of the code.
if (x > 2) {
if (y > 2) {
z = x + y;
System.out.println("z is " + z);
}
}
else
System.out.println("x is " + x);
• Suppose x = 2 and y = 3. Show the output, if any, of the following code.
What is the output if x = 3 and y = 2? What is the output if x = 3 and
y = 3?

if (x > 2)
if (y > 2) {
int z = x + y;
System.out.println("z is " + z);
}
else
System.out.println("x is " + x);
Generating Random Numbers
• You can use Math.random() to obtain a random double value between 0.0
and 1.0, excluding 1.0.

The program can work as follows:

1. Generate two single-digit integers into number1 and number2.

2. If number1 < number2, swap number1 with number2.

3. Prompt the student to answer, "What is number1 – number2?"

4. Check the student’s answer and display whether the answer is correct.
SubtractionQuiz.java
1 import java.util.Scanner;
2
3 public class SubtractionQuiz {
4 public static void main(String[] args) {
5 // 1. Generate two random single-digit integers
6 int number1 = (int)(Math.random() * 10);
7 int number2 = (int)(Math.random() * 10);
8
9 // 2. If number1 < number2, swap number1 with number2
10 if (number1 < number2) {
11 int temp = number1;
12 number1 = number2;
13 number2 = temp;
15
16 // 3. Prompt the student to answer ”What is number1 – number2?”
17 System.out.print ("What is " + number1 + " - " + number2 + "? ");
18 Scanner input = new Scanner(System.in);
19 int answer = input.nextInt();
20
21 // 4. Grade the answer and display the result
22 if (number1 - number2 == answer)
23 System.out.println("You are correct!");
24 else {
25 System.out.println("Your answer is wrong.");
26 System.out.println(number1 + " - " + number2 +
27 " should be " + (number1 - number2));
28 }
29 }
Logical Operators
• The logical operators !, &&, ||, and ^ can be used to create a
compound Boolean expression.

• Sometimes, whether a statement is executed is determined by a


combination of several conditions. You can use logical operators to
combine these conditions to form a compound Boolean expression.
Logical operators, also known as Boolean operators, operate on
Boolean values to create a new Boolean value.
Boolean Operators
Operator Name Description

! not logical negation

&& and logical conjunction

|| or logical disjunction

^ exclusive or logical exclusion


Truth Table for Operator !
p !p Example (assume age = 24, weight = 140)

true false !(age > 18) is false, because (age > 18) is true.
Result is false.

false true !(weight == 150) is true, because (weight == 150) is false.


Result is true.
Truth Table for Operator &&
p1 p2 p1 && p2 Example (assume age = 24, weight = 140)

false false false (age > 28) && (weight < 100) is false, because (age > 28) and (weight >100) are both false.
Result is false.

false true false (age > 28) && (weight <= 140) is true, because (age > 28) is false.
Result is false.

true false false (age > 18) && (weight >= 150) is false, because (age > 18) is false.
Result is false

true true true (age > 18) && (weight >= 140) is true, because (age > 18) and (weight >= 140) are both true.
Result is true.
Truth Table for Operator ||
p1 p2 p1 || p2 Example (assume age = 24, weight = 140)

false false false (age > 34) || (weight >= 150) is false, because (age > 34) and (weight >= 150) are both false.
Result is false.

false true true (age > 28) || (weight <= 140) is true, because (age > 28) is false but (weight <= 140) is true.
Result is true.

true false true (age > 18) || (weight < 140) is true, because (age > 18) is true.
Result is true.

true true true (age > 14) || (weight >= 140) is true, because (age > 14) and (weight >= 140) are both true.
Result is true.
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140)

false false false (age > 34) ^ (weight > 140) is false, because (age > 34) and (weight > 140) are both false.
Result is false.

false true true (age > 34) ^ (weight >= 140) is true, because (age > 34) is false but (weight >= 140) is true.
Result is true.

true false true (age > 14) ^ (weight >140) is false, because (age > 14) is true but (weight >= 140) is false.
Result is true

true true false (age > 14) ^ (weight > 130) is true, because (age > 14) and (weight > 130) are both true.
Result is false
• This program checks whether a number is divisible by 2 and 3, by 2 or 3, and by 2
or 3 but not both:
TestBooleanOperators.java

import java.util.Scanner;

public class TestBooleanOperators {

public static void main(String[] args) {

// Create a Scanner

Scanner input = new Scanner(System.in);

// Receive an input

System.out.print("Enter an integer: ");


int number = input.nextInt();

if (number % 2 == 0 && number % 3 == 0)

System.out.println(number + " is divisible by 2 and 3.");

if (number % 2 == 0 || number % 3 == 0)

System.out.println(number + " is divisible by 2 or 3.");

if (number % 2 == 0 ^ number % 3 == 0)

System.out.println(number + " is divisible by 2 or 3, but not both.");

}
Caution

In mathematics, the expression

1 <= numberOfDaysInAMonth <= 31

is correct. However, it is incorrect in Java, because 1 <= numberOfDaysInAMonth is

evaluated to a boolean value, which cannot be compared with 31. Here, two
operands (a boolean value and a numeric value) are incompatible. The correct
expression in Java is

(1 <= numberOfDaysInAMonth) && (numberOfDaysInAMonth <= 31)


Note

De Morgan’s law, named after Indian-born British mathematician and logician


Augustus De Morgan (1806–1871), can be used to simplify Boolean
expressions. The law states:

!(condition1 && condition2) is the same as

!condition1 || !condition2

!(condition1 || condition2) is the same as

!condition1 && !condition2


For example,

! (number % 2 == 0 && number % 3 == 0)

can be simplified using an equivalent expression:

(number % 2 != 0 || number % 3 != 0)

As another example,

!(number == 2 || number == 3)

is better written as

number != 2 && number != 3


• If one of the operands of an && operator is false, the expression is
false; if one of the operands of an || operator is true, the expression is
true. Java uses these properties to improve the performance of these
operators. When evaluating p1 && p2, Java first evaluates p1 and then,
if p1 is true, evaluates p2; if p1 is false, it does not evaluate p2. When
evaluating p1 || p2, Java first evaluates p1 and then, if p1 is false,
evaluates p2; if p1 is true, it does not evaluate p2. In programming
language terminology, && and || are known as the short-circuit or lazy
operators.
• Assuming that x is 1, show the result of the following Boolean expressions.

(true) && (3 > 4) Result is false

!(x > 0) && (x > 0) Result is false

(x > 0) || (x < 0) Result is true

(x != 0) || (x == 0) Result is true

(x >= 0) || (x < 0) Result is true

(x != 1) == !(x == 1) Result is true


• Suppose, when you run the following program, you enter the input 2 3 6 from the
console. What is the output?
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
System.out.println("(x < y && y < z) is " + (x < y && y < z));
System.out.println("(x < y || y < z) is " + (x < y || y < z));
System.out.println("!(x < y) is " + !(x < y));
System.out.println("(x + y < z) is " + (x + y < z));
System.out.println("(x + y > z) is " + (x + y > z));
}
Case Study: Determining Leap Year
• A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400.
• You can use the following Boolean expressions to check whether a year is a leap
year:
// A leap year is divisible by 4
boolean isLeapYear = (year % 4 == 0);
// A leap year is divisible by 4 but not by 100
isLeapYear = isLeapYear && (year % 100 != 0);
// A leap year is divisible by 4 but not by 100 or divisible by 400
isLeapYear = isLeapYear || (year % 400 == 0);
Or you can combine all these expressions into one like this:
isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
This program lets the user enter a year and checks whether it is a leap year.
LeapYear.java
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
// Check if the year is a leap year
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
// Display the result
System.out.println(year + " is a leap year? " + isLeapYear);
}
switch Statements
• A switch statement executes statements based on the value of a variable or an
expression.
switch (status) {
case 0: compute tax for single filers;
break;
case 1: compute tax for married jointly or qualifying widow(er);
break;
case 2: compute tax for married filing separately;
break;
case 3: compute tax for head of household;
break;
default: System.out.println("Error: invalid status");
The flowchart of the preceding switch statement

The switch statement checks all cases and executes the statements in the matched case.
• This statement checks to see whether the status matches the value 0, 1, 2, or 3, in
that order. If matched, the corresponding tax is computed; if not matched, a
message is displayed.
Here is the full syntax for the switch statement:

switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
The switch statement observes the following rules:
■ The switch-expression must yield a value of char, byte, short, int, or String
type and must always be enclosed in parentheses. (The char and String types will be
introduced in the next chapter.)
■ The value1, . . ., and valueN must have the same data type as the value of the
switchexpression. Note that value1, . . ., and valueN are constant expressions, meaning
that they cannot contain variables, such as 1 + x.
■ When the value in a case statement matches the value of the switch-expression,
the statements starting from this case are executed until either a break statement or
the
end of the switch statement is reached.
■ The default case, which is optional, can be used to perform actions when none of the
specified cases matches the switch-expression.
■ The keyword break is optional. The break statement immediately ends the switch
Caution

Do not forget to use a break statement when one is needed. Once


a case is matched, the statements starting from the matched case
are executed until a break statement or the end of the switch
statement is reached. This is referred to as fall-through behavior.
For example, the following code displays Weekdays for day of 1 to 5
and Weekends for day 0 and 6.
switch (day) {

case 1:

case 2:

case 3:

case 4:

case 5: System.out.println("Weekday"); break;

case 0:

case 6: System.out.println("Weekend");

}
Conditional Expressions
• A conditional expression evaluates an expression based on a condition.
if (x > 0)
y = 1;
else
y = -1;
• Alternatively, as in the following example, you can use a conditional expression to
achieve the same result.
y = (x > 0) ? 1 : -1;
• Conditional expressions are in a completely different style, with no explicit if
in the statement.

• The syntax is:

boolean-expression ? expression1 : expression2;

• The result of this conditional expression is expression1 if boolean-


expression is true; otherwise the result is expression2.

• Suppose you want to assign the larger number of variable num1 and num2
to max. You can simply write a statement using the conditional expression:

max = (num1 > num2) ? num1 : num2;


• Note
• The symbols ? and : appear together in a conditional expression. They form
a conditional operator and also called a ternary operator because it uses
three operands. It is the only ternary operator in Java.
Operator Precedence and Associativity
• Operator precedence and associativity determine the order in which
operators are evaluated.
• Section 2.11 introduced operator precedence involving arithmetic
operators. This section discusses operator precedence in more detail.
Suppose that you have this expression:
3 + 4 * 4 > 5 * (4 + 3) – 1 && (4 - 3 > 5)
Operator Precedence Chart
Precedence Operator

var++ and var–– (Postfix)


+, – (Unary plus and minus), ++var and ––var (Prefix)
(type) (Casting)
!(Not)
*, /, % (Multiplication, division, and remainder)
+, – (Binary addition and subtraction)
<, <=, >, >= (Relational)
==, != (Equality)
^ (Exclusive OR)
&& (AND)
|| (OR)
=, +=, –=, *=, /=, %= (Assignment operator)
• List the precedence order of the Boolean operators. Evaluate the
following expressions:

true || true && false

true && true || false

The precedence order for boolean operators is !, ^, &&, and ||


true || true && false is true
true && true || false is true

• Evaluate the following expressions:


2 * 2 - 3 > 2 && 4 - 2 > 5 false
2 * 2 - 3 > 2 || 4 - 2 > 5 false

You might also like