# The if-else statement

• Introduction

• The if-statement has a "cousin statement" (closely related statement) called the if-else-statement

• Motivational Example

• Consider the following problem:

• Given 3 variables" x, y and max

• The variables x and y already have some value assigned to them

• Determine the largest value between x and y and assign this largest value to the variable max

• A poor solution is:

 ``` if ( x > y ) max = x; if ( x <= y ) max = y; ```

• There are 2 problems with this approach:

• We need to write 2 separate conditions - it is more error prone.

• If for one reason or another, the first if-statement modifies the values in the variables x or y, then the condition in the second if-statement is changed and the program will become incorrect...

• This problem can better be solved using the if-else-statement

IMPORTANT

• The if-else   statement

• The syntax of the if-else-statement is:

 ``` if ( Condition ) ONE-single-statement1 // "then part" else ONE-single-statement2 // "else part" ```

• The meaning of the if-else-statement is:

 Evaluate the Condition-clause If the Condition-clause is TRUE, then execute statement1 and SKIP statement2 If the Condition-clause is FALSE, then execute SKIP statement1 and execute statement2

• The statement statement1 is called the "then" part (for obvious reasons).

• The statement statement2 is called the "else" part (for obvious reasons).

• NOTE: statement1 has a ";"

• NOTE: If you use a compound statement, then statement1; (including the ";") is replaced by the compound statement !!!

• Example of using the if-else   statement

• Let us write the solution of the following problem using the if-else   statement:

• Given 3 variables" x, y and max

• The variables x and y already have some value assigned to them

• Determine the largest value between x and y and assign this largest value to the variable max

• Solution:

 ``` public class FindMax { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x, y; int max; x = in.nextInt(); y = in.nextInt(); if ( x > y ) // if ( Condition) max = x ; // ONE-statement else // else max = y ; // ONE-statement } } ```

• Example Program: (Demo above code)

• NOTE: if we use compound statements for the "then" and "else" parts, we would write:

 ``` public class FindMax { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x, y; int max; x = in.nextInt(); y = in.nextInt(); if ( x > y ) { // { \ max = x ; // max = x; +-> one (compound) statement } // } / else } // { \ max = y ; // max = y; +-> one (compound) statement } // } } } ```