1/16
Prof. Moheb Ramzy Girgis
Department of Computer Science Faculty of Science
Minia University
Java Programming
3. Selections
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Introduction
If we enter a negative value for radius in ComputeArea.java, the program would print an invalid result.
So, if the radius is negative, we don't want the program to compute the area.
How can we deal with this situation?
Like all high-level languages, Java provides selection statements that let us choose actions with two or more alternatives.
We can use the following selection statement to prevent computing the area if the radius is negative:
if (radius < 0)
System.out.println("Incorrect input");
else {
area = radius * radius * 3.14159;
System.out.println("Area is " + area);
}
2/16
The Boolean Type and Operators
Selection statements use conditions.
Conditions are Boolean expressions that evaluate to a Boolean value: true or false.
The condition radius < 0 is a Boolean expression that compares radius with 0. It includes a comparison operator <.
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: trueor false. For example, the following statement displays true:
double radius = 1;
System.out.println(radius > 0);
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Comparison Operators
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
The following table shows the comparison operators (assume radius = 5)
A variable that holds a Boolean value is known as a Boolean variable. The booleandata type is used to declare Boolean variables. A boolean variable can hold one of the two
values: trueand false. (Ex: boolean lightsOn = true;)
3/16
One-way if Statements
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
A one-way if statement executes an action if and only if the
condition is true. The syntax for a one-way if statement and its execution flowchart
are shown below:
if (boolean-expression) { statement(s);
}
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area"
+ " for the circle of radius "
+ radius + " is " + area);
}
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
One-way if Statements
The boolean-expression is enclosed in parentheses.
For example, the code in (a) below is wrong. It should be corrected, as shown in (b):
The block braces can be omitted if they enclose a single statement.
For example, the following statements are equivalent:
4/16
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.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
One-way if Statements - Example
// Program 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");
} }
The Two-way if Statement
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
A one-way if statement takes 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 statement.
The actions that a two-way if statement specifies differ based on whether the condition is true or false.
Here is the syntax for a two-way if statement and its corresponding flowchart:
if (boolean-expression) {
statement(s)-for-the-true-case;
} else {
statement(s)-for-the-false-case;
}
5/16
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
The Two-way if Statement
If the boolean-expression evaluates to true, the statement(s) for the true case are executed; otherwise, the statement(s) for the false case are executed.
For example, consider the following code:
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");
}
If radius >= 0 is true, area is computed and displayed; if it is false, the message "Negative input" is printed.
Nested if Statements
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
The statement in an if or if ... else statement can be another if or if ... else statement.
The inner if statement is said to be nested inside the outer if statement.
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");
The if (j > k) statement is nested inside the if (i > k) statement.
6/16
Multiple Alternative if Statements
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
The nested if statement can be used to implement multiple alternatives.
The statement given in Figure (a), for instance, assigns a letter grade to the variable grade according to the score, with multiple alternatives.
A preferred format for multiple alternative if statements is shown in Figure (b).
The style in (b) avoids deep indentation and makes the program easy to read.
Notes about if-else statement
The code in (a) below has two if clauses and one else clause. Which if clause is matched by the else clause?
The indentation indicates that the else clause matches the first if clause.
However, the else clause actually matches the second if clause.
The else clause matches the most recent if clause in the same block.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
7/16
Since (i > j) is false, 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.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Notes about if-else statement
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Notes about if-else statement
The code in (a) assigns the value of a test condition to a boolean variable. It is better to assign the test value directly to the variable, as shown in (b).
To test whether a boolean variable is true or false in a test condition, it is redundant to use the equality comparison operator like the code in (a). Instead, it is better to test the boolean variable directly, as shown in (b).
8/16
Common Error
Adding a semicolon at the end of an if clause is a common mistake.
if (radius >= 0);
{
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. Using the end-of-line block style can help prevent the error.
Wrong
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Problem: Body Mass Index
Body Mass Index (BMI) is a measure of health on weight.
It can be calculated by: dividing your weight in kilograms by the square of your height in meters.
The interpretation of BMI is as follows:
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Write a program that prompts the user to enter a weight in pounds and height in inches and display the BMI.
Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters.
9/16
Problem: Body Mass Index
// 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();
final double KILOGRAMS_PER_POUND = 0.45359237; // Constant final double METERS_PER_INCH = 0.0254; // Constant
// Compute BMI
double weightInKilograms = weight * KILOGRAMS_PER_POUND;
double heightInMeters = height * METERS_PER_INCH;
double bmi = weightInKilograms / (heightInMeters * heightInMeters);
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Problem: Body Mass Index
// Display result
System.out.printf("Your BMI is %5.2f\n", bmi);
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");
} }
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Enter weight in pounds: 146 Enter height in inches: 70 Your BMI is 20.95
You are normal weight
10/16
Logical Operators
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
To test multiple conditions in the process of making a
decision, we performed these tests in separate statements or in nested if or if/else structures.
Java provides several logical operators(Boolean operators) that may be used to form complex conditions by combining simple conditions. The following table shows these operators:
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Logical Operators
11/16
Example
Here is a program that checks whether a number is
divisible by 2 and 3, divisible by 2 or 3, and divisible by 2 or 3 but not both.
import java.util.Scanner;
public class TestBoolean {
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();
System.out.println("Is " + number +
"\n\tdivisible by 2 and 3? " +
(number % 2 == 0 && number % 3 == 0) + "\n\tdivisible by 2 or 3? " +
(number % 2 == 0 || number % 3 == 0)+
"\n\tdivisible by 2 or 3, but not both? "
+ (number % 2 == 0 ^ number % 3 == 0));
} }
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Problem: Determining Leap Year?
This program first prompts the user to enter a year as an int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
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);
}
} Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science
Minia University
12/16
switch Statement
We have discussed the if single-selection and the if/else double-selection structures.
Occasionally, an algorithm contains a series of decisions in which it tests a variable or expression separately for each value the variable or expression may assume. The algorithm then takes different actions based on those values.
Java provides the switch statement to handle such decision making.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
switch- expression
is value1
switch- expression
is value2
switch- expression
is valueN
statement(s)1
statement(s)2
statement(s)N
break
statement(s)-for- default
break
break Yes
Yes
Yes
No No No
switch Statement
The syntax and flowchart of 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;
}
13/16
switch Statement:
Example:
This code segment accepts a letter grade: A, B, C, D or F, then displays the corresponding word grade: Excellent, Very Good, Good, Pass or Fail, respectively.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Scanner input = new Scanner(System.in);
System.out.print("Enter a Letter Grade : ");
char letterGrade = input.next().charAt(0);
String grade = "";
switch (letterGrade) { case ‘A’:
case ‘a’: grade = “Excellent”;
break;
case ‘B’:
case ‘b’: grade = “Very Good”;
break;
case ‘C’:
case ‘c’: grade = “Good”;
break;
case ‘D’:
case ‘d’: grade = “Pass”;
break;
case ‘F’:
case ‘f’: grade = “Fail”;
break;
default: grade = “incorrect”;
}
System.out.println(“Your Grade is: “ + grade);
switch Statement Rules
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
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. 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 keyword break is optional. The break statement immediately ends the switch statement.
The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression.
14/16
Conditional Expressions
The following statement assigns 1 to y if x is greater than 0, and -1 to y if x is less than or equal to 0.
if (x > 0) y = 1 else
y = -1;
Alternatively, we can use a conditional expression to achieve the same result, as follows:
y = (x > 0) ? 1 : -1;
The syntax of conditional expressions is shown below:
(boolean-expression) ? expression1 : expression2
The result of this conditional expression is expression1if boolean-expression is true; otherwise the result is
expression2.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Conditional Expressions (Continued)
Examples:
To assign the larger number between variable num1 and num2 to max, we can use the conditional expression:
max = (num1 > num2) ? num1 : num2;
To display the message “num is even” if num is even, and otherwise displays “num is odd”, we can use if statement:
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
Alternatively, we can use a conditional expression:
System.out.println((num % 2 == 0) ? "num is even" : "num is odd");
The symbols ? and :appear together in a conditional
expression. They form a conditional operator. It is called a ternary operator because it uses three operands.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
15/16
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 .
The precedence rule defines precedence for
operators, as shown in the next slide, which contains the operators you have learned so far.
If operators with the same precedence are next to each other, their associativity determines the order of evaluation.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Operator Precedence Chart
Operator Precedence and Associativity
16/16
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 left-associative.
For example, since + and – are of the same precedence and are left associative, the expression:
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))
Suppose a, b, and c are 1 before the assignment; after the whole expression is evaluated, a becomes 6, b becomes 6, and c becomes 5.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Operator Precedence and Associativity
Operator Precedence and Associativity: Example
Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows:
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University