3 Conditional Statements
3 Conditional Statements
Control structure provide alternatives to sequential program execution and are used to alter the flow
of execution. The two most common control structures are selection repetition. In selection, the
program executes particular statements depending on one or more conditions. In repetition, the
program repeats particular statements a certain number of times depending on one or more
conditions.
SELECTION (CONDITIONAL STATEMENTS)
OPERATOR DESCRIPTION
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Logical Operators
OPERATOR DESCRIPTION
! not
&& and
|| or
Sample Code:
import java.util.Scanner;
public class ConditionalStatements_ifElse {
static Scanner console = new Scanner (System.in);
System.out.println("Enter hours:");
hours = console.nextDouble();
System.out.println();
System.out.println("Enter rate:");
rate = console.nextDouble();
System.out.println();
if (hours> 40.0){
wages = 40.0 * rate + 1.5 * rate * (hours - 40.0);
}
else {
wages =hours * rate;
}
Output:
Enter hours:
2
Enter rate:
200
The total wages are 400.0
Sample Code:
import java.util.Scanner;
public class ConditionalStatements_Nested {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
System.out.println("Enter balance:");
balance = console.nextDouble();
System.out.println();
if (balance>= 50000.00){
interestRate = 0.05;
}
else if (balance>= 25000.00){
interestRate = 0.04;
}
else if (balance>= 1000.00){
interestRate = 0.03;
}
else {
interestRate = 0.00;
}
System.out.println("The interest rate is:"+" "+
interestRate);
}
Output:
Enter balance:
20000
A selection structure, which does not require the evaluation of a logical expression.
Java’s switch structure gives the computer the power to choose from many alternatives
Sample Code:
import java.util.Scanner;
public class ConditionalStatements_Switch {
static Scanner console = new Scanner (System.in);
public static void main (String[] args){
int num;
switch (num)
{
case 0:
System.out.println("Hello");
case 1:
System.out.println("Hi");
case 2:
System.out.println("Good Day");
break;
case 3:
System.out.println("How are you?");
break;
default:
System.out.print("Sorry the number is out of range");
break;
}
}
}
Output:
import java.util.Scanner;
public class ConditionalStatements_Switch2 {
char letter;
switch (letter)
{
case 'A':
System.out.println("Hello");
break;
case 'B':
System.out.println("Hi");
break;
case 'C':
System.out.println("Good Day");
break;
default:
System.out.print("Sorry the letter is out of range");
break;
}
System.out.println("Out of switch structure");
}
}
Output:
Hi
Out of switch structure