Conditional Statements: Unit 5
Conditional Statements: Unit 5
Conditional statements
Summary
• The if-else and if statements
• Block of statements
• Conditional expression
• Comparison between objects
• The switch statement
1
2 UNIT 5
Semantics:
First, the condition is evaluated. If the result of the evaluation is the value true, the then-statement is
executed, otherwise the else-statement is executed. In both cases, the execution continues with the statement
immediately following the if-else statement.
Example:
int a, b;
...
if (a > b)
System.out.println("bigger value = " + a);
else
System.out.println("bigger value = " + b);
When this if-else statement is executed, the string "bigger value = " followed by the bigger one among a
and b is printed on the output channel (the monitor).
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Conditional statements 3
if (condition )
then-statement
• condition is an expression of type boolean
• then-statement is a single statement (also called the then-branch of the if statement)
Semantics:
First, the condition is evaluated. If the result of the evaluation is the value true, the then-statement is
executed, and the execution continues with the statement immediately following the if statement. Otherwise,
the execution continues directly with the statement following the if statement.
Example:
boolean found;
...
if (!found)
System.out.println("element not found");
When this if statement is executed, the string "element not found" is printed on the output channel, provided
the value of the boolean variable found is false.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
4 UNIT 5
{
double r = 5.5; // OK
i = i + 1; // OK. i is still visible
System.out.println(r); // OK. r is visible - prints 5.5
}
{
int r = 4; // OK. previous r is not visible anymore
System.out.println(a);
// OK. a is still visibile - prints Hello
}
}
i = i + 1; // OK. i is visible
System.out.println(i); // OK. i is visible - prints 3
}
}
5.9 Nested if ’s
We have a nested if when the then-branch or the else-branch of an if-else statement is again an if-else or
an if statement.
Example: Given day, month, and year, compute day, month, and year of the next day.
int day, month, year, nextDay, nextMonth, nextYear;
...
if (month == 12) {
if (day == 31) {
nextDay = 1;
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Conditional statements 5
nextMonth = 1;
nextYear = year + 1;
} else {
nextDay = Day + 1;
nextMonth = month;
nextYear = year;
}
} else {
...
}
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
6 UNIT 5
It is always possible to use a block (i.e., {..}) to disambiguate nested if-else statements. In particular, if we
want that an else refers to an if that is not the immediately preceding one, we have to enclose the immediately
preceding if in a block. For example:
if (a > 0) {
if (b > 0)
System.out.println("b positive");
} else
System.out.println("a negative");
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Conditional statements 7
Note: In general, if-else statements that make use of complex boolean conditions could be rewritten by
making use of nested if-else statements. However, to do so, it may be necessary to duplicate code. We
illustrate this in the following separately for && and ||.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
8 UNIT 5
Semantics:
Evaluate condition . If the result is true, then evaluate expression-1 and return its value, otherwise evaluate
expression-2 and return its value.
Example:
System.out.println("bigger value = " + (a > b)? a : b);
The statement in the example, which makes use of a conditional expression, is equivalent to:
if (a > b)
System.out.println("bigger value = " + a);
else
System.out.println("bigger value = " + b);
Note that the selection operator is similar to the if-else statement, but it works at a different syntactic level:
• The selection operator combines expressions and returns another expression. Hence it can be used wher-
ever an expression can be used.
• The if-else statement groups statements, and the result is a composite statement.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Conditional statements 9
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
10 UNIT 5
• a method sameOwner() to verify whether two objects of the class BankAccount have the same owner (i.e.,
the same name and surname);
• a method transferTo() that, given a bank account and an amount, transfers the amount to the bank
account, handling also the case where not enough money is available for the transfer;
• a method transferFrom() that, given a bank account and an amount, transfers the amount from the
bank account, handling also the case where not enough money is available for the transfer.
Example of usage:
public class TestBankAccount {
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Conditional statements 11
// we represent a time of the day by the total number of seconds since midnight
private int totsec;
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
12 UNIT 5
Note: If we have more than one values of the expression for which we want to execute the same statements,
we can group together different cases:
case label-1 : case label-2 : statements
break;
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Conditional statements 13
break;
case 2:
daysOfMonth = 28;
break;
default:
daysOfMonth = 0;
System.out.println("Month is not valid");
}
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
14 UNIT 5
Semantics:
1. First, expression is evaluated.
2. Then, the first i is found for which the value of label-i is equal to the value of expression .
3. If there is such an i , then statements-i , statements-i+1 , . . . are executed in sequence until the first
break statement or the end of the switch statement;
otherwise default-statements are executed.
4. The execution continues with the statement immediately following the switch statement.
Exercises
Exercise 5.1. Write a program that reads a real number and prints a message according to the following
table:
alcohol content g message
40 < g extra strong liquor
20 < g ≤ 40 strong liquor
15 < g ≤ 20 liquor
12 < g ≤ 15 strong vine
10.5 < g ≤ 12 normal vine
g ≤ 10.5 light vine
Exercise 5.2. Write a program that reads from input the lengths of the three sides of a triangle and determines
the type of the triangle according to the following algorithm:
compare each pair of sides and count home many pairs are equal
if (the number of equal pairs is 0 )
it is irregular
else if (the number of equal pairs is 1 )
it is symmetric
else
it is regular
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Conditional statements 15
Exercise 5.3. Write a program that reads from input the lengths of the three sides of a triangle and determines
the type of the triangle by using if-else statements with complex conditions.
Exercise 5.4. Design and realize a Java class Triangle to represent triangles. The following functionalities
are of interest for triangles:
• creation of a triangle, given the lenghts of the three sides;
• return of the length of the longest side, the intermediate side, and the shortest side;
• return of the perimeter of the triangle;
• return of the area of the triangle; notice that, given
p the lengths a, b, and c of the three sides of a triangle,
the area A can be computed according to A = s · (s − a) · (s − b) · (s − c), where s = (a + b + c)/2 is
the semiperimeter;
• return of a string representing the type of the triangle, which may be either regular, symmetric, or irregular.
• test whether the three sides can actually be the sides of a triangle; i.e., they respect the triangular
inequality, which states that the longest side is shorter than the sum of the other two;
Write also a program to test all functionalities of the class representing triangles.
Exercise 5.5. Write a program that reads from input the coefficients a, b, c of the quadratic equation
a · x2 + b · x + c = 0 and computes the zeroes of the equation.
Depending on the sign of the discriminant b2 − 4 · a · c, the program should print the two distinct real solutions,
the real double solution, or the two complex solutions.
Exercise 5.6. Write a program that reads from input a line of text containing a YES/NO question (without
final question mark) and prints an answer to the question according to the following rules:
1. if the line starts with a vocal, the answer is "MAYBE".
2. if the last letter of the line is ’a’, ’i’, or ’u’, the answer is "YES";
3. if the last letter of the line is ’e’ or ’o’, the answer is "NO";
4. if the last letter of the line is a character different from ’a’, ’e’, ’i’, ’o’, ’u’, the answer is
"DON’T KNOW";
Note: When two rules can be applied, the answer is obtained by concatenating the answers for the two rules.
Exercise 5.7. Realize a Java class to represent dates, on which the following functionalities are defined:
• creation of a date, given day, month, and year;
• return of day, month, and year;
• test whether two dates are equal;
• test whether a date precedes another date;
• test whether the year of a date is a leap year;
• compute the date of the next day.
Write also a program to test all functionalities of the class representing dates.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07