Chapter 3 - Selections
Chapter 3 - 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.
• 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 (radius >= 0) {
}
• 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.
if (radius >= 0) {
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)
else
if (i > k) {
if (j > k)
else
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.
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.
|| or logical disjunction
true false !(age > 18) is false, because (age > 18) is true.
Result is false.
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;
// Create a Scanner
// Receive an input
if (number % 2 == 0 || number % 3 == 0)
if (number % 2 == 0 ^ number % 3 == 0)
}
Caution
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
!condition1 || !condition2
(number % 2 != 0 || number % 3 != 0)
As another example,
!(number == 2 || number == 3)
is better written as
(x != 0) || (x == 0) Result is true
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
case 1:
case 2:
case 3:
case 4:
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.
• 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: