Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 50

Chapter 3

Decisions

Decision Making In Java


Sometimes our program needs to take a
decision based on whether a particular
condition has occurred or not.  Then our
program will execute certain statements
based on this decision.

Copyright © 2016 Allan Ninyesiga Uganda Technology


and Management University
Outline
Boolean Expressions
If-statements
If –else statements
if-else ladder
Nested if statements
Switch statements

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Conditional Statements
• A conditional statement lets us choose which
statement will be executed next
• They are sometimes called selection statements
• Conditional statements give us the power to
make basic decisions
• The Java conditional statements are the:
– if and if-else statement
– switch statement

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Boolean Expressions
• A condition often uses one of Java's equality
operators or relational operators, which all
return boolean results:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to

• Note the difference between the equality


operator (==) and the assignment operator (=)
Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University
Boolean Expressions
• An if statement with its boolean condition:
if (sum > MAX)
delta = sum – MAX;

• First, the condition is evaluated: the value of sum


is either greater than the value of MAX, or it is
not
• If the condition is true, the assignment statement
is executed; if it isn't, it is skipped
• See Age.java
Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University
//********************************************************************
// Age.java Author: Lewis/Loftus
//
// Demonstrates the use of an if statement.
//********************************************************************

import java.util.Scanner;

public class Age


{
//-----------------------------------------------------------------
// Reads the user's age and prints comments accordingly.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int MINOR = 21;

Scanner scan = new Scanner (System.in);

System.out.print ("Enter your age: ");


int age = scan.nextInt();

continue

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


continue

System.out.println ("You entered: " + age);

if (age < MINOR)


System.out.println ("Youth is a wonderful thing. Enjoy.");

System.out.println ("Age is a state of mind.");


}
}

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Sample Run
Enter your age: 47
You entered: 47
continue Age is a state of mind.
System.out.println ("You entered: " + age);

if (age < MINOR)


System.out.println ("Youth is a wonderful thing. Enjoy.");

System.out.println ("Age is a state of mind.");


}
}
Another Sample Run
Enter your age: 12
You entered: 12
Youth is a wonderful thing. Enjoy.
Age is a state of mind.

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Logical Operators
• Boolean expressions can also use the following
logical operators:
! Logical NOT
&& Logical AND
|| Logical OR

• They all take boolean operands and produce


boolean results
• Logical NOT is a unary operator (it operates on
one operand)
• Logical AND and logical OR are binary operators
(each operates on two operands)
Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University
Logical NOT
• The logical NOT operation is also called logical
negation or logical complement
• If some boolean condition a is true, then !a is false;
if a is false, then !a is true
• Logical expressions can be shown using a truth table:

a !a
true false
false true

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Logical AND and Logical OR
• The logical AND expression
a && b
is true if both a and b are true, and false
otherwise

• The logical OR expression


a || b
is true if a or b or both are true, and false
otherwise
Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University
Logical AND and Logical OR
• A truth table shows all possible true-false
combinations of the terms
• Since && and || each have two operands, there are
four possible combinations of conditions a and b
a b a && b a || b
true true true true
true false false true
false true false true
false false false false

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Logical Operators
• Expressions that use logical operators can form
complex conditions
if (total < MAX+5 && !found)
System.out.println ("Processing…");

• All logical operators have lower precedence than


the relational operators
• The ! operator has higher precedence than &&
and ||

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Boolean Expressions
• Specific expressions can be evaluated using truth
tables
total < MAX found !found total < MAX && !found
false false true false
false true false false
true false true true
true true false false

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Short-Circuited Operators
• The processing of && and || is “short-circuited”
• If the left operand is sufficient to determine the
result, the right operand is not evaluated
if (count != 0 && total/count > MAX)
System.out.println ("Testing.");

• This type of processing should be used carefully

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Outline
Boolean Expressions
If-statements
If –else statements
if-else ladder
Nested if statements
Switch statements

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


If Statement
• This statement is used to make a certain decision
in our program.
• For example, sometimes we need to check if
salary is credited or not. If credited, we may need
to pay some utility bill and if salary is not
credited, we may need to wait for salary. So here,
based on the condition whether salary is credited
or not, we are taking a decision on what we need
to do.

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Syntax
If(condition)
if statement {
  Statements which will be executed if the
if (CONDITION) { condition is true
}
Statements that need to be executed always
STATEMENTS
Here if the condition is true, the code which is
} written inside the curly brackets {} of the if block
will be executed.
• Example
• We can take a look on a program which will display
a message “Success” if a particular value is greater
than 5.  It then displays a message “Executed
successfully” and complete its execution.

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Logic of an if statement

condition
evaluated

true
false
statement

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


/ * FileName :  SimpleIfStatementDemo1.java
 */
public class SimpleIfStatementDemo1
{
     public static void main(String args[])
     {
         //Declaring a variable "test" and initializing it with a value 10
         int test=10;
 
         //Checking if "test" is greater than 5
         if(test>5)
         {
             //This block will be executed only if "test" is greater than 5
             System.out.println("Success");
         }
 
         //The if block ends.
         System.out.println("Executed successfully");
     }
}
Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University
output
Out put
Success
Executed Successfully

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Outline
Boolean Expressions
If-statements
If –else statements
if-else ladder
Nested if statements
Switch statements

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


If- else statement
if (CONDITION) {
If(condition)
STATEMENTS {
  Statements which will be executed if the
condition is true
} else { }
else
{
STATEMENTS   Statements which will be executed if the
condition is false
}
} Statements that need to be executed always

Here if the condition is true, the code which is


written inside the curly brackets {} of the if block will
be executed.  If the condition is false, the code which
is written inside the curly brackets {} of the else block
will be executed.
Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University
Logic of an if-else statement
condition
evaluated

true false

statement1 statement2

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


• Example
• We can take a look on a program which will
display a message “Success” if a particular value
is greater than 5.   If this value is not greater
than 5, it will display a message “Failure”. It then
displays a message “Executed successfully” and
complete its execution.

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


/*
 * FileName :  IfElseStatementDemo1.java
 */
public class IfElseStatementDemo1
{
     public static void main(String args[])
     {
         //Declaring a variable "test" and initializing it with a value 10
         int test=10;
 
         //Checking if "test" is greater than 5
         if(test>5)
         {
             //This block will be executed only if "test" is greater than 5
             System.out.println("Success");
         }
         else
         {
             //This block will be executed only if "test" is not greater than 5
             System.out.println("Failure");
 
         }
 
         //The if else blocks ends.
         System.out.println("Executed successfully");
     }
Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University
Output
Success
Executed Success fully

•This program outputs the message “Success”


because the declared variable “test” has a value 10
which is greater than 5.
•If the value of “test” was lesser than or equal to 5,
the message “Failure” would have been displayed
instead of “Success”. 
•Class quiz. Please change the value of the variable
“test” and execute the program and observer
different results.
Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University
Outline
Boolean Expressions
If-statements
If –else statements
if-else ladder
Nested if statements
Switch statements

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


if–else-if ladder
Syntax
if (CONDITION) {
STATEMENTS
} else if (CONDITION) {
STATEMENTS
} else if (CONDITION) {
STATEMENTS
} else {
STATEMENTS
}

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Syntax
If(condition-1)
{
  Statements which will be executed if condition-1 is true
}
else if (condition-2)
{
  Statements which will be executed if condition-2 is true
}
.
.
.
else if (condition-n)
{
  Statements which will be executed if condition-n is true
}
else
{
  Statements which will be executed if none of the conditions in condition-1, condition2,…
condition-n are true.
}
Statements which will be executed always

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Syntax
If(condition-1)
{
  Statements which will be executed if condition-1 is true
}
else if (condition-2)
{
  Statements which will be executed if condition-2 is true
}
.
. As you can see in this if-else-if ladder, conditions are evaluated from top. First
. condition-1 will be evaluated and if this is true, the code inside the if block will be
else if (condition-n)
executed. If condition-1 is false, condition-2 will be evaluated.
{ If condition-2 is true, the code inside that else if block will be executed. If
  Statements which is
condition-2 will be executed
false, if condition-n
condition-3 is true This will go on like this.
will be evaluated.
} If none of the conditions are true, the code inside the else block will be executed.
else
{
  Statements which will be executed if none of the conditions in condition-1, condition2,…
condition-n are true.
}
Statements which will be executed always

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Example
• We can take a look on a program which will
• display a message “Hello” if a particular value is
equal to 1.  
• display a message “Hi” if a particular value is equal
to 2.  
• display a message “Good” if a particular value is
equal to 3.  
• display a message “No Match Found”  if none of the
above conditions are matching.

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


/*
* FileName : IfElseIfLadderDemo1.java
*/
public class IfElseIfLadderDemo1
{
public static void main(String args[])
{
//Declaring a variable "test" and initializing it with a value 2
int test=2;

if(test==1)
{
//This block will be executed only if "test" is equal to 1
System.out.println("Hello");
}
else if(test==2)
{
//This block will be executed only if "test" is equal to 2
System.out.println("Hi");

}
else if(test==3)
{
//This block will be executed only if "test" is equal to 3
System.out.println("Good");
}
else
{
System.out.println("No Match Found");
}
} Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University
Output

Hi

This program outputs the message “Hi” because the declared


variable “test” has a value 2.
If the value of “test” was 1, the message “Hello” would have
been displayed.
If the value of “test” was 3, the message “Good” would have
been displayed
If the value of “test” was any other than 1, 2, 3, the message
“No Match Found” would have been displayed
Class Quiz: Please change the value of the variable “test”
accordingly and execute the program and see the different
outputs.

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Outline
Boolean Expressions
If-statements
If –else statements
if-else ladder
Nested if statements
Switch statements

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Nested if Statements
•The statement executed as a result of an if or else
clause could be another if statement

•These are called nested if statements

•Braces can be used to specify the if statement to


which an else clause belongs

•See MinOfThree.java

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


//********************************************************************
// MinOfThree.java
//
// Demonstrates the use of nested if statements.
//********************************************************************

import java.util.Scanner;

public class MinOfThree


{
//-----------------------------------------------------------------
// Reads three integers from the user and determines the smallest
// value.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int num1, num2, num3, min = 0;

Scanner scan = new Scanner (System.in);

System.out.println ("Enter three integers: ");


num1 = scan.nextInt();
num2 = scan.nextInt();
num3 = scan.nextInt();

continue

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


continue

if (num1 < num2)


if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;

System.out.println ("Minimum value: " + min);


}
}

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


continue Sample Run
if (num1 < num2) Enter three integers:
if (num1 < num3) 84 69 90
min = num1; Minimum value: 69
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;

System.out.println ("Minimum value: " + min);


}
}

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Outline
Boolean Expressions
If-statements
If –else statements
if-else ladder
Nested if statements
Switch statements

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


The switch Statement
• The switch statement provides another way to
decide which statement to execute next
• The switch statement evaluates an expression,
then attempts to match the result to one of
several possible cases
• Each case contains a value and a list of
statements
• The flow of control transfers to statement
associated with the first case value that matches
Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University
The switch Statement
• The general syntax of a switch statement is:
switch switch ( expression )
and {
case case value1 :
are statement-list1
reserved case value2 :
words statement-list2
case value3 :
statement-list3 If expression
case ... matches value2,
control jumps
} to here

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


The switch Statement
• Often a break statement is used as the last statement
in each case's statement list
• A break statement causes control to transfer to the
end of the switch statement
• If a break statement is not used, the flow of control
will continue into the next case
• Sometimes this may be appropriate, but often we
want to execute only the statements associated with
one case

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


• An example of a switch statement:

The switch Statement


switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


The switch Statement
• A switch statement can have an optional default
case
• The default case has no associated value and simply
uses the reserved word default
• If the default case is present, control will transfer to
it if no other case value matches
• If there is no default case, and no other value
matches, control falls through to the statement after
the switch

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


The switch Statement
• The type of a switch expression must be integers,
characters
• You cannot use a switch with floating point values

• See GradeReport.java

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


//********************************************************************
// GradeReport.java Author: Lewis/Loftus
//
// Demonstrates the use of a switch statement.
//********************************************************************

import java.util.Scanner;

public class GradeReport


{
//-----------------------------------------------------------------
// Reads a grade from the user and prints comments accordingly.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int grade, category;

Scanner scan = new Scanner (System.in);

System.out.print ("Enter a numeric grade (0 to 100): ");


grade = scan.nextInt();

category = grade / 10;

System.out.print ("That grade is ");

continue

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


continue

switch (category)
{
case 10:
System.out.println ("a perfect score. Well done.");
break;
case 9:
System.out.println ("well above average. Excellent.");
break;
case 8:
System.out.println ("above average. Nice job.");
break;
case 7:
System.out.println ("average.");
break;
case 6:
System.out.println ("below average. You should see the");
System.out.println ("instructor to clarify the material "
+ "presented in class.");
break;
default:
System.out.println ("not passing.");
}
}
}

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


continue Sample Run
switch (category)
Enter a numeric grade (0 to 100): 91
{ That grade is well above average. Excellent.
case 10:
System.out.println ("a perfect score. Well done.");
break;
case 9:
System.out.println ("well above average. Excellent.");
break;
case 8:
System.out.println ("above average. Nice job.");
break;
case 7:
System.out.println ("average.");
break;
case 6:
System.out.println ("below average. You should see the");
System.out.println ("instructor to clarify the material "
+ "presented in class.");
break;
default:
System.out.println ("not passing.");
}
}
}

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University


Summary
• Lecture focused on: Dealing with Decision making
- Boolean Expressions

- If-statements

- If –else statements

- if-else ladder

- Nested if statements

- Switch statements

Copyright © 2016 Allan Ninyesiga Uganda Technology and Management University

You might also like